id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_815_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC IIIII N N %
% C I NN N %
% C I N N N %
% C I N NN %
% CCCC IIIII N N %
% %
% %
% Read/Write Kodak Cineon Image Format %
% Cineon Image Format is a subset of SMTPE CIN %
% %
% %
% Software Design %
% Cristy %
% Kelly Bergougnoux %
% October 2003 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Cineon image file format draft is available at
% http://www.cineon.com/ff_draft.php.
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/module.h"
/*
Typedef declaration.
*/
typedef struct _CINDataFormatInfo
{
unsigned char
interleave,
packing,
sign,
sense;
size_t
line_pad,
channel_pad;
unsigned char
reserve[20];
} CINDataFormatInfo;
typedef struct _CINFileInfo
{
size_t
magic,
image_offset,
generic_length,
industry_length,
user_length,
file_size;
char
version[8],
filename[100],
create_date[12],
create_time[12],
reserve[36];
} CINFileInfo;
typedef struct _CINFilmInfo
{
char
id,
type,
offset,
reserve1;
size_t
prefix,
count;
char
format[32];
size_t
frame_position;
float
frame_rate;
char
frame_id[32],
slate_info[200],
reserve[740];
} CINFilmInfo;
typedef struct _CINImageChannel
{
unsigned char
designator[2],
bits_per_pixel,
reserve;
size_t
pixels_per_line,
lines_per_image;
float
min_data,
min_quantity,
max_data,
max_quantity;
} CINImageChannel;
typedef struct _CINImageInfo
{
unsigned char
orientation,
number_channels,
reserve1[2];
CINImageChannel
channel[8];
float
white_point[2],
red_primary_chromaticity[2],
green_primary_chromaticity[2],
blue_primary_chromaticity[2];
char
label[200],
reserve[28];
} CINImageInfo;
typedef struct _CINOriginationInfo
{
ssize_t
x_offset,
y_offset;
char
filename[100],
create_date[12],
create_time[12],
device[64],
model[32],
serial[32];
float
x_pitch,
y_pitch,
gamma;
char
reserve[40];
} CINOriginationInfo;
typedef struct _CINUserInfo
{
char
id[32];
} CINUserInfo;
typedef struct CINInfo
{
CINFileInfo
file;
CINImageInfo
image;
CINDataFormatInfo
data_format;
CINOriginationInfo
origination;
CINFilmInfo
film;
CINUserInfo
user;
} CINInfo;
/*
Forward declaractions.
*/
static MagickBooleanType
WriteCINImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s C I N E O N %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsCIN() returns MagickTrue if the image format type, identified by the magick
% string, is CIN.
%
% The format of the IsCIN method is:
%
% MagickBooleanType IsCIN(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 IsCIN(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\200\052\137\327",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadCINImage() reads an CIN X image file and returns it. It allocates
% the memory necessary for the new Image structure and returns a point to the
% new image.
%
% The format of the ReadCINImage method is:
%
% Image *ReadCINImage(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 size_t GetBytesPerRow(size_t columns,
size_t samples_per_pixel,size_t bits_per_pixel,
MagickBooleanType pad)
{
size_t
bytes_per_row;
switch (bits_per_pixel)
{
case 1:
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
case 8:
default:
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
case 10:
{
if (pad == MagickFalse)
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
bytes_per_row=4*(((size_t) (32*((samples_per_pixel*columns+2)/3))+31)/32);
break;
}
case 12:
{
if (pad == MagickFalse)
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
bytes_per_row=2*(((size_t) (16*samples_per_pixel*columns)+15)/16);
break;
}
case 16:
{
bytes_per_row=2*(((size_t) samples_per_pixel*columns*
bits_per_pixel+8)/16);
break;
}
case 32:
{
bytes_per_row=4*(((size_t) samples_per_pixel*columns*
bits_per_pixel+31)/32);
break;
}
case 64:
{
bytes_per_row=8*(((size_t) samples_per_pixel*columns*
bits_per_pixel+63)/64);
break;
}
}
return(bytes_per_row);
}
static inline MagickBooleanType IsFloatDefined(const float value)
{
union
{
unsigned int
unsigned_value;
double
float_value;
} quantum;
quantum.unsigned_value=0U;
quantum.float_value=value;
if (quantum.unsigned_value == 0U)
return(MagickFalse);
return(MagickTrue);
}
static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType 1
#define RGBColorType 3
char
property[MagickPathExtent];
CINInfo
cin;
const unsigned char
*pixels;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
register Quantum
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
magick[4];
/*
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);
}
/*
File information.
*/
offset=0;
count=ReadBlob(image,4,magick);
offset+=count;
if ((count != 4) ||
((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
memset(&cin,0,sizeof(cin));
image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
(magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
cin.file.image_offset=ReadBlobLong(image);
offset+=4;
cin.file.generic_length=ReadBlobLong(image);
offset+=4;
cin.file.industry_length=ReadBlobLong(image);
offset+=4;
cin.file.user_length=ReadBlobLong(image);
offset+=4;
cin.file.file_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
(void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
(void) SetImageProperty(image,"dpx:file.version",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
(void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
(void) SetImageProperty(image,"dpx:file.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) CopyMagickString(property,cin.file.create_date,
sizeof(cin.file.create_date));
(void) SetImageProperty(image,"dpx:file.create_date",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
(void) CopyMagickString(property,cin.file.create_time,
sizeof(cin.file.create_time));
(void) SetImageProperty(image,"dpx:file.create_time",property,exception);
offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
/*
Image information.
*/
cin.image.orientation=(unsigned char) ReadBlobByte(image);
offset++;
if (cin.image.orientation != (unsigned char) (~0))
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
cin.image.orientation);
switch (cin.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
cin.image.number_channels=(unsigned char) ReadBlobByte(image);
offset++;
offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].lines_per_image=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].min_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].min_quantity=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_quantity=ReadBlobFloat(image);
offset+=4;
}
cin.image.white_point[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
image->chromaticity.white_point.x=cin.image.white_point[0];
cin.image.white_point[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
image->chromaticity.white_point.y=cin.image.white_point[1];
cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
(void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
(void) SetImageProperty(image,"dpx:image.label",property,exception);
offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Image data format information.
*/
cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.packing=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sign=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sense=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.line_pad=ReadBlobLong(image);
offset+=4;
cin.data_format.channel_pad=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Image origination information.
*/
cin.origination.x_offset=ReadBlobSignedLong(image);
offset+=4;
if ((size_t) cin.origination.x_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g",
(double) cin.origination.x_offset);
cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.y_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g",
(double) cin.origination.y_offset);
offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
(void) CopyMagickString(property,cin.origination.filename,
sizeof(cin.origination.filename));
(void) SetImageProperty(image,"dpx:origination.filename",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) CopyMagickString(property,cin.origination.create_date,
sizeof(cin.origination.create_date));
(void) SetImageProperty(image,"dpx:origination.create_date",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
(void) CopyMagickString(property,cin.origination.create_time,
sizeof(cin.origination.create_time));
(void) SetImageProperty(image,"dpx:origination.create_time",property,
exception);
offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
(void) CopyMagickString(property,cin.origination.device,
sizeof(cin.origination.device));
(void) SetImageProperty(image,"dpx:origination.device",property,exception);
offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
(void) CopyMagickString(property,cin.origination.model,
sizeof(cin.origination.model));
(void) SetImageProperty(image,"dpx:origination.model",property,exception);
(void) memset(cin.origination.serial,0,
sizeof(cin.origination.serial));
offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
(void) CopyMagickString(property,cin.origination.serial,
sizeof(cin.origination.serial));
(void) SetImageProperty(image,"dpx:origination.serial",property,exception);
cin.origination.x_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.y_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
image->gamma=cin.origination.gamma;
offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
int
c;
/*
Image film information.
*/
cin.film.id=ReadBlobByte(image);
offset++;
c=cin.film.id;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id);
cin.film.type=ReadBlobByte(image);
offset++;
c=cin.film.type;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type);
cin.film.offset=ReadBlobByte(image);
offset++;
c=cin.film.offset;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.offset","%d",
cin.film.offset);
cin.film.reserve1=ReadBlobByte(image);
offset++;
cin.film.prefix=ReadBlobLong(image);
offset+=4;
if (cin.film.prefix != ~0UL)
(void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double)
cin.film.prefix);
cin.film.count=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
(void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));
(void) SetImageProperty(image,"dpx:film.format",property,exception);
cin.film.frame_position=ReadBlobLong(image);
offset+=4;
if (cin.film.frame_position != ~0UL)
(void) FormatImageProperty(image,"dpx:film.frame_position","%.20g",
(double) cin.film.frame_position);
cin.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
cin.film.frame_rate);
offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
(void) CopyMagickString(property,cin.film.frame_id,
sizeof(cin.film.frame_id));
(void) SetImageProperty(image,"dpx:film.frame_id",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
(void) CopyMagickString(property,cin.film.slate_info,
sizeof(cin.film.slate_info));
(void) SetImageProperty(image,"dpx:film.slate_info",property,exception);
offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
}
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
StringInfo
*profile;
/*
User defined data.
*/
if (cin.file.user_length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
profile=BlobToStringInfo((const unsigned char *) NULL,
cin.file.user_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user.data",profile,exception);
profile=DestroyStringInfo(profile);
}
image->depth=cin.image.channel[0].bits_per_pixel;
image->columns=cin.image.channel[0].pixels_per_line;
image->rows=cin.image.channel[0].lines_per_image;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
if (offset < (MagickOffsetType) cin.file.image_offset)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
/*
Convert CIN raster image to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
length=GetQuantumExtent(image,quantum_info,quantum_type);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
if (cin.image.number_channels == 1)
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != length)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
SetImageColorspace(image,LogColorspace,exception);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterCINImage() adds attributes for the CIN image format to the list of
% 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 RegisterCINImage method is:
%
% size_t RegisterCINImage(void)
%
*/
ModuleExport size_t RegisterCINImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("CIN","CIN","Cineon Image File");
entry->decoder=(DecodeImageHandler *) ReadCINImage;
entry->encoder=(EncodeImageHandler *) WriteCINImage;
entry->magick=(IsImageFormatHandler *) IsCIN;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterCINImage() removes format registrations made by the CIN module
% from the list of supported formats.
%
% The format of the UnregisterCINImage method is:
%
% UnregisterCINImage(void)
%
*/
ModuleExport void UnregisterCINImage(void)
{
(void) UnregisterMagickInfo("CINEON");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e C I N E O N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteCINImage() writes an image in CIN encoded image format.
%
% The format of the WriteCINImage method is:
%
% MagickBooleanType WriteCINImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline const char *GetCINProperty(const ImageInfo *image_info,
const Image *image,const char *property,ExceptionInfo *exception)
{
const char
*value;
value=GetImageOption(image_info,property);
if (value != (const char *) NULL)
return(value);
return(GetImageProperty(image,property,exception));
}
static MagickBooleanType WriteCINImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
timestamp[MagickPathExtent];
const char
*value;
CINInfo
cin;
const StringInfo
*profile;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register const Quantum
*p;
register ssize_t
i;
size_t
length;
ssize_t
count,
y;
struct tm
local_time;
time_t
seconds;
unsigned char
*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);
if (image->colorspace != LogColorspace)
(void) TransformImageColorspace(image,LogColorspace,exception);
/*
Write image information.
*/
(void) memset(&cin,0,sizeof(cin));
offset=0;
cin.file.magic=0x802A5FD7UL;
offset+=WriteBlobLong(image,(unsigned int) cin.file.magic);
cin.file.image_offset=0x800;
offset+=WriteBlobLong(image,(unsigned int) cin.file.image_offset);
cin.file.generic_length=0x400;
offset+=WriteBlobLong(image,(unsigned int) cin.file.generic_length);
cin.file.industry_length=0x400;
offset+=WriteBlobLong(image,(unsigned int) cin.file.industry_length);
cin.file.user_length=0x00;
profile=GetImageProfile(image,"dpx:user.data");
if (profile != (StringInfo *) NULL)
{
cin.file.user_length+=(size_t) GetStringInfoLength(profile);
cin.file.user_length=(((cin.file.user_length+0x2000-1)/0x2000)*0x2000);
}
offset+=WriteBlobLong(image,(unsigned int) cin.file.user_length);
cin.file.file_size=4*image->columns*image->rows+0x2000;
offset+=WriteBlobLong(image,(unsigned int) cin.file.file_size);
(void) CopyMagickString(cin.file.version,"V4.5",sizeof(cin.file.version));
offset+=WriteBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
value=GetCINProperty(image_info,image,"dpx:file.filename",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.file.filename,value,sizeof(cin.file.filename));
else
(void) CopyMagickString(cin.file.filename,image->filename,
sizeof(cin.file.filename));
offset+=WriteBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
seconds=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(&seconds,&local_time);
#else
(void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
#endif
(void) memset(timestamp,0,sizeof(timestamp));
(void) strftime(timestamp,MagickPathExtent,"%Y:%m:%d:%H:%M:%S%Z",&local_time);
(void) memset(cin.file.create_date,0,sizeof(cin.file.create_date));
(void) CopyMagickString(cin.file.create_date,timestamp,11);
offset+=WriteBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) memset(cin.file.create_time,0,sizeof(cin.file.create_time));
(void) CopyMagickString(cin.file.create_time,timestamp+11,11);
offset+=WriteBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
offset+=WriteBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
cin.image.orientation=0x00;
offset+=WriteBlobByte(image,cin.image.orientation);
cin.image.number_channels=3;
offset+=WriteBlobByte(image,cin.image.number_channels);
offset+=WriteBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=0; /* universal metric */
offset+=WriteBlobByte(image,cin.image.channel[0].designator[0]);
cin.image.channel[i].designator[1]=(unsigned char) (i > 3 ? 0 : i+1); /* channel color */;
offset+=WriteBlobByte(image,cin.image.channel[1].designator[0]);
cin.image.channel[i].bits_per_pixel=(unsigned char) image->depth;
offset+=WriteBlobByte(image,cin.image.channel[0].bits_per_pixel);
offset+=WriteBlobByte(image,cin.image.channel[0].reserve);
cin.image.channel[i].pixels_per_line=image->columns;
offset+=WriteBlobLong(image,(unsigned int)
cin.image.channel[0].pixels_per_line);
cin.image.channel[i].lines_per_image=image->rows;
offset+=WriteBlobLong(image,(unsigned int)
cin.image.channel[0].lines_per_image);
cin.image.channel[i].min_data=0;
offset+=WriteBlobFloat(image,cin.image.channel[0].min_data);
cin.image.channel[i].min_quantity=0.0;
offset+=WriteBlobFloat(image,cin.image.channel[0].min_quantity);
cin.image.channel[i].max_data=(float) ((MagickOffsetType)
GetQuantumRange(image->depth));
offset+=WriteBlobFloat(image,cin.image.channel[0].max_data);
cin.image.channel[i].max_quantity=2.048f;
offset+=WriteBlobFloat(image,cin.image.channel[0].max_quantity);
}
offset+=WriteBlobFloat(image,image->chromaticity.white_point.x);
offset+=WriteBlobFloat(image,image->chromaticity.white_point.y);
offset+=WriteBlobFloat(image,image->chromaticity.red_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.red_primary.y);
offset+=WriteBlobFloat(image,image->chromaticity.green_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.green_primary.y);
offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.x);
offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.y);
value=GetCINProperty(image_info,image,"dpx:image.label",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.image.label,value,sizeof(cin.image.label));
offset+=WriteBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
offset+=WriteBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Write data format information.
*/
cin.data_format.interleave=0; /* pixel interleave (rgbrgbr...) */
offset+=WriteBlobByte(image,cin.data_format.interleave);
cin.data_format.packing=5; /* packing ssize_tword (32bit) boundaries */
offset+=WriteBlobByte(image,cin.data_format.packing);
cin.data_format.sign=0; /* unsigned data */
offset+=WriteBlobByte(image,cin.data_format.sign);
cin.data_format.sense=0; /* image sense: positive image */
offset+=WriteBlobByte(image,cin.data_format.sense);
cin.data_format.line_pad=0;
offset+=WriteBlobLong(image,(unsigned int) cin.data_format.line_pad);
cin.data_format.channel_pad=0;
offset+=WriteBlobLong(image,(unsigned int) cin.data_format.channel_pad);
offset+=WriteBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Write origination information.
*/
cin.origination.x_offset=0UL;
value=GetCINProperty(image_info,image,"dpx:origination.x_offset",exception);
if (value != (const char *) NULL)
cin.origination.x_offset=(ssize_t) StringToLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.origination.x_offset);
cin.origination.y_offset=0UL;
value=GetCINProperty(image_info,image,"dpx:origination.y_offset",exception);
if (value != (const char *) NULL)
cin.origination.y_offset=(ssize_t) StringToLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.origination.y_offset);
value=GetCINProperty(image_info,image,"dpx:origination.filename",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.filename,value,
sizeof(cin.origination.filename));
else
(void) CopyMagickString(cin.origination.filename,image->filename,
sizeof(cin.origination.filename));
offset+=WriteBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
seconds=time((time_t *) NULL);
(void) memset(timestamp,0,sizeof(timestamp));
(void) strftime(timestamp,MagickPathExtent,"%Y:%m:%d:%H:%M:%S%Z",&local_time);
(void) memset(cin.origination.create_date,0,
sizeof(cin.origination.create_date));
(void) CopyMagickString(cin.origination.create_date,timestamp,11);
offset+=WriteBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) memset(cin.origination.create_time,0,
sizeof(cin.origination.create_time));
(void) CopyMagickString(cin.origination.create_time,timestamp+11,15);
offset+=WriteBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
value=GetCINProperty(image_info,image,"dpx:origination.device",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.device,value,
sizeof(cin.origination.device));
offset+=WriteBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
value=GetCINProperty(image_info,image,"dpx:origination.model",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.model,value,
sizeof(cin.origination.model));
offset+=WriteBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
value=GetCINProperty(image_info,image,"dpx:origination.serial",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.origination.serial,value,
sizeof(cin.origination.serial));
offset+=WriteBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
cin.origination.x_pitch=0.0f;
value=GetCINProperty(image_info,image,"dpx:origination.x_pitch",exception);
if (value != (const char *) NULL)
cin.origination.x_pitch=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.origination.x_pitch);
cin.origination.y_pitch=0.0f;
value=GetCINProperty(image_info,image,"dpx:origination.y_pitch",exception);
if (value != (const char *) NULL)
cin.origination.y_pitch=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.origination.y_pitch);
cin.origination.gamma=image->gamma;
offset+=WriteBlobFloat(image,cin.origination.gamma);
offset+=WriteBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
/*
Image film information.
*/
cin.film.id=0;
value=GetCINProperty(image_info,image,"dpx:film.id",exception);
if (value != (const char *) NULL)
cin.film.id=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.id);
cin.film.type=0;
value=GetCINProperty(image_info,image,"dpx:film.type",exception);
if (value != (const char *) NULL)
cin.film.type=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.type);
cin.film.offset=0;
value=GetCINProperty(image_info,image,"dpx:film.offset",exception);
if (value != (const char *) NULL)
cin.film.offset=(char) StringToLong(value);
offset+=WriteBlobByte(image,(unsigned char) cin.film.offset);
offset+=WriteBlobByte(image,(unsigned char) cin.film.reserve1);
cin.film.prefix=0UL;
value=GetCINProperty(image_info,image,"dpx:film.prefix",exception);
if (value != (const char *) NULL)
cin.film.prefix=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.prefix);
cin.film.count=0UL;
value=GetCINProperty(image_info,image,"dpx:film.count",exception);
if (value != (const char *) NULL)
cin.film.count=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.count);
value=GetCINProperty(image_info,image,"dpx:film.format",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.format,value,sizeof(cin.film.format));
offset+=WriteBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
cin.film.frame_position=0UL;
value=GetCINProperty(image_info,image,"dpx:film.frame_position",exception);
if (value != (const char *) NULL)
cin.film.frame_position=StringToUnsignedLong(value);
offset+=WriteBlobLong(image,(unsigned int) cin.film.frame_position);
cin.film.frame_rate=0.0f;
value=GetCINProperty(image_info,image,"dpx:film.frame_rate",exception);
if (value != (const char *) NULL)
cin.film.frame_rate=StringToDouble(value,(char **) NULL);
offset+=WriteBlobFloat(image,cin.film.frame_rate);
value=GetCINProperty(image_info,image,"dpx:film.frame_id",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.frame_id,value,sizeof(cin.film.frame_id));
offset+=WriteBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
value=GetCINProperty(image_info,image,"dpx:film.slate_info",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(cin.film.slate_info,value,
sizeof(cin.film.slate_info));
offset+=WriteBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
offset+=WriteBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
if (profile != (StringInfo *) NULL)
offset+=WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
while (offset < (MagickOffsetType) cin.file.image_offset)
offset+=WriteBlobByte(image,0x00);
/*
Convert pixel packets to CIN raster image.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->quantum=32;
quantum_info->pack=MagickFalse;
quantum_type=RGBQuantum;
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
(void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-400/c/bad_815_0 |
crossvul-cpp_data_bad_898_0 | /*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2001-2003, David Janssens
* Copyright (c) 2002-2003, Yannick Verschueren
* Copyright (c) 2003-2007, Francois-Olivier Devaux
* Copyright (c) 2003-2014, Antonin Descampe
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* Copyright (c) 2006-2007, Parvatha Elangovan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_apps_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "openjpeg.h"
#include "convert.h"
typedef struct {
OPJ_UINT16 bfType; /* 'BM' for Bitmap (19776) */
OPJ_UINT32 bfSize; /* Size of the file */
OPJ_UINT16 bfReserved1; /* Reserved : 0 */
OPJ_UINT16 bfReserved2; /* Reserved : 0 */
OPJ_UINT32 bfOffBits; /* Offset */
} OPJ_BITMAPFILEHEADER;
typedef struct {
OPJ_UINT32 biSize; /* Size of the structure in bytes */
OPJ_UINT32 biWidth; /* Width of the image in pixels */
OPJ_UINT32 biHeight; /* Height of the image in pixels */
OPJ_UINT16 biPlanes; /* 1 */
OPJ_UINT16 biBitCount; /* Number of color bits by pixels */
OPJ_UINT32 biCompression; /* Type of encoding 0: none 1: RLE8 2: RLE4 */
OPJ_UINT32 biSizeImage; /* Size of the image in bytes */
OPJ_UINT32 biXpelsPerMeter; /* Horizontal (X) resolution in pixels/meter */
OPJ_UINT32 biYpelsPerMeter; /* Vertical (Y) resolution in pixels/meter */
OPJ_UINT32 biClrUsed; /* Number of color used in the image (0: ALL) */
OPJ_UINT32 biClrImportant; /* Number of important color (0: ALL) */
OPJ_UINT32 biRedMask; /* Red channel bit mask */
OPJ_UINT32 biGreenMask; /* Green channel bit mask */
OPJ_UINT32 biBlueMask; /* Blue channel bit mask */
OPJ_UINT32 biAlphaMask; /* Alpha channel bit mask */
OPJ_UINT32 biColorSpaceType; /* Color space type */
OPJ_UINT8 biColorSpaceEP[36]; /* Color space end points */
OPJ_UINT32 biRedGamma; /* Red channel gamma */
OPJ_UINT32 biGreenGamma; /* Green channel gamma */
OPJ_UINT32 biBlueGamma; /* Blue channel gamma */
OPJ_UINT32 biIntent; /* Intent */
OPJ_UINT32 biIccProfileData; /* ICC profile data */
OPJ_UINT32 biIccProfileSize; /* ICC profile size */
OPJ_UINT32 biReserved; /* Reserved */
} OPJ_BITMAPINFOHEADER;
static void opj_applyLUT8u_8u32s_C1R(
OPJ_UINT8 const* pSrc, OPJ_INT32 srcStride,
OPJ_INT32* pDst, OPJ_INT32 dstStride,
OPJ_UINT8 const* pLUT,
OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 y;
for (y = height; y != 0U; --y) {
OPJ_UINT32 x;
for (x = 0; x < width; x++) {
pDst[x] = (OPJ_INT32)pLUT[pSrc[x]];
}
pSrc += srcStride;
pDst += dstStride;
}
}
static void opj_applyLUT8u_8u32s_C1P3R(
OPJ_UINT8 const* pSrc, OPJ_INT32 srcStride,
OPJ_INT32* const* pDst, OPJ_INT32 const* pDstStride,
OPJ_UINT8 const* const* pLUT,
OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 y;
OPJ_INT32* pR = pDst[0];
OPJ_INT32* pG = pDst[1];
OPJ_INT32* pB = pDst[2];
OPJ_UINT8 const* pLUT_R = pLUT[0];
OPJ_UINT8 const* pLUT_G = pLUT[1];
OPJ_UINT8 const* pLUT_B = pLUT[2];
for (y = height; y != 0U; --y) {
OPJ_UINT32 x;
for (x = 0; x < width; x++) {
OPJ_UINT8 idx = pSrc[x];
pR[x] = (OPJ_INT32)pLUT_R[idx];
pG[x] = (OPJ_INT32)pLUT_G[idx];
pB[x] = (OPJ_INT32)pLUT_B[idx];
}
pSrc += srcStride;
pR += pDstStride[0];
pG += pDstStride[1];
pB += pDstStride[2];
}
}
static void bmp24toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride,
opj_image_t* image)
{
int index;
OPJ_UINT32 width, height;
OPJ_UINT32 x, y;
const OPJ_UINT8 *pSrc = NULL;
width = image->comps[0].w;
height = image->comps[0].h;
index = 0;
pSrc = pData + (height - 1U) * stride;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
image->comps[0].data[index] = (OPJ_INT32)pSrc[3 * x + 2]; /* R */
image->comps[1].data[index] = (OPJ_INT32)pSrc[3 * x + 1]; /* G */
image->comps[2].data[index] = (OPJ_INT32)pSrc[3 * x + 0]; /* B */
index++;
}
pSrc -= stride;
}
}
static void bmp_mask_get_shift_and_prec(OPJ_UINT32 mask, OPJ_UINT32* shift,
OPJ_UINT32* prec)
{
OPJ_UINT32 l_shift, l_prec;
l_shift = l_prec = 0U;
if (mask != 0U) {
while ((mask & 1U) == 0U) {
mask >>= 1;
l_shift++;
}
while (mask & 1U) {
mask >>= 1;
l_prec++;
}
}
*shift = l_shift;
*prec = l_prec;
}
static void bmpmask32toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride,
opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask,
OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask)
{
int index;
OPJ_UINT32 width, height;
OPJ_UINT32 x, y;
const OPJ_UINT8 *pSrc = NULL;
OPJ_BOOL hasAlpha;
OPJ_UINT32 redShift, redPrec;
OPJ_UINT32 greenShift, greenPrec;
OPJ_UINT32 blueShift, bluePrec;
OPJ_UINT32 alphaShift, alphaPrec;
width = image->comps[0].w;
height = image->comps[0].h;
hasAlpha = image->numcomps > 3U;
bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec);
bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec);
bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec);
bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec);
image->comps[0].bpp = redPrec;
image->comps[0].prec = redPrec;
image->comps[1].bpp = greenPrec;
image->comps[1].prec = greenPrec;
image->comps[2].bpp = bluePrec;
image->comps[2].prec = bluePrec;
if (hasAlpha) {
image->comps[3].bpp = alphaPrec;
image->comps[3].prec = alphaPrec;
}
index = 0;
pSrc = pData + (height - 1U) * stride;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
OPJ_UINT32 value = 0U;
value |= ((OPJ_UINT32)pSrc[4 * x + 0]) << 0;
value |= ((OPJ_UINT32)pSrc[4 * x + 1]) << 8;
value |= ((OPJ_UINT32)pSrc[4 * x + 2]) << 16;
value |= ((OPJ_UINT32)pSrc[4 * x + 3]) << 24;
image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >>
redShift); /* R */
image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >>
greenShift); /* G */
image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >>
blueShift); /* B */
if (hasAlpha) {
image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >>
alphaShift); /* A */
}
index++;
}
pSrc -= stride;
}
}
static void bmpmask16toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride,
opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask,
OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask)
{
int index;
OPJ_UINT32 width, height;
OPJ_UINT32 x, y;
const OPJ_UINT8 *pSrc = NULL;
OPJ_BOOL hasAlpha;
OPJ_UINT32 redShift, redPrec;
OPJ_UINT32 greenShift, greenPrec;
OPJ_UINT32 blueShift, bluePrec;
OPJ_UINT32 alphaShift, alphaPrec;
width = image->comps[0].w;
height = image->comps[0].h;
hasAlpha = image->numcomps > 3U;
bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec);
bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec);
bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec);
bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec);
image->comps[0].bpp = redPrec;
image->comps[0].prec = redPrec;
image->comps[1].bpp = greenPrec;
image->comps[1].prec = greenPrec;
image->comps[2].bpp = bluePrec;
image->comps[2].prec = bluePrec;
if (hasAlpha) {
image->comps[3].bpp = alphaPrec;
image->comps[3].prec = alphaPrec;
}
index = 0;
pSrc = pData + (height - 1U) * stride;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
OPJ_UINT32 value = 0U;
value |= ((OPJ_UINT32)pSrc[2 * x + 0]) << 0;
value |= ((OPJ_UINT32)pSrc[2 * x + 1]) << 8;
image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >>
redShift); /* R */
image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >>
greenShift); /* G */
image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >>
blueShift); /* B */
if (hasAlpha) {
image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >>
alphaShift); /* A */
}
index++;
}
pSrc -= stride;
}
}
static opj_image_t* bmp8toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride,
opj_image_t* image, OPJ_UINT8 const* const* pLUT)
{
OPJ_UINT32 width, height;
const OPJ_UINT8 *pSrc = NULL;
width = image->comps[0].w;
height = image->comps[0].h;
pSrc = pData + (height - 1U) * stride;
if (image->numcomps == 1U) {
opj_applyLUT8u_8u32s_C1R(pSrc, -(OPJ_INT32)stride, image->comps[0].data,
(OPJ_INT32)width, pLUT[0], width, height);
} else {
OPJ_INT32* pDst[3];
OPJ_INT32 pDstStride[3];
pDst[0] = image->comps[0].data;
pDst[1] = image->comps[1].data;
pDst[2] = image->comps[2].data;
pDstStride[0] = (OPJ_INT32)width;
pDstStride[1] = (OPJ_INT32)width;
pDstStride[2] = (OPJ_INT32)width;
opj_applyLUT8u_8u32s_C1P3R(pSrc, -(OPJ_INT32)stride, pDst, pDstStride, pLUT,
width, height);
}
return image;
}
static OPJ_BOOL bmp_read_file_header(FILE* IN, OPJ_BITMAPFILEHEADER* header)
{
header->bfType = (OPJ_UINT16)getc(IN);
header->bfType |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
if (header->bfType != 19778) {
fprintf(stderr, "Error, not a BMP file!\n");
return OPJ_FALSE;
}
/* FILE HEADER */
/* ------------- */
header->bfSize = (OPJ_UINT32)getc(IN);
header->bfSize |= (OPJ_UINT32)getc(IN) << 8;
header->bfSize |= (OPJ_UINT32)getc(IN) << 16;
header->bfSize |= (OPJ_UINT32)getc(IN) << 24;
header->bfReserved1 = (OPJ_UINT16)getc(IN);
header->bfReserved1 |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
header->bfReserved2 = (OPJ_UINT16)getc(IN);
header->bfReserved2 |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
header->bfOffBits = (OPJ_UINT32)getc(IN);
header->bfOffBits |= (OPJ_UINT32)getc(IN) << 8;
header->bfOffBits |= (OPJ_UINT32)getc(IN) << 16;
header->bfOffBits |= (OPJ_UINT32)getc(IN) << 24;
return OPJ_TRUE;
}
static OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header)
{
memset(header, 0, sizeof(*header));
/* INFO HEADER */
/* ------------- */
header->biSize = (OPJ_UINT32)getc(IN);
header->biSize |= (OPJ_UINT32)getc(IN) << 8;
header->biSize |= (OPJ_UINT32)getc(IN) << 16;
header->biSize |= (OPJ_UINT32)getc(IN) << 24;
switch (header->biSize) {
case 12U: /* BITMAPCOREHEADER */
case 40U: /* BITMAPINFOHEADER */
case 52U: /* BITMAPV2INFOHEADER */
case 56U: /* BITMAPV3INFOHEADER */
case 108U: /* BITMAPV4HEADER */
case 124U: /* BITMAPV5HEADER */
break;
default:
fprintf(stderr, "Error, unknown BMP header size %d\n", header->biSize);
return OPJ_FALSE;
}
header->biWidth = (OPJ_UINT32)getc(IN);
header->biWidth |= (OPJ_UINT32)getc(IN) << 8;
header->biWidth |= (OPJ_UINT32)getc(IN) << 16;
header->biWidth |= (OPJ_UINT32)getc(IN) << 24;
header->biHeight = (OPJ_UINT32)getc(IN);
header->biHeight |= (OPJ_UINT32)getc(IN) << 8;
header->biHeight |= (OPJ_UINT32)getc(IN) << 16;
header->biHeight |= (OPJ_UINT32)getc(IN) << 24;
header->biPlanes = (OPJ_UINT16)getc(IN);
header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
header->biBitCount = (OPJ_UINT16)getc(IN);
header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
if (header->biBitCount == 0) {
fprintf(stderr, "Error, invalid biBitCount %d\n", 0);
return OPJ_FALSE;
}
if (header->biSize >= 40U) {
header->biCompression = (OPJ_UINT32)getc(IN);
header->biCompression |= (OPJ_UINT32)getc(IN) << 8;
header->biCompression |= (OPJ_UINT32)getc(IN) << 16;
header->biCompression |= (OPJ_UINT32)getc(IN) << 24;
header->biSizeImage = (OPJ_UINT32)getc(IN);
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8;
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16;
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24;
header->biXpelsPerMeter = (OPJ_UINT32)getc(IN);
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8;
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16;
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24;
header->biYpelsPerMeter = (OPJ_UINT32)getc(IN);
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8;
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16;
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24;
header->biClrUsed = (OPJ_UINT32)getc(IN);
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8;
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16;
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24;
header->biClrImportant = (OPJ_UINT32)getc(IN);
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8;
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16;
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 56U) {
header->biRedMask = (OPJ_UINT32)getc(IN);
header->biRedMask |= (OPJ_UINT32)getc(IN) << 8;
header->biRedMask |= (OPJ_UINT32)getc(IN) << 16;
header->biRedMask |= (OPJ_UINT32)getc(IN) << 24;
if (!header->biRedMask) {
fprintf(stderr, "Error, invalid red mask value %d\n", header->biRedMask);
return OPJ_FALSE;
}
header->biGreenMask = (OPJ_UINT32)getc(IN);
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8;
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16;
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24;
if (!header->biGreenMask) {
fprintf(stderr, "Error, invalid green mask value %d\n", header->biGreenMask);
return OPJ_FALSE;
}
header->biBlueMask = (OPJ_UINT32)getc(IN);
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8;
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16;
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24;
if (!header->biBlueMask) {
fprintf(stderr, "Error, invalid blue mask value %d\n", header->biBlueMask);
return OPJ_FALSE;
}
header->biAlphaMask = (OPJ_UINT32)getc(IN);
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8;
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16;
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 108U) {
header->biColorSpaceType = (OPJ_UINT32)getc(IN);
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8;
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16;
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24;
if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP),
IN) != sizeof(header->biColorSpaceEP)) {
fprintf(stderr, "Error, can't read BMP header\n");
return OPJ_FALSE;
}
header->biRedGamma = (OPJ_UINT32)getc(IN);
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24;
header->biGreenGamma = (OPJ_UINT32)getc(IN);
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24;
header->biBlueGamma = (OPJ_UINT32)getc(IN);
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 124U) {
header->biIntent = (OPJ_UINT32)getc(IN);
header->biIntent |= (OPJ_UINT32)getc(IN) << 8;
header->biIntent |= (OPJ_UINT32)getc(IN) << 16;
header->biIntent |= (OPJ_UINT32)getc(IN) << 24;
header->biIccProfileData = (OPJ_UINT32)getc(IN);
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8;
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16;
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24;
header->biIccProfileSize = (OPJ_UINT32)getc(IN);
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8;
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16;
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24;
header->biReserved = (OPJ_UINT32)getc(IN);
header->biReserved |= (OPJ_UINT32)getc(IN) << 8;
header->biReserved |= (OPJ_UINT32)getc(IN) << 16;
header->biReserved |= (OPJ_UINT32)getc(IN) << 24;
}
return OPJ_TRUE;
}
static OPJ_BOOL bmp_read_raw_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride,
OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_ARG_NOT_USED(width);
if (fread(pData, sizeof(OPJ_UINT8), stride * height, IN) != (stride * height)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y, written;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = written = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
if (c) {
int j, c1_int;
OPJ_UINT8 c1;
c1_int = getc(IN);
if (c1_int == EOF) {
return OPJ_FALSE;
}
c1 = (OPJ_UINT8)c1_int;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = c1;
written++;
}
} else {
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
if (c == 0x00) { /* EOL */
x = 0;
++y;
pix = pData + y * stride + x;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
x += (OPJ_UINT32)c;
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 */
int j;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
int c1_int;
OPJ_UINT8 c1;
c1_int = getc(IN);
if (c1_int == EOF) {
return OPJ_FALSE;
}
c1 = (OPJ_UINT8)c1_int;
*pix = c1;
written++;
}
if ((OPJ_UINT32)c & 1U) { /* skip padding byte */
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
}
}
}
}/* while() */
if (written != width * height) {
fprintf(stderr, "warning, image's actual size does not match advertized one\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
break;
}
if (c) { /* encoded mode */
int j;
OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN);
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
}
} else { /* absolute mode */
c = getc(IN);
if (c == EOF) {
break;
}
if (c == 0x00) { /* EOL */
x = 0;
y++;
pix = pData + y * stride;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
x += (OPJ_UINT32)c;
c = getc(IN);
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 : absolute mode */
int j;
OPJ_UINT8 c1 = 0U;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
if ((j & 1) == 0) {
c1 = (OPJ_UINT8)getc(IN);
}
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
}
if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */
getc(IN);
}
}
}
} /* while(y < height) */
return OPJ_TRUE;
}
opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
{
opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */
OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256];
OPJ_UINT8 const* pLUT[3];
opj_image_t * image = NULL;
FILE *IN;
OPJ_BITMAPFILEHEADER File_h;
OPJ_BITMAPINFOHEADER Info_h;
OPJ_UINT32 i, palette_len, numcmpts = 1U;
OPJ_BOOL l_result = OPJ_FALSE;
OPJ_UINT8* pData = NULL;
OPJ_UINT32 stride;
pLUT[0] = lut_R;
pLUT[1] = lut_G;
pLUT[2] = lut_B;
IN = fopen(filename, "rb");
if (!IN) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return NULL;
}
if (!bmp_read_file_header(IN, &File_h)) {
fclose(IN);
return NULL;
}
if (!bmp_read_info_header(IN, &Info_h)) {
fclose(IN);
return NULL;
}
/* Load palette */
if (Info_h.biBitCount <= 8U) {
memset(&lut_R[0], 0, sizeof(lut_R));
memset(&lut_G[0], 0, sizeof(lut_G));
memset(&lut_B[0], 0, sizeof(lut_B));
palette_len = Info_h.biClrUsed;
if ((palette_len == 0U) && (Info_h.biBitCount <= 8U)) {
palette_len = (1U << Info_h.biBitCount);
}
if (palette_len > 256U) {
palette_len = 256U;
}
if (palette_len > 0U) {
OPJ_UINT8 has_color = 0U;
for (i = 0U; i < palette_len; i++) {
lut_B[i] = (OPJ_UINT8)getc(IN);
lut_G[i] = (OPJ_UINT8)getc(IN);
lut_R[i] = (OPJ_UINT8)getc(IN);
(void)getc(IN); /* padding */
has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]);
}
if (has_color) {
numcmpts = 3U;
}
}
} else {
numcmpts = 3U;
if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) {
numcmpts++;
}
}
if (Info_h.biWidth == 0 || Info_h.biHeight == 0) {
fclose(IN);
return NULL;
}
if (Info_h.biBitCount > (((OPJ_UINT32) - 1) - 31) / Info_h.biWidth) {
fclose(IN);
return NULL;
}
stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) *
4U; /* rows are aligned on 32bits */
if (Info_h.biBitCount == 4 &&
Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */
if (8 > (((OPJ_UINT32) - 1) - 31) / Info_h.biWidth) {
fclose(IN);
return NULL;
}
stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U;
}
if (stride > ((OPJ_UINT32) - 1) / sizeof(OPJ_UINT8) / Info_h.biHeight) {
fclose(IN);
return NULL;
}
pData = (OPJ_UINT8 *) calloc(1, sizeof(OPJ_UINT8) * stride * Info_h.biHeight);
if (pData == NULL) {
fclose(IN);
return NULL;
}
/* Place the cursor at the beginning of the image information */
fseek(IN, 0, SEEK_SET);
fseek(IN, (long)File_h.bfOffBits, SEEK_SET);
switch (Info_h.biCompression) {
case 0:
case 3:
/* read raw data */
l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth,
Info_h.biHeight);
break;
case 1:
/* read rle8 data */
l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth,
Info_h.biHeight);
break;
case 2:
/* read rle4 data */
l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth,
Info_h.biHeight);
break;
default:
fprintf(stderr, "Unsupported BMP compression\n");
l_result = OPJ_FALSE;
break;
}
if (!l_result) {
free(pData);
fclose(IN);
return NULL;
}
/* create the image */
memset(&cmptparm[0], 0, sizeof(cmptparm));
for (i = 0; i < 4U; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy;
cmptparm[i].w = Info_h.biWidth;
cmptparm[i].h = Info_h.biHeight;
}
image = opj_image_create(numcmpts, &cmptparm[0],
(numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB);
if (!image) {
fclose(IN);
free(pData);
return NULL;
}
if (numcmpts == 4U) {
image->comps[3].alpha = 1;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)
parameters->subsampling_dx + 1U;
image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)
parameters->subsampling_dy + 1U;
/* Read the data */
if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */
bmp24toimage(pData, stride, image);
} else if (Info_h.biBitCount == 8 &&
Info_h.biCompression == 0) { /* RGB 8bpp Indexed */
bmp8toimage(pData, stride, image, pLUT);
} else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/
bmp8toimage(pData, stride, image, pLUT);
} else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/
bmp8toimage(pData, stride, image,
pLUT); /* RLE 4 gets decoded as 8 bits data for now */
} else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */
bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU,
0x00000000U);
} else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */
if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) &&
(Info_h.biBlueMask == 0U)) {
Info_h.biRedMask = 0x00FF0000U;
Info_h.biGreenMask = 0x0000FF00U;
Info_h.biBlueMask = 0x000000FFU;
}
bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask,
Info_h.biBlueMask, Info_h.biAlphaMask);
} else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */
bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U);
} else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */
if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) &&
(Info_h.biBlueMask == 0U)) {
Info_h.biRedMask = 0xF800U;
Info_h.biGreenMask = 0x07E0U;
Info_h.biBlueMask = 0x001FU;
}
bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask,
Info_h.biBlueMask, Info_h.biAlphaMask);
} else {
opj_image_destroy(image);
image = NULL;
fprintf(stderr,
"Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n",
Info_h.biBitCount);
}
free(pData);
fclose(IN);
return image;
}
int imagetobmp(opj_image_t * image, const char *outfile)
{
int w, h;
int i, pad;
FILE *fdest = NULL;
int adjustR, adjustG, adjustB;
if (image->comps[0].prec < 8) {
fprintf(stderr, "imagetobmp: Unsupported precision: %d\n",
image->comps[0].prec);
return 1;
}
if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx
&& image->comps[1].dx == image->comps[2].dx
&& image->comps[0].dy == image->comps[1].dy
&& image->comps[1].dy == image->comps[2].dy
&& image->comps[0].prec == image->comps[1].prec
&& image->comps[1].prec == image->comps[2].prec
&& image->comps[0].sgnd == image->comps[1].sgnd
&& image->comps[1].sgnd == image->comps[2].sgnd) {
/* -->> -->> -->> -->>
24 bits color
<<-- <<-- <<-- <<-- */
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return 1;
}
w = (int)image->comps[0].w;
h = (int)image->comps[0].h;
fprintf(fdest, "BM");
/* FILE HEADER */
/* ------------- */
fprintf(fdest, "%c%c%c%c",
(OPJ_UINT8)(h * w * 3 + 3 * h * (w % 2) + 54) & 0xff,
(OPJ_UINT8)((h * w * 3 + 3 * h * (w % 2) + 54) >> 8) & 0xff,
(OPJ_UINT8)((h * w * 3 + 3 * h * (w % 2) + 54) >> 16) & 0xff,
(OPJ_UINT8)((h * w * 3 + 3 * h * (w % 2) + 54) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff,
((0) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff, ((54) >> 16) & 0xff,
((54) >> 24) & 0xff);
/* INFO HEADER */
/* ------------- */
fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff,
((40) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (OPJ_UINT8)((w) & 0xff),
(OPJ_UINT8)((w) >> 8) & 0xff,
(OPJ_UINT8)((w) >> 16) & 0xff,
(OPJ_UINT8)((w) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (OPJ_UINT8)((h) & 0xff),
(OPJ_UINT8)((h) >> 8) & 0xff,
(OPJ_UINT8)((h) >> 16) & 0xff,
(OPJ_UINT8)((h) >> 24) & 0xff);
fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff);
fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff,
((0) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (OPJ_UINT8)(3 * h * w + 3 * h * (w % 2)) & 0xff,
(OPJ_UINT8)((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff,
(OPJ_UINT8)((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff,
(OPJ_UINT8)((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff,
((0) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff,
((0) >> 24) & 0xff);
if (image->comps[0].prec > 8) {
adjustR = (int)image->comps[0].prec - 8;
printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n",
image->comps[0].prec);
} else {
adjustR = 0;
}
if (image->comps[1].prec > 8) {
adjustG = (int)image->comps[1].prec - 8;
printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n",
image->comps[1].prec);
} else {
adjustG = 0;
}
if (image->comps[2].prec > 8) {
adjustB = (int)image->comps[2].prec - 8;
printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n",
image->comps[2].prec);
} else {
adjustB = 0;
}
for (i = 0; i < w * h; i++) {
OPJ_UINT8 rc, gc, bc;
int r, g, b;
r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (adjustR > 0) {
r = ((r >> adjustR) + ((r >> (adjustR - 1)) % 2));
}
if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}
rc = (OPJ_UINT8)r;
g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
if (adjustG > 0) {
g = ((g >> adjustG) + ((g >> (adjustG - 1)) % 2));
}
if (g > 255) {
g = 255;
} else if (g < 0) {
g = 0;
}
gc = (OPJ_UINT8)g;
b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
if (adjustB > 0) {
b = ((b >> adjustB) + ((b >> (adjustB - 1)) % 2));
}
if (b > 255) {
b = 255;
} else if (b < 0) {
b = 0;
}
bc = (OPJ_UINT8)b;
fprintf(fdest, "%c%c%c", bc, gc, rc);
if ((i + 1) % w == 0) {
for (pad = ((3 * w) % 4) ? (4 - (3 * w) % 4) : 0; pad > 0; pad--) { /* ADD */
fprintf(fdest, "%c", 0);
}
}
}
fclose(fdest);
} else { /* Gray-scale */
/* -->> -->> -->> -->>
8 bits non code (Gray scale)
<<-- <<-- <<-- <<-- */
fdest = fopen(outfile, "wb");
if (!fdest) {
fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
return 1;
}
if (image->numcomps > 1) {
fprintf(stderr, "imagetobmp: only first component of %d is used.\n",
image->numcomps);
}
w = (int)image->comps[0].w;
h = (int)image->comps[0].h;
fprintf(fdest, "BM");
/* FILE HEADER */
/* ------------- */
fprintf(fdest, "%c%c%c%c", (OPJ_UINT8)(h * w + 54 + 1024 + h * (w % 2)) & 0xff,
(OPJ_UINT8)((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff,
(OPJ_UINT8)((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff,
(OPJ_UINT8)((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff,
((0) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff,
((54 + 1024) >> 16) & 0xff,
((54 + 1024) >> 24) & 0xff);
/* INFO HEADER */
/* ------------- */
fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff,
((40) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (OPJ_UINT8)((w) & 0xff),
(OPJ_UINT8)((w) >> 8) & 0xff,
(OPJ_UINT8)((w) >> 16) & 0xff,
(OPJ_UINT8)((w) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (OPJ_UINT8)((h) & 0xff),
(OPJ_UINT8)((h) >> 8) & 0xff,
(OPJ_UINT8)((h) >> 16) & 0xff,
(OPJ_UINT8)((h) >> 24) & 0xff);
fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff);
fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff);
fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff,
((0) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (OPJ_UINT8)(h * w + h * (w % 2)) & 0xff,
(OPJ_UINT8)((h * w + h * (w % 2)) >> 8) & 0xff,
(OPJ_UINT8)((h * w + h * (w % 2)) >> 16) & 0xff,
(OPJ_UINT8)((h * w + h * (w % 2)) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff,
((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff,
((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff,
((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
if (image->comps[0].prec > 8) {
adjustR = (int)image->comps[0].prec - 8;
printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n",
image->comps[0].prec);
} else {
adjustR = 0;
}
for (i = 0; i < 256; i++) {
fprintf(fdest, "%c%c%c%c", i, i, i, 0);
}
for (i = 0; i < w * h; i++) {
int r;
r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)];
r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
if (adjustR > 0) {
r = ((r >> adjustR) + ((r >> (adjustR - 1)) % 2));
}
if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}
fprintf(fdest, "%c", (OPJ_UINT8)r);
if ((i + 1) % w == 0) {
for (pad = (w % 4) ? (4 - w % 4) : 0; pad > 0; pad--) { /* ADD */
fprintf(fdest, "%c", 0);
}
}
}
fclose(fdest);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-400/c/bad_898_0 |
crossvul-cpp_data_bad_1247_0 | /*
* Marvell Wireless LAN device driver: PCIE specific handling
*
* Copyright (C) 2011-2014, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include <linux/firmware.h>
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
#include "pcie.h"
#define PCIE_VERSION "1.0"
#define DRV_NAME "Marvell mwifiex PCIe"
static struct mwifiex_if_ops pcie_ops;
static const struct of_device_id mwifiex_pcie_of_match_table[] = {
{ .compatible = "pci11ab,2b42" },
{ .compatible = "pci1b4b,2b42" },
{ }
};
static int mwifiex_pcie_probe_of(struct device *dev)
{
if (!of_match_node(mwifiex_pcie_of_match_table, dev->of_node)) {
dev_err(dev, "required compatible string missing\n");
return -EINVAL;
}
return 0;
}
static void mwifiex_pcie_work(struct work_struct *work);
static int
mwifiex_map_pci_memory(struct mwifiex_adapter *adapter, struct sk_buff *skb,
size_t size, int flags)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_dma_mapping mapping;
mapping.addr = pci_map_single(card->dev, skb->data, size, flags);
if (pci_dma_mapping_error(card->dev, mapping.addr)) {
mwifiex_dbg(adapter, ERROR, "failed to map pci memory!\n");
return -1;
}
mapping.len = size;
mwifiex_store_mapping(skb, &mapping);
return 0;
}
static void mwifiex_unmap_pci_memory(struct mwifiex_adapter *adapter,
struct sk_buff *skb, int flags)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_dma_mapping mapping;
mwifiex_get_mapping(skb, &mapping);
pci_unmap_single(card->dev, mapping.addr, mapping.len, flags);
}
/*
* This function writes data into PCIE card register.
*/
static int mwifiex_write_reg(struct mwifiex_adapter *adapter, int reg, u32 data)
{
struct pcie_service_card *card = adapter->card;
iowrite32(data, card->pci_mmap1 + reg);
return 0;
}
/* This function reads data from PCIE card register.
*/
static int mwifiex_read_reg(struct mwifiex_adapter *adapter, int reg, u32 *data)
{
struct pcie_service_card *card = adapter->card;
*data = ioread32(card->pci_mmap1 + reg);
if (*data == 0xffffffff)
return 0xffffffff;
return 0;
}
/* This function reads u8 data from PCIE card register. */
static int mwifiex_read_reg_byte(struct mwifiex_adapter *adapter,
int reg, u8 *data)
{
struct pcie_service_card *card = adapter->card;
*data = ioread8(card->pci_mmap1 + reg);
return 0;
}
/*
* This function reads sleep cookie and checks if FW is ready
*/
static bool mwifiex_pcie_ok_to_access_hw(struct mwifiex_adapter *adapter)
{
u32 cookie_value;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!reg->sleep_cookie)
return true;
if (card->sleep_cookie_vbase) {
cookie_value = get_unaligned_le32(card->sleep_cookie_vbase);
mwifiex_dbg(adapter, INFO,
"info: ACCESS_HW: sleep cookie=0x%x\n",
cookie_value);
if (cookie_value == FW_AWAKE_COOKIE)
return true;
}
return false;
}
#ifdef CONFIG_PM_SLEEP
/*
* Kernel needs to suspend all functions separately. Therefore all
* registered functions must have drivers with suspend and resume
* methods. Failing that the kernel simply removes the whole card.
*
* If already not suspended, this function allocates and sends a host
* sleep activate request to the firmware and turns off the traffic.
*/
static int mwifiex_pcie_suspend(struct device *dev)
{
struct mwifiex_adapter *adapter;
struct pcie_service_card *card = dev_get_drvdata(dev);
/* Might still be loading firmware */
wait_for_completion(&card->fw_done);
adapter = card->adapter;
if (!adapter) {
dev_err(dev, "adapter is not valid\n");
return 0;
}
mwifiex_enable_wake(adapter);
/* Enable the Host Sleep */
if (!mwifiex_enable_hs(adapter)) {
mwifiex_dbg(adapter, ERROR,
"cmd: failed to suspend\n");
clear_bit(MWIFIEX_IS_HS_ENABLING, &adapter->work_flags);
mwifiex_disable_wake(adapter);
return -EFAULT;
}
flush_workqueue(adapter->workqueue);
/* Indicate device suspended */
set_bit(MWIFIEX_IS_SUSPENDED, &adapter->work_flags);
clear_bit(MWIFIEX_IS_HS_ENABLING, &adapter->work_flags);
return 0;
}
/*
* Kernel needs to suspend all functions separately. Therefore all
* registered functions must have drivers with suspend and resume
* methods. Failing that the kernel simply removes the whole card.
*
* If already not resumed, this function turns on the traffic and
* sends a host sleep cancel request to the firmware.
*/
static int mwifiex_pcie_resume(struct device *dev)
{
struct mwifiex_adapter *adapter;
struct pcie_service_card *card = dev_get_drvdata(dev);
if (!card->adapter) {
dev_err(dev, "adapter structure is not valid\n");
return 0;
}
adapter = card->adapter;
if (!test_bit(MWIFIEX_IS_SUSPENDED, &adapter->work_flags)) {
mwifiex_dbg(adapter, WARN,
"Device already resumed\n");
return 0;
}
clear_bit(MWIFIEX_IS_SUSPENDED, &adapter->work_flags);
mwifiex_cancel_hs(mwifiex_get_priv(adapter, MWIFIEX_BSS_ROLE_STA),
MWIFIEX_ASYNC_CMD);
mwifiex_disable_wake(adapter);
return 0;
}
#endif
/*
* This function probes an mwifiex device and registers it. It allocates
* the card structure, enables PCIE function number and initiates the
* device registration and initialization procedure by adding a logical
* interface.
*/
static int mwifiex_pcie_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct pcie_service_card *card;
int ret;
pr_debug("info: vendor=0x%4.04X device=0x%4.04X rev=%d\n",
pdev->vendor, pdev->device, pdev->revision);
card = devm_kzalloc(&pdev->dev, sizeof(*card), GFP_KERNEL);
if (!card)
return -ENOMEM;
init_completion(&card->fw_done);
card->dev = pdev;
if (ent->driver_data) {
struct mwifiex_pcie_device *data = (void *)ent->driver_data;
card->pcie.reg = data->reg;
card->pcie.blksz_fw_dl = data->blksz_fw_dl;
card->pcie.tx_buf_size = data->tx_buf_size;
card->pcie.can_dump_fw = data->can_dump_fw;
card->pcie.mem_type_mapping_tbl = data->mem_type_mapping_tbl;
card->pcie.num_mem_types = data->num_mem_types;
card->pcie.can_ext_scan = data->can_ext_scan;
INIT_WORK(&card->work, mwifiex_pcie_work);
}
/* device tree node parsing and platform specific configuration*/
if (pdev->dev.of_node) {
ret = mwifiex_pcie_probe_of(&pdev->dev);
if (ret)
return ret;
}
if (mwifiex_add_card(card, &card->fw_done, &pcie_ops,
MWIFIEX_PCIE, &pdev->dev)) {
pr_err("%s failed\n", __func__);
return -1;
}
return 0;
}
/*
* This function removes the interface and frees up the card structure.
*/
static void mwifiex_pcie_remove(struct pci_dev *pdev)
{
struct pcie_service_card *card;
struct mwifiex_adapter *adapter;
struct mwifiex_private *priv;
const struct mwifiex_pcie_card_reg *reg;
u32 fw_status;
int ret;
card = pci_get_drvdata(pdev);
wait_for_completion(&card->fw_done);
adapter = card->adapter;
if (!adapter || !adapter->priv_num)
return;
reg = card->pcie.reg;
if (reg)
ret = mwifiex_read_reg(adapter, reg->fw_status, &fw_status);
else
fw_status = -1;
if (fw_status == FIRMWARE_READY_PCIE && !adapter->mfg_mode) {
mwifiex_deauthenticate_all(adapter);
priv = mwifiex_get_priv(adapter, MWIFIEX_BSS_ROLE_ANY);
mwifiex_disable_auto_ds(priv);
mwifiex_init_shutdown_fw(priv, MWIFIEX_FUNC_SHUTDOWN);
}
mwifiex_remove_card(adapter);
}
static void mwifiex_pcie_shutdown(struct pci_dev *pdev)
{
mwifiex_pcie_remove(pdev);
return;
}
static void mwifiex_pcie_coredump(struct device *dev)
{
struct pci_dev *pdev;
struct pcie_service_card *card;
pdev = container_of(dev, struct pci_dev, dev);
card = pci_get_drvdata(pdev);
if (!test_and_set_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP,
&card->work_flags))
schedule_work(&card->work);
}
static const struct pci_device_id mwifiex_ids[] = {
{
PCIE_VENDOR_ID_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8766P,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8766,
},
{
PCIE_VENDOR_ID_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8897,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8897,
},
{
PCIE_VENDOR_ID_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8997,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8997,
},
{
PCIE_VENDOR_ID_V2_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8997,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8997,
},
{},
};
MODULE_DEVICE_TABLE(pci, mwifiex_ids);
/*
* Cleanup all software without cleaning anything related to PCIe and HW.
*/
static void mwifiex_pcie_reset_prepare(struct pci_dev *pdev)
{
struct pcie_service_card *card = pci_get_drvdata(pdev);
struct mwifiex_adapter *adapter = card->adapter;
if (!adapter) {
dev_err(&pdev->dev, "%s: adapter structure is not valid\n",
__func__);
return;
}
mwifiex_dbg(adapter, INFO,
"%s: vendor=0x%4.04x device=0x%4.04x rev=%d Pre-FLR\n",
__func__, pdev->vendor, pdev->device, pdev->revision);
mwifiex_shutdown_sw(adapter);
clear_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP, &card->work_flags);
clear_bit(MWIFIEX_IFACE_WORK_CARD_RESET, &card->work_flags);
mwifiex_dbg(adapter, INFO, "%s, successful\n", __func__);
}
/*
* Kernel stores and restores PCIe function context before and after performing
* FLR respectively. Reconfigure the software and firmware including firmware
* redownload.
*/
static void mwifiex_pcie_reset_done(struct pci_dev *pdev)
{
struct pcie_service_card *card = pci_get_drvdata(pdev);
struct mwifiex_adapter *adapter = card->adapter;
int ret;
if (!adapter) {
dev_err(&pdev->dev, "%s: adapter structure is not valid\n",
__func__);
return;
}
mwifiex_dbg(adapter, INFO,
"%s: vendor=0x%4.04x device=0x%4.04x rev=%d Post-FLR\n",
__func__, pdev->vendor, pdev->device, pdev->revision);
ret = mwifiex_reinit_sw(adapter);
if (ret)
dev_err(&pdev->dev, "reinit failed: %d\n", ret);
else
mwifiex_dbg(adapter, INFO, "%s, successful\n", __func__);
}
static const struct pci_error_handlers mwifiex_pcie_err_handler = {
.reset_prepare = mwifiex_pcie_reset_prepare,
.reset_done = mwifiex_pcie_reset_done,
};
#ifdef CONFIG_PM_SLEEP
/* Power Management Hooks */
static SIMPLE_DEV_PM_OPS(mwifiex_pcie_pm_ops, mwifiex_pcie_suspend,
mwifiex_pcie_resume);
#endif
/* PCI Device Driver */
static struct pci_driver __refdata mwifiex_pcie = {
.name = "mwifiex_pcie",
.id_table = mwifiex_ids,
.probe = mwifiex_pcie_probe,
.remove = mwifiex_pcie_remove,
.driver = {
.coredump = mwifiex_pcie_coredump,
#ifdef CONFIG_PM_SLEEP
.pm = &mwifiex_pcie_pm_ops,
#endif
},
.shutdown = mwifiex_pcie_shutdown,
.err_handler = &mwifiex_pcie_err_handler,
};
/*
* This function adds delay loop to ensure FW is awake before proceeding.
*/
static void mwifiex_pcie_dev_wakeup_delay(struct mwifiex_adapter *adapter)
{
int i = 0;
while (mwifiex_pcie_ok_to_access_hw(adapter)) {
i++;
usleep_range(10, 20);
/* 50ms max wait */
if (i == 5000)
break;
}
return;
}
static void mwifiex_delay_for_sleep_cookie(struct mwifiex_adapter *adapter,
u32 max_delay_loop_cnt)
{
struct pcie_service_card *card = adapter->card;
u8 *buffer;
u32 sleep_cookie, count;
struct sk_buff *cmdrsp = card->cmdrsp_buf;
for (count = 0; count < max_delay_loop_cnt; count++) {
pci_dma_sync_single_for_cpu(card->dev,
MWIFIEX_SKB_DMA_ADDR(cmdrsp),
sizeof(sleep_cookie),
PCI_DMA_FROMDEVICE);
buffer = cmdrsp->data;
sleep_cookie = get_unaligned_le32(buffer);
if (sleep_cookie == MWIFIEX_DEF_SLEEP_COOKIE) {
mwifiex_dbg(adapter, INFO,
"sleep cookie found at count %d\n", count);
break;
}
pci_dma_sync_single_for_device(card->dev,
MWIFIEX_SKB_DMA_ADDR(cmdrsp),
sizeof(sleep_cookie),
PCI_DMA_FROMDEVICE);
usleep_range(20, 30);
}
if (count >= max_delay_loop_cnt)
mwifiex_dbg(adapter, INFO,
"max count reached while accessing sleep cookie\n");
}
/* This function wakes up the card by reading fw_status register. */
static int mwifiex_pm_wakeup_card(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_dbg(adapter, EVENT,
"event: Wakeup device...\n");
if (reg->sleep_cookie)
mwifiex_pcie_dev_wakeup_delay(adapter);
/* Accessing fw_status register will wakeup device */
if (mwifiex_write_reg(adapter, reg->fw_status, FIRMWARE_READY_PCIE)) {
mwifiex_dbg(adapter, ERROR,
"Writing fw_status register failed\n");
return -1;
}
if (reg->sleep_cookie) {
mwifiex_pcie_dev_wakeup_delay(adapter);
mwifiex_dbg(adapter, INFO,
"PCIE wakeup: Setting PS_STATE_AWAKE\n");
adapter->ps_state = PS_STATE_AWAKE;
}
return 0;
}
/*
* This function is called after the card has woken up.
*
* The card configuration register is reset.
*/
static int mwifiex_pm_wakeup_card_complete(struct mwifiex_adapter *adapter)
{
mwifiex_dbg(adapter, CMD,
"cmd: Wakeup device completed\n");
return 0;
}
/*
* This function disables the host interrupt.
*
* The host interrupt mask is read, the disable bit is reset and
* written back to the card host interrupt mask register.
*/
static int mwifiex_pcie_disable_host_int(struct mwifiex_adapter *adapter)
{
if (mwifiex_pcie_ok_to_access_hw(adapter)) {
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_MASK,
0x00000000)) {
mwifiex_dbg(adapter, ERROR,
"Disable host interrupt failed\n");
return -1;
}
}
atomic_set(&adapter->tx_hw_pending, 0);
return 0;
}
static void mwifiex_pcie_disable_host_int_noerr(struct mwifiex_adapter *adapter)
{
WARN_ON(mwifiex_pcie_disable_host_int(adapter));
}
/*
* This function enables the host interrupt.
*
* The host interrupt enable mask is written to the card
* host interrupt mask register.
*/
static int mwifiex_pcie_enable_host_int(struct mwifiex_adapter *adapter)
{
if (mwifiex_pcie_ok_to_access_hw(adapter)) {
/* Simply write the mask to the register */
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_MASK,
HOST_INTR_MASK)) {
mwifiex_dbg(adapter, ERROR,
"Enable host interrupt failed\n");
return -1;
}
}
return 0;
}
/*
* This function initializes TX buffer ring descriptors
*/
static int mwifiex_init_txq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
card->tx_buf_list[i] = NULL;
if (reg->pfu_enabled) {
card->txbd_ring[i] = (void *)card->txbd_ring_vbase +
(sizeof(*desc2) * i);
desc2 = card->txbd_ring[i];
memset(desc2, 0, sizeof(*desc2));
} else {
card->txbd_ring[i] = (void *)card->txbd_ring_vbase +
(sizeof(*desc) * i);
desc = card->txbd_ring[i];
memset(desc, 0, sizeof(*desc));
}
}
return 0;
}
/* This function initializes RX buffer ring descriptors. Each SKB is allocated
* here and after mapping PCI memory, its physical address is assigned to
* PCIE Rx buffer descriptor's physical address.
*/
static int mwifiex_init_rxq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct sk_buff *skb;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
dma_addr_t buf_pa;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
/* Allocate skb here so that firmware can DMA data from it */
skb = mwifiex_alloc_dma_align_buf(MWIFIEX_RX_DATA_BUF_SIZE,
GFP_KERNEL);
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb for RX ring.\n");
kfree(card->rxbd_ring_vbase);
return -ENOMEM;
}
if (mwifiex_map_pci_memory(adapter, skb,
MWIFIEX_RX_DATA_BUF_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
mwifiex_dbg(adapter, INFO,
"info: RX ring: skb=%p len=%d data=%p buf_pa=%#x:%x\n",
skb, skb->len, skb->data, (u32)buf_pa,
(u32)((u64)buf_pa >> 32));
card->rx_buf_list[i] = skb;
if (reg->pfu_enabled) {
card->rxbd_ring[i] = (void *)card->rxbd_ring_vbase +
(sizeof(*desc2) * i);
desc2 = card->rxbd_ring[i];
desc2->paddr = buf_pa;
desc2->len = (u16)skb->len;
desc2->frag_len = (u16)skb->len;
desc2->flags = reg->ring_flag_eop | reg->ring_flag_sop;
desc2->offset = 0;
} else {
card->rxbd_ring[i] = (void *)(card->rxbd_ring_vbase +
(sizeof(*desc) * i));
desc = card->rxbd_ring[i];
desc->paddr = buf_pa;
desc->len = (u16)skb->len;
desc->flags = 0;
}
}
return 0;
}
/* This function initializes event buffer ring descriptors. Each SKB is
* allocated here and after mapping PCI memory, its physical address is assigned
* to PCIE Rx buffer descriptor's physical address
*/
static int mwifiex_pcie_init_evt_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_evt_buf_desc *desc;
struct sk_buff *skb;
dma_addr_t buf_pa;
int i;
for (i = 0; i < MWIFIEX_MAX_EVT_BD; i++) {
/* Allocate skb here so that firmware can DMA data from it */
skb = dev_alloc_skb(MAX_EVENT_SIZE);
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb for EVENT buf.\n");
kfree(card->evtbd_ring_vbase);
return -ENOMEM;
}
skb_put(skb, MAX_EVENT_SIZE);
if (mwifiex_map_pci_memory(adapter, skb, MAX_EVENT_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
mwifiex_dbg(adapter, EVENT,
"info: EVT ring: skb=%p len=%d data=%p buf_pa=%#x:%x\n",
skb, skb->len, skb->data, (u32)buf_pa,
(u32)((u64)buf_pa >> 32));
card->evt_buf_list[i] = skb;
card->evtbd_ring[i] = (void *)(card->evtbd_ring_vbase +
(sizeof(*desc) * i));
desc = card->evtbd_ring[i];
desc->paddr = buf_pa;
desc->len = (u16)skb->len;
desc->flags = 0;
}
return 0;
}
/* This function cleans up TX buffer rings. If any of the buffer list has valid
* SKB address, associated SKB is freed.
*/
static void mwifiex_cleanup_txq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct sk_buff *skb;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
if (reg->pfu_enabled) {
desc2 = card->txbd_ring[i];
if (card->tx_buf_list[i]) {
skb = card->tx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(skb);
}
memset(desc2, 0, sizeof(*desc2));
} else {
desc = card->txbd_ring[i];
if (card->tx_buf_list[i]) {
skb = card->tx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(skb);
}
memset(desc, 0, sizeof(*desc));
}
card->tx_buf_list[i] = NULL;
}
atomic_set(&adapter->tx_hw_pending, 0);
return;
}
/* This function cleans up RX buffer rings. If any of the buffer list has valid
* SKB address, associated SKB is freed.
*/
static void mwifiex_cleanup_rxq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
struct sk_buff *skb;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
if (reg->pfu_enabled) {
desc2 = card->rxbd_ring[i];
if (card->rx_buf_list[i]) {
skb = card->rx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(skb);
}
memset(desc2, 0, sizeof(*desc2));
} else {
desc = card->rxbd_ring[i];
if (card->rx_buf_list[i]) {
skb = card->rx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(skb);
}
memset(desc, 0, sizeof(*desc));
}
card->rx_buf_list[i] = NULL;
}
return;
}
/* This function cleans up event buffer rings. If any of the buffer list has
* valid SKB address, associated SKB is freed.
*/
static void mwifiex_cleanup_evt_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_evt_buf_desc *desc;
struct sk_buff *skb;
int i;
for (i = 0; i < MWIFIEX_MAX_EVT_BD; i++) {
desc = card->evtbd_ring[i];
if (card->evt_buf_list[i]) {
skb = card->evt_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(skb);
}
card->evt_buf_list[i] = NULL;
memset(desc, 0, sizeof(*desc));
}
return;
}
/* This function creates buffer descriptor ring for TX
*/
static int mwifiex_pcie_create_txbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
/*
* driver maintaines the write pointer and firmware maintaines the read
* pointer. The write pointer starts at 0 (zero) while the read pointer
* starts at zero with rollover bit set
*/
card->txbd_wrptr = 0;
if (reg->pfu_enabled)
card->txbd_rdptr = 0;
else
card->txbd_rdptr |= reg->tx_rollover_ind;
/* allocate shared memory for the BD ring and divide the same in to
several descriptors */
if (reg->pfu_enabled)
card->txbd_ring_size = sizeof(struct mwifiex_pfu_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
else
card->txbd_ring_size = sizeof(struct mwifiex_pcie_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
mwifiex_dbg(adapter, INFO,
"info: txbd_ring: Allocating %d bytes\n",
card->txbd_ring_size);
card->txbd_ring_vbase = pci_alloc_consistent(card->dev,
card->txbd_ring_size,
&card->txbd_ring_pbase);
if (!card->txbd_ring_vbase) {
mwifiex_dbg(adapter, ERROR,
"allocate consistent memory (%d bytes) failed!\n",
card->txbd_ring_size);
return -ENOMEM;
}
mwifiex_dbg(adapter, DATA,
"info: txbd_ring - base: %p, pbase: %#x:%x, len: %x\n",
card->txbd_ring_vbase, (unsigned int)card->txbd_ring_pbase,
(u32)((u64)card->txbd_ring_pbase >> 32),
card->txbd_ring_size);
return mwifiex_init_txq_ring(adapter);
}
static int mwifiex_pcie_delete_txbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_cleanup_txq_ring(adapter);
if (card->txbd_ring_vbase)
pci_free_consistent(card->dev, card->txbd_ring_size,
card->txbd_ring_vbase,
card->txbd_ring_pbase);
card->txbd_ring_size = 0;
card->txbd_wrptr = 0;
card->txbd_rdptr = 0 | reg->tx_rollover_ind;
card->txbd_ring_vbase = NULL;
card->txbd_ring_pbase = 0;
return 0;
}
/*
* This function creates buffer descriptor ring for RX
*/
static int mwifiex_pcie_create_rxbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
/*
* driver maintaines the read pointer and firmware maintaines the write
* pointer. The write pointer starts at 0 (zero) while the read pointer
* starts at zero with rollover bit set
*/
card->rxbd_wrptr = 0;
card->rxbd_rdptr = reg->rx_rollover_ind;
if (reg->pfu_enabled)
card->rxbd_ring_size = sizeof(struct mwifiex_pfu_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
else
card->rxbd_ring_size = sizeof(struct mwifiex_pcie_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
mwifiex_dbg(adapter, INFO,
"info: rxbd_ring: Allocating %d bytes\n",
card->rxbd_ring_size);
card->rxbd_ring_vbase = pci_alloc_consistent(card->dev,
card->rxbd_ring_size,
&card->rxbd_ring_pbase);
if (!card->rxbd_ring_vbase) {
mwifiex_dbg(adapter, ERROR,
"allocate consistent memory (%d bytes) failed!\n",
card->rxbd_ring_size);
return -ENOMEM;
}
mwifiex_dbg(adapter, DATA,
"info: rxbd_ring - base: %p, pbase: %#x:%x, len: %#x\n",
card->rxbd_ring_vbase, (u32)card->rxbd_ring_pbase,
(u32)((u64)card->rxbd_ring_pbase >> 32),
card->rxbd_ring_size);
return mwifiex_init_rxq_ring(adapter);
}
/*
* This function deletes Buffer descriptor ring for RX
*/
static int mwifiex_pcie_delete_rxbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_cleanup_rxq_ring(adapter);
if (card->rxbd_ring_vbase)
pci_free_consistent(card->dev, card->rxbd_ring_size,
card->rxbd_ring_vbase,
card->rxbd_ring_pbase);
card->rxbd_ring_size = 0;
card->rxbd_wrptr = 0;
card->rxbd_rdptr = 0 | reg->rx_rollover_ind;
card->rxbd_ring_vbase = NULL;
card->rxbd_ring_pbase = 0;
return 0;
}
/*
* This function creates buffer descriptor ring for Events
*/
static int mwifiex_pcie_create_evtbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
/*
* driver maintaines the read pointer and firmware maintaines the write
* pointer. The write pointer starts at 0 (zero) while the read pointer
* starts at zero with rollover bit set
*/
card->evtbd_wrptr = 0;
card->evtbd_rdptr = reg->evt_rollover_ind;
card->evtbd_ring_size = sizeof(struct mwifiex_evt_buf_desc) *
MWIFIEX_MAX_EVT_BD;
mwifiex_dbg(adapter, INFO,
"info: evtbd_ring: Allocating %d bytes\n",
card->evtbd_ring_size);
card->evtbd_ring_vbase = pci_alloc_consistent(card->dev,
card->evtbd_ring_size,
&card->evtbd_ring_pbase);
if (!card->evtbd_ring_vbase) {
mwifiex_dbg(adapter, ERROR,
"allocate consistent memory (%d bytes) failed!\n",
card->evtbd_ring_size);
return -ENOMEM;
}
mwifiex_dbg(adapter, EVENT,
"info: CMDRSP/EVT bd_ring - base: %p pbase: %#x:%x len: %#x\n",
card->evtbd_ring_vbase, (u32)card->evtbd_ring_pbase,
(u32)((u64)card->evtbd_ring_pbase >> 32),
card->evtbd_ring_size);
return mwifiex_pcie_init_evt_ring(adapter);
}
/*
* This function deletes Buffer descriptor ring for Events
*/
static int mwifiex_pcie_delete_evtbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_cleanup_evt_ring(adapter);
if (card->evtbd_ring_vbase)
pci_free_consistent(card->dev, card->evtbd_ring_size,
card->evtbd_ring_vbase,
card->evtbd_ring_pbase);
card->evtbd_wrptr = 0;
card->evtbd_rdptr = 0 | reg->evt_rollover_ind;
card->evtbd_ring_size = 0;
card->evtbd_ring_vbase = NULL;
card->evtbd_ring_pbase = 0;
return 0;
}
/*
* This function allocates a buffer for CMDRSP
*/
static int mwifiex_pcie_alloc_cmdrsp_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct sk_buff *skb;
/* Allocate memory for receiving command response data */
skb = dev_alloc_skb(MWIFIEX_UPLD_SIZE);
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb for command response data.\n");
return -ENOMEM;
}
skb_put(skb, MWIFIEX_UPLD_SIZE);
if (mwifiex_map_pci_memory(adapter, skb, MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE)) {
kfree_skb(skb);
return -1;
}
card->cmdrsp_buf = skb;
return 0;
}
/*
* This function deletes a buffer for CMDRSP
*/
static int mwifiex_pcie_delete_cmdrsp_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card;
if (!adapter)
return 0;
card = adapter->card;
if (card && card->cmdrsp_buf) {
mwifiex_unmap_pci_memory(adapter, card->cmdrsp_buf,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(card->cmdrsp_buf);
card->cmdrsp_buf = NULL;
}
if (card && card->cmd_buf) {
mwifiex_unmap_pci_memory(adapter, card->cmd_buf,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(card->cmd_buf);
card->cmd_buf = NULL;
}
return 0;
}
/*
* This function allocates a buffer for sleep cookie
*/
static int mwifiex_pcie_alloc_sleep_cookie_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
u32 tmp;
card->sleep_cookie_vbase = pci_alloc_consistent(card->dev, sizeof(u32),
&card->sleep_cookie_pbase);
if (!card->sleep_cookie_vbase) {
mwifiex_dbg(adapter, ERROR,
"pci_alloc_consistent failed!\n");
return -ENOMEM;
}
/* Init val of Sleep Cookie */
tmp = FW_AWAKE_COOKIE;
put_unaligned(tmp, card->sleep_cookie_vbase);
mwifiex_dbg(adapter, INFO,
"alloc_scook: sleep cookie=0x%x\n",
get_unaligned(card->sleep_cookie_vbase));
return 0;
}
/*
* This function deletes buffer for sleep cookie
*/
static int mwifiex_pcie_delete_sleep_cookie_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card;
if (!adapter)
return 0;
card = adapter->card;
if (card && card->sleep_cookie_vbase) {
pci_free_consistent(card->dev, sizeof(u32),
card->sleep_cookie_vbase,
card->sleep_cookie_pbase);
card->sleep_cookie_vbase = NULL;
}
return 0;
}
/* This function flushes the TX buffer descriptor ring
* This function defined as handler is also called while cleaning TXRX
* during disconnect/ bss stop.
*/
static int mwifiex_clean_pcie_ring_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
if (!mwifiex_pcie_txbd_empty(card, card->txbd_rdptr)) {
card->txbd_flush = 1;
/* write pointer already set at last send
* send dnld-rdy intr again, wait for completion.
*/
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DNLD_RDY)) {
mwifiex_dbg(adapter, ERROR,
"failed to assert dnld-rdy interrupt.\n");
return -1;
}
}
return 0;
}
/*
* This function unmaps and frees downloaded data buffer
*/
static int mwifiex_pcie_send_data_complete(struct mwifiex_adapter *adapter)
{
struct sk_buff *skb;
u32 wrdoneidx, rdptr, num_tx_buffs, unmap_count = 0;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
/* Read the TX ring read pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->tx_rdptr, &rdptr)) {
mwifiex_dbg(adapter, ERROR,
"SEND COMP: failed to read reg->tx_rdptr\n");
return -1;
}
mwifiex_dbg(adapter, DATA,
"SEND COMP: rdptr_prev=0x%x, rdptr=0x%x\n",
card->txbd_rdptr, rdptr);
num_tx_buffs = MWIFIEX_MAX_TXRX_BD << reg->tx_start_ptr;
/* free from previous txbd_rdptr to current txbd_rdptr */
while (((card->txbd_rdptr & reg->tx_mask) !=
(rdptr & reg->tx_mask)) ||
((card->txbd_rdptr & reg->tx_rollover_ind) !=
(rdptr & reg->tx_rollover_ind))) {
wrdoneidx = (card->txbd_rdptr & reg->tx_mask) >>
reg->tx_start_ptr;
skb = card->tx_buf_list[wrdoneidx];
if (skb) {
mwifiex_dbg(adapter, DATA,
"SEND COMP: Detach skb %p at txbd_rdidx=%d\n",
skb, wrdoneidx);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
unmap_count++;
if (card->txbd_flush)
mwifiex_write_data_complete(adapter, skb, 0,
-1);
else
mwifiex_write_data_complete(adapter, skb, 0, 0);
atomic_dec(&adapter->tx_hw_pending);
}
card->tx_buf_list[wrdoneidx] = NULL;
if (reg->pfu_enabled) {
desc2 = card->txbd_ring[wrdoneidx];
memset(desc2, 0, sizeof(*desc2));
} else {
desc = card->txbd_ring[wrdoneidx];
memset(desc, 0, sizeof(*desc));
}
switch (card->dev->device) {
case PCIE_DEVICE_ID_MARVELL_88W8766P:
card->txbd_rdptr++;
break;
case PCIE_DEVICE_ID_MARVELL_88W8897:
case PCIE_DEVICE_ID_MARVELL_88W8997:
card->txbd_rdptr += reg->ring_tx_start_ptr;
break;
}
if ((card->txbd_rdptr & reg->tx_mask) == num_tx_buffs)
card->txbd_rdptr = ((card->txbd_rdptr &
reg->tx_rollover_ind) ^
reg->tx_rollover_ind);
}
if (unmap_count)
adapter->data_sent = false;
if (card->txbd_flush) {
if (mwifiex_pcie_txbd_empty(card, card->txbd_rdptr))
card->txbd_flush = 0;
else
mwifiex_clean_pcie_ring_buf(adapter);
}
return 0;
}
/* This function sends data buffer to device. First 4 bytes of payload
* are filled with payload length and payload type. Then this payload
* is mapped to PCI device memory. Tx ring pointers are advanced accordingly.
* Download ready interrupt to FW is deffered if Tx ring is not full and
* additional payload can be accomodated.
* Caller must ensure tx_param parameter to this function is not NULL.
*/
static int
mwifiex_pcie_send_data(struct mwifiex_adapter *adapter, struct sk_buff *skb,
struct mwifiex_tx_param *tx_param)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 wrindx, num_tx_buffs, rx_val;
int ret;
dma_addr_t buf_pa;
struct mwifiex_pcie_buf_desc *desc = NULL;
struct mwifiex_pfu_buf_desc *desc2 = NULL;
if (!(skb->data && skb->len)) {
mwifiex_dbg(adapter, ERROR,
"%s(): invalid parameter <%p, %#x>\n",
__func__, skb->data, skb->len);
return -1;
}
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
num_tx_buffs = MWIFIEX_MAX_TXRX_BD << reg->tx_start_ptr;
mwifiex_dbg(adapter, DATA,
"info: SEND DATA: <Rd: %#x, Wr: %#x>\n",
card->txbd_rdptr, card->txbd_wrptr);
if (mwifiex_pcie_txbd_not_full(card)) {
u8 *payload;
adapter->data_sent = true;
payload = skb->data;
put_unaligned_le16((u16)skb->len, payload + 0);
put_unaligned_le16(MWIFIEX_TYPE_DATA, payload + 2);
if (mwifiex_map_pci_memory(adapter, skb, skb->len,
PCI_DMA_TODEVICE))
return -1;
wrindx = (card->txbd_wrptr & reg->tx_mask) >> reg->tx_start_ptr;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
card->tx_buf_list[wrindx] = skb;
atomic_inc(&adapter->tx_hw_pending);
if (reg->pfu_enabled) {
desc2 = card->txbd_ring[wrindx];
desc2->paddr = buf_pa;
desc2->len = (u16)skb->len;
desc2->frag_len = (u16)skb->len;
desc2->offset = 0;
desc2->flags = MWIFIEX_BD_FLAG_FIRST_DESC |
MWIFIEX_BD_FLAG_LAST_DESC;
} else {
desc = card->txbd_ring[wrindx];
desc->paddr = buf_pa;
desc->len = (u16)skb->len;
desc->flags = MWIFIEX_BD_FLAG_FIRST_DESC |
MWIFIEX_BD_FLAG_LAST_DESC;
}
switch (card->dev->device) {
case PCIE_DEVICE_ID_MARVELL_88W8766P:
card->txbd_wrptr++;
break;
case PCIE_DEVICE_ID_MARVELL_88W8897:
case PCIE_DEVICE_ID_MARVELL_88W8997:
card->txbd_wrptr += reg->ring_tx_start_ptr;
break;
}
if ((card->txbd_wrptr & reg->tx_mask) == num_tx_buffs)
card->txbd_wrptr = ((card->txbd_wrptr &
reg->tx_rollover_ind) ^
reg->tx_rollover_ind);
rx_val = card->rxbd_rdptr & reg->rx_wrap_mask;
/* Write the TX ring write pointer in to reg->tx_wrptr */
if (mwifiex_write_reg(adapter, reg->tx_wrptr,
card->txbd_wrptr | rx_val)) {
mwifiex_dbg(adapter, ERROR,
"SEND DATA: failed to write reg->tx_wrptr\n");
ret = -1;
goto done_unmap;
}
if ((mwifiex_pcie_txbd_not_full(card)) &&
tx_param->next_pkt_len) {
/* have more packets and TxBD still can hold more */
mwifiex_dbg(adapter, DATA,
"SEND DATA: delay dnld-rdy interrupt.\n");
adapter->data_sent = false;
} else {
/* Send the TX ready interrupt */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DNLD_RDY)) {
mwifiex_dbg(adapter, ERROR,
"SEND DATA: failed to assert dnld-rdy interrupt.\n");
ret = -1;
goto done_unmap;
}
}
mwifiex_dbg(adapter, DATA,
"info: SEND DATA: Updated <Rd: %#x, Wr:\t"
"%#x> and sent packet to firmware successfully\n",
card->txbd_rdptr, card->txbd_wrptr);
} else {
mwifiex_dbg(adapter, DATA,
"info: TX Ring full, can't send packets to fw\n");
adapter->data_sent = true;
/* Send the TX ready interrupt */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DNLD_RDY))
mwifiex_dbg(adapter, ERROR,
"SEND DATA: failed to assert door-bell intr\n");
return -EBUSY;
}
return -EINPROGRESS;
done_unmap:
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
card->tx_buf_list[wrindx] = NULL;
atomic_dec(&adapter->tx_hw_pending);
if (reg->pfu_enabled)
memset(desc2, 0, sizeof(*desc2));
else
memset(desc, 0, sizeof(*desc));
return ret;
}
/*
* This function handles received buffer ring and
* dispatches packets to upper
*/
static int mwifiex_pcie_process_recv_data(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 wrptr, rd_index, tx_val;
dma_addr_t buf_pa;
int ret = 0;
struct sk_buff *skb_tmp = NULL;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
/* Read the RX ring Write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->rx_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"RECV DATA: failed to read reg->rx_wrptr\n");
ret = -1;
goto done;
}
card->rxbd_wrptr = wrptr;
while (((wrptr & reg->rx_mask) !=
(card->rxbd_rdptr & reg->rx_mask)) ||
((wrptr & reg->rx_rollover_ind) ==
(card->rxbd_rdptr & reg->rx_rollover_ind))) {
struct sk_buff *skb_data;
u16 rx_len;
rd_index = card->rxbd_rdptr & reg->rx_mask;
skb_data = card->rx_buf_list[rd_index];
/* If skb allocation was failed earlier for Rx packet,
* rx_buf_list[rd_index] would have been left with a NULL.
*/
if (!skb_data)
return -ENOMEM;
mwifiex_unmap_pci_memory(adapter, skb_data, PCI_DMA_FROMDEVICE);
card->rx_buf_list[rd_index] = NULL;
/* Get data length from interface header -
* first 2 bytes for len, next 2 bytes is for type
*/
rx_len = get_unaligned_le16(skb_data->data);
if (WARN_ON(rx_len <= adapter->intf_hdr_len ||
rx_len > MWIFIEX_RX_DATA_BUF_SIZE)) {
mwifiex_dbg(adapter, ERROR,
"Invalid RX len %d, Rd=%#x, Wr=%#x\n",
rx_len, card->rxbd_rdptr, wrptr);
dev_kfree_skb_any(skb_data);
} else {
skb_put(skb_data, rx_len);
mwifiex_dbg(adapter, DATA,
"info: RECV DATA: Rd=%#x, Wr=%#x, Len=%d\n",
card->rxbd_rdptr, wrptr, rx_len);
skb_pull(skb_data, adapter->intf_hdr_len);
if (adapter->rx_work_enabled) {
skb_queue_tail(&adapter->rx_data_q, skb_data);
adapter->data_received = true;
atomic_inc(&adapter->rx_pending);
} else {
mwifiex_handle_rx_packet(adapter, skb_data);
}
}
skb_tmp = mwifiex_alloc_dma_align_buf(MWIFIEX_RX_DATA_BUF_SIZE,
GFP_KERNEL);
if (!skb_tmp) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb.\n");
return -ENOMEM;
}
if (mwifiex_map_pci_memory(adapter, skb_tmp,
MWIFIEX_RX_DATA_BUF_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb_tmp);
mwifiex_dbg(adapter, INFO,
"RECV DATA: Attach new sk_buff %p at rxbd_rdidx=%d\n",
skb_tmp, rd_index);
card->rx_buf_list[rd_index] = skb_tmp;
if (reg->pfu_enabled) {
desc2 = card->rxbd_ring[rd_index];
desc2->paddr = buf_pa;
desc2->len = skb_tmp->len;
desc2->frag_len = skb_tmp->len;
desc2->offset = 0;
desc2->flags = reg->ring_flag_sop | reg->ring_flag_eop;
} else {
desc = card->rxbd_ring[rd_index];
desc->paddr = buf_pa;
desc->len = skb_tmp->len;
desc->flags = 0;
}
if ((++card->rxbd_rdptr & reg->rx_mask) ==
MWIFIEX_MAX_TXRX_BD) {
card->rxbd_rdptr = ((card->rxbd_rdptr &
reg->rx_rollover_ind) ^
reg->rx_rollover_ind);
}
mwifiex_dbg(adapter, DATA,
"info: RECV DATA: <Rd: %#x, Wr: %#x>\n",
card->rxbd_rdptr, wrptr);
tx_val = card->txbd_wrptr & reg->tx_wrap_mask;
/* Write the RX ring read pointer in to reg->rx_rdptr */
if (mwifiex_write_reg(adapter, reg->rx_rdptr,
card->rxbd_rdptr | tx_val)) {
mwifiex_dbg(adapter, DATA,
"RECV DATA: failed to write reg->rx_rdptr\n");
ret = -1;
goto done;
}
/* Read the RX ring Write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->rx_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"RECV DATA: failed to read reg->rx_wrptr\n");
ret = -1;
goto done;
}
mwifiex_dbg(adapter, DATA,
"info: RECV DATA: Rcvd packet from fw successfully\n");
card->rxbd_wrptr = wrptr;
}
done:
return ret;
}
/*
* This function downloads the boot command to device
*/
static int
mwifiex_pcie_send_boot_cmd(struct mwifiex_adapter *adapter, struct sk_buff *skb)
{
dma_addr_t buf_pa;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!(skb->data && skb->len)) {
mwifiex_dbg(adapter, ERROR,
"Invalid parameter in %s <%p. len %d>\n",
__func__, skb->data, skb->len);
return -1;
}
if (mwifiex_map_pci_memory(adapter, skb, skb->len, PCI_DMA_TODEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
/* Write the lower 32bits of the physical address to low command
* address scratch register
*/
if (mwifiex_write_reg(adapter, reg->cmd_addr_lo, (u32)buf_pa)) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to write download command to boot code.\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
/* Write the upper 32bits of the physical address to high command
* address scratch register
*/
if (mwifiex_write_reg(adapter, reg->cmd_addr_hi,
(u32)((u64)buf_pa >> 32))) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to write download command to boot code.\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
/* Write the command length to cmd_size scratch register */
if (mwifiex_write_reg(adapter, reg->cmd_size, skb->len)) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to write command len to cmd_size scratch reg\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
/* Ring the door bell */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DOOR_BELL)) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to assert door-bell intr\n", __func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
return 0;
}
/* This function init rx port in firmware which in turn enables to receive data
* from device before transmitting any packet.
*/
static int mwifiex_pcie_init_fw_port(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int tx_wrap = card->txbd_wrptr & reg->tx_wrap_mask;
/* Write the RX ring read pointer in to reg->rx_rdptr */
if (mwifiex_write_reg(adapter, reg->rx_rdptr, card->rxbd_rdptr |
tx_wrap)) {
mwifiex_dbg(adapter, ERROR,
"RECV DATA: failed to write reg->rx_rdptr\n");
return -1;
}
return 0;
}
/* This function downloads commands to the device
*/
static int
mwifiex_pcie_send_cmd(struct mwifiex_adapter *adapter, struct sk_buff *skb)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret = 0;
dma_addr_t cmd_buf_pa, cmdrsp_buf_pa;
u8 *payload = (u8 *)skb->data;
if (!(skb->data && skb->len)) {
mwifiex_dbg(adapter, ERROR,
"Invalid parameter in %s <%p, %#x>\n",
__func__, skb->data, skb->len);
return -1;
}
/* Make sure a command response buffer is available */
if (!card->cmdrsp_buf) {
mwifiex_dbg(adapter, ERROR,
"No response buffer available, send command failed\n");
return -EBUSY;
}
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
adapter->cmd_sent = true;
put_unaligned_le16((u16)skb->len, &payload[0]);
put_unaligned_le16(MWIFIEX_TYPE_CMD, &payload[2]);
if (mwifiex_map_pci_memory(adapter, skb, skb->len, PCI_DMA_TODEVICE))
return -1;
card->cmd_buf = skb;
/*
* Need to keep a reference, since core driver might free up this
* buffer before we've unmapped it.
*/
skb_get(skb);
/* To send a command, the driver will:
1. Write the 64bit physical address of the data buffer to
cmd response address low + cmd response address high
2. Ring the door bell (i.e. set the door bell interrupt)
In response to door bell interrupt, the firmware will perform
the DMA of the command packet (first header to obtain the total
length and then rest of the command).
*/
if (card->cmdrsp_buf) {
cmdrsp_buf_pa = MWIFIEX_SKB_DMA_ADDR(card->cmdrsp_buf);
/* Write the lower 32bits of the cmdrsp buffer physical
address */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_lo,
(u32)cmdrsp_buf_pa)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
/* Write the upper 32bits of the cmdrsp buffer physical
address */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_hi,
(u32)((u64)cmdrsp_buf_pa >> 32))) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
}
cmd_buf_pa = MWIFIEX_SKB_DMA_ADDR(card->cmd_buf);
/* Write the lower 32bits of the physical address to reg->cmd_addr_lo */
if (mwifiex_write_reg(adapter, reg->cmd_addr_lo,
(u32)cmd_buf_pa)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
/* Write the upper 32bits of the physical address to reg->cmd_addr_hi */
if (mwifiex_write_reg(adapter, reg->cmd_addr_hi,
(u32)((u64)cmd_buf_pa >> 32))) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
/* Write the command length to reg->cmd_size */
if (mwifiex_write_reg(adapter, reg->cmd_size,
card->cmd_buf->len)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write cmd len to reg->cmd_size\n");
ret = -1;
goto done;
}
/* Ring the door bell */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DOOR_BELL)) {
mwifiex_dbg(adapter, ERROR,
"Failed to assert door-bell intr\n");
ret = -1;
goto done;
}
done:
if (ret)
adapter->cmd_sent = false;
return 0;
}
/*
* This function handles command complete interrupt
*/
static int mwifiex_pcie_process_cmd_complete(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct sk_buff *skb = card->cmdrsp_buf;
int count = 0;
u16 rx_len;
mwifiex_dbg(adapter, CMD,
"info: Rx CMD Response\n");
if (adapter->curr_cmd)
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_FROMDEVICE);
else
pci_dma_sync_single_for_cpu(card->dev,
MWIFIEX_SKB_DMA_ADDR(skb),
MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE);
/* Unmap the command as a response has been received. */
if (card->cmd_buf) {
mwifiex_unmap_pci_memory(adapter, card->cmd_buf,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(card->cmd_buf);
card->cmd_buf = NULL;
}
rx_len = get_unaligned_le16(skb->data);
skb_put(skb, MWIFIEX_UPLD_SIZE - skb->len);
skb_trim(skb, rx_len);
if (!adapter->curr_cmd) {
if (adapter->ps_state == PS_STATE_SLEEP_CFM) {
pci_dma_sync_single_for_device(card->dev,
MWIFIEX_SKB_DMA_ADDR(skb),
MWIFIEX_SLEEP_COOKIE_SIZE,
PCI_DMA_FROMDEVICE);
if (mwifiex_write_reg(adapter,
PCIE_CPU_INT_EVENT,
CPU_INTR_SLEEP_CFM_DONE)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
mwifiex_delay_for_sleep_cookie(adapter,
MWIFIEX_MAX_DELAY_COUNT);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
skb_pull(skb, adapter->intf_hdr_len);
while (reg->sleep_cookie && (count++ < 10) &&
mwifiex_pcie_ok_to_access_hw(adapter))
usleep_range(50, 60);
mwifiex_pcie_enable_host_int(adapter);
mwifiex_process_sleep_confirm_resp(adapter, skb->data,
skb->len);
} else {
mwifiex_dbg(adapter, ERROR,
"There is no command but got cmdrsp\n");
}
memcpy(adapter->upld_buf, skb->data,
min_t(u32, MWIFIEX_SIZE_OF_CMD_BUFFER, skb->len));
skb_push(skb, adapter->intf_hdr_len);
if (mwifiex_map_pci_memory(adapter, skb, MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
} else if (mwifiex_pcie_ok_to_access_hw(adapter)) {
skb_pull(skb, adapter->intf_hdr_len);
adapter->curr_cmd->resp_skb = skb;
adapter->cmd_resp_received = true;
/* Take the pointer and set it to CMD node and will
return in the response complete callback */
card->cmdrsp_buf = NULL;
/* Clear the cmd-rsp buffer address in scratch registers. This
will prevent firmware from writing to the same response
buffer again. */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_lo, 0)) {
mwifiex_dbg(adapter, ERROR,
"cmd_done: failed to clear cmd_rsp_addr_lo\n");
return -1;
}
/* Write the upper 32bits of the cmdrsp buffer physical
address */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_hi, 0)) {
mwifiex_dbg(adapter, ERROR,
"cmd_done: failed to clear cmd_rsp_addr_hi\n");
return -1;
}
}
return 0;
}
/*
* Command Response processing complete handler
*/
static int mwifiex_pcie_cmdrsp_complete(struct mwifiex_adapter *adapter,
struct sk_buff *skb)
{
struct pcie_service_card *card = adapter->card;
if (skb) {
card->cmdrsp_buf = skb;
skb_push(card->cmdrsp_buf, adapter->intf_hdr_len);
if (mwifiex_map_pci_memory(adapter, skb, MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
}
return 0;
}
/*
* This function handles firmware event ready interrupt
*/
static int mwifiex_pcie_process_event_ready(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 rdptr = card->evtbd_rdptr & MWIFIEX_EVTBD_MASK;
u32 wrptr, event;
struct mwifiex_evt_buf_desc *desc;
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
if (adapter->event_received) {
mwifiex_dbg(adapter, EVENT,
"info: Event being processed,\t"
"do not process this interrupt just yet\n");
return 0;
}
if (rdptr >= MWIFIEX_MAX_EVT_BD) {
mwifiex_dbg(adapter, ERROR,
"info: Invalid read pointer...\n");
return -1;
}
/* Read the event ring write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->evt_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"EventReady: failed to read reg->evt_wrptr\n");
return -1;
}
mwifiex_dbg(adapter, EVENT,
"info: EventReady: Initial <Rd: 0x%x, Wr: 0x%x>",
card->evtbd_rdptr, wrptr);
if (((wrptr & MWIFIEX_EVTBD_MASK) != (card->evtbd_rdptr
& MWIFIEX_EVTBD_MASK)) ||
((wrptr & reg->evt_rollover_ind) ==
(card->evtbd_rdptr & reg->evt_rollover_ind))) {
struct sk_buff *skb_cmd;
__le16 data_len = 0;
u16 evt_len;
mwifiex_dbg(adapter, INFO,
"info: Read Index: %d\n", rdptr);
skb_cmd = card->evt_buf_list[rdptr];
mwifiex_unmap_pci_memory(adapter, skb_cmd, PCI_DMA_FROMDEVICE);
/* Take the pointer and set it to event pointer in adapter
and will return back after event handling callback */
card->evt_buf_list[rdptr] = NULL;
desc = card->evtbd_ring[rdptr];
memset(desc, 0, sizeof(*desc));
event = get_unaligned_le32(
&skb_cmd->data[adapter->intf_hdr_len]);
adapter->event_cause = event;
/* The first 4bytes will be the event transfer header
len is 2 bytes followed by type which is 2 bytes */
memcpy(&data_len, skb_cmd->data, sizeof(__le16));
evt_len = le16_to_cpu(data_len);
skb_trim(skb_cmd, evt_len);
skb_pull(skb_cmd, adapter->intf_hdr_len);
mwifiex_dbg(adapter, EVENT,
"info: Event length: %d\n", evt_len);
if (evt_len > MWIFIEX_EVENT_HEADER_LEN &&
evt_len < MAX_EVENT_SIZE)
memcpy(adapter->event_body, skb_cmd->data +
MWIFIEX_EVENT_HEADER_LEN, evt_len -
MWIFIEX_EVENT_HEADER_LEN);
adapter->event_received = true;
adapter->event_skb = skb_cmd;
/* Do not update the event read pointer here, wait till the
buffer is released. This is just to make things simpler,
we need to find a better method of managing these buffers.
*/
} else {
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_EVENT_DONE)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
}
return 0;
}
/*
* Event processing complete handler
*/
static int mwifiex_pcie_event_complete(struct mwifiex_adapter *adapter,
struct sk_buff *skb)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret = 0;
u32 rdptr = card->evtbd_rdptr & MWIFIEX_EVTBD_MASK;
u32 wrptr;
struct mwifiex_evt_buf_desc *desc;
if (!skb)
return 0;
if (rdptr >= MWIFIEX_MAX_EVT_BD) {
mwifiex_dbg(adapter, ERROR,
"event_complete: Invalid rdptr 0x%x\n",
rdptr);
return -EINVAL;
}
/* Read the event ring write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->evt_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"event_complete: failed to read reg->evt_wrptr\n");
return -1;
}
if (!card->evt_buf_list[rdptr]) {
skb_push(skb, adapter->intf_hdr_len);
skb_put(skb, MAX_EVENT_SIZE - skb->len);
if (mwifiex_map_pci_memory(adapter, skb,
MAX_EVENT_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
card->evt_buf_list[rdptr] = skb;
desc = card->evtbd_ring[rdptr];
desc->paddr = MWIFIEX_SKB_DMA_ADDR(skb);
desc->len = (u16)skb->len;
desc->flags = 0;
skb = NULL;
} else {
mwifiex_dbg(adapter, ERROR,
"info: ERROR: buf still valid at index %d, <%p, %p>\n",
rdptr, card->evt_buf_list[rdptr], skb);
}
if ((++card->evtbd_rdptr & MWIFIEX_EVTBD_MASK) == MWIFIEX_MAX_EVT_BD) {
card->evtbd_rdptr = ((card->evtbd_rdptr &
reg->evt_rollover_ind) ^
reg->evt_rollover_ind);
}
mwifiex_dbg(adapter, EVENT,
"info: Updated <Rd: 0x%x, Wr: 0x%x>",
card->evtbd_rdptr, wrptr);
/* Write the event ring read pointer in to reg->evt_rdptr */
if (mwifiex_write_reg(adapter, reg->evt_rdptr,
card->evtbd_rdptr)) {
mwifiex_dbg(adapter, ERROR,
"event_complete: failed to read reg->evt_rdptr\n");
return -1;
}
mwifiex_dbg(adapter, EVENT,
"info: Check Events Again\n");
ret = mwifiex_pcie_process_event_ready(adapter);
return ret;
}
/* Combo firmware image is a combination of
* (1) combo crc heaer, start with CMD5
* (2) bluetooth image, start with CMD7, end with CMD6, data wrapped in CMD1.
* (3) wifi image.
*
* This function bypass the header and bluetooth part, return
* the offset of tail wifi-only part. If the image is already wifi-only,
* that is start with CMD1, return 0.
*/
static int mwifiex_extract_wifi_fw(struct mwifiex_adapter *adapter,
const void *firmware, u32 firmware_len) {
const struct mwifiex_fw_data *fwdata;
u32 offset = 0, data_len, dnld_cmd;
int ret = 0;
bool cmd7_before = false, first_cmd = false;
while (1) {
/* Check for integer and buffer overflow */
if (offset + sizeof(fwdata->header) < sizeof(fwdata->header) ||
offset + sizeof(fwdata->header) >= firmware_len) {
mwifiex_dbg(adapter, ERROR,
"extract wifi-only fw failure!\n");
ret = -1;
goto done;
}
fwdata = firmware + offset;
dnld_cmd = le32_to_cpu(fwdata->header.dnld_cmd);
data_len = le32_to_cpu(fwdata->header.data_length);
/* Skip past header */
offset += sizeof(fwdata->header);
switch (dnld_cmd) {
case MWIFIEX_FW_DNLD_CMD_1:
if (offset + data_len < data_len) {
mwifiex_dbg(adapter, ERROR, "bad FW parse\n");
ret = -1;
goto done;
}
/* Image start with cmd1, already wifi-only firmware */
if (!first_cmd) {
mwifiex_dbg(adapter, MSG,
"input wifi-only firmware\n");
return 0;
}
if (!cmd7_before) {
mwifiex_dbg(adapter, ERROR,
"no cmd7 before cmd1!\n");
ret = -1;
goto done;
}
offset += data_len;
break;
case MWIFIEX_FW_DNLD_CMD_5:
first_cmd = true;
/* Check for integer overflow */
if (offset + data_len < data_len) {
mwifiex_dbg(adapter, ERROR, "bad FW parse\n");
ret = -1;
goto done;
}
offset += data_len;
break;
case MWIFIEX_FW_DNLD_CMD_6:
first_cmd = true;
/* Check for integer overflow */
if (offset + data_len < data_len) {
mwifiex_dbg(adapter, ERROR, "bad FW parse\n");
ret = -1;
goto done;
}
offset += data_len;
if (offset >= firmware_len) {
mwifiex_dbg(adapter, ERROR,
"extract wifi-only fw failure!\n");
ret = -1;
} else {
ret = offset;
}
goto done;
case MWIFIEX_FW_DNLD_CMD_7:
first_cmd = true;
cmd7_before = true;
break;
default:
mwifiex_dbg(adapter, ERROR, "unknown dnld_cmd %d\n",
dnld_cmd);
ret = -1;
goto done;
}
}
done:
return ret;
}
/*
* This function downloads the firmware to the card.
*
* Firmware is downloaded to the card in blocks. Every block download
* is tested for CRC errors, and retried a number of times before
* returning failure.
*/
static int mwifiex_prog_fw_w_helper(struct mwifiex_adapter *adapter,
struct mwifiex_fw_image *fw)
{
int ret;
u8 *firmware = fw->fw_buf;
u32 firmware_len = fw->fw_len;
u32 offset = 0;
struct sk_buff *skb;
u32 txlen, tx_blocks = 0, tries, len, val;
u32 block_retry_cnt = 0;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!firmware || !firmware_len) {
mwifiex_dbg(adapter, ERROR,
"No firmware image found! Terminating download\n");
return -1;
}
mwifiex_dbg(adapter, INFO,
"info: Downloading FW image (%d bytes)\n",
firmware_len);
if (mwifiex_pcie_disable_host_int(adapter)) {
mwifiex_dbg(adapter, ERROR,
"%s: Disabling interrupts failed.\n", __func__);
return -1;
}
skb = dev_alloc_skb(MWIFIEX_UPLD_SIZE);
if (!skb) {
ret = -ENOMEM;
goto done;
}
ret = mwifiex_read_reg(adapter, PCIE_SCRATCH_13_REG, &val);
if (ret) {
mwifiex_dbg(adapter, FATAL, "Failed to read scratch register 13\n");
goto done;
}
/* PCIE FLR case: extract wifi part from combo firmware*/
if (val == MWIFIEX_PCIE_FLR_HAPPENS) {
ret = mwifiex_extract_wifi_fw(adapter, firmware, firmware_len);
if (ret < 0) {
mwifiex_dbg(adapter, ERROR, "Failed to extract wifi fw\n");
goto done;
}
offset = ret;
mwifiex_dbg(adapter, MSG,
"info: dnld wifi firmware from %d bytes\n", offset);
}
/* Perform firmware data transfer */
do {
u32 ireg_intr = 0;
/* More data? */
if (offset >= firmware_len)
break;
for (tries = 0; tries < MAX_POLL_TRIES; tries++) {
ret = mwifiex_read_reg(adapter, reg->cmd_size,
&len);
if (ret) {
mwifiex_dbg(adapter, FATAL,
"Failed reading len from boot code\n");
goto done;
}
if (len)
break;
usleep_range(10, 20);
}
if (!len) {
break;
} else if (len > MWIFIEX_UPLD_SIZE) {
mwifiex_dbg(adapter, ERROR,
"FW download failure @ %d, invalid length %d\n",
offset, len);
ret = -1;
goto done;
}
txlen = len;
if (len & BIT(0)) {
block_retry_cnt++;
if (block_retry_cnt > MAX_WRITE_IOMEM_RETRY) {
mwifiex_dbg(adapter, ERROR,
"FW download failure @ %d, over max\t"
"retry count\n", offset);
ret = -1;
goto done;
}
mwifiex_dbg(adapter, ERROR,
"FW CRC error indicated by the\t"
"helper: len = 0x%04X, txlen = %d\n",
len, txlen);
len &= ~BIT(0);
/* Setting this to 0 to resend from same offset */
txlen = 0;
} else {
block_retry_cnt = 0;
/* Set blocksize to transfer - checking for
last block */
if (firmware_len - offset < txlen)
txlen = firmware_len - offset;
tx_blocks = (txlen + card->pcie.blksz_fw_dl - 1) /
card->pcie.blksz_fw_dl;
/* Copy payload to buffer */
memmove(skb->data, &firmware[offset], txlen);
}
skb_put(skb, MWIFIEX_UPLD_SIZE - skb->len);
skb_trim(skb, tx_blocks * card->pcie.blksz_fw_dl);
/* Send the boot command to device */
if (mwifiex_pcie_send_boot_cmd(adapter, skb)) {
mwifiex_dbg(adapter, ERROR,
"Failed to send firmware download command\n");
ret = -1;
goto done;
}
/* Wait for the command done interrupt */
for (tries = 0; tries < MAX_POLL_TRIES; tries++) {
if (mwifiex_read_reg(adapter, PCIE_CPU_INT_STATUS,
&ireg_intr)) {
mwifiex_dbg(adapter, ERROR,
"%s: Failed to read\t"
"interrupt status during fw dnld.\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
ret = -1;
goto done;
}
if (!(ireg_intr & CPU_INTR_DOOR_BELL))
break;
usleep_range(10, 20);
}
if (ireg_intr & CPU_INTR_DOOR_BELL) {
mwifiex_dbg(adapter, ERROR, "%s: Card failed to ACK download\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
ret = -1;
goto done;
}
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
offset += txlen;
} while (true);
mwifiex_dbg(adapter, MSG,
"info: FW download over, size %d bytes\n", offset);
ret = 0;
done:
dev_kfree_skb_any(skb);
return ret;
}
/*
* This function checks the firmware status in card.
*/
static int
mwifiex_check_fw_status(struct mwifiex_adapter *adapter, u32 poll_num)
{
int ret = 0;
u32 firmware_stat;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 tries;
/* Mask spurios interrupts */
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_STATUS_MASK,
HOST_INTR_MASK)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
mwifiex_dbg(adapter, INFO,
"Setting driver ready signature\n");
if (mwifiex_write_reg(adapter, reg->drv_rdy,
FIRMWARE_READY_PCIE)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write driver ready signature\n");
return -1;
}
/* Wait for firmware initialization event */
for (tries = 0; tries < poll_num; tries++) {
if (mwifiex_read_reg(adapter, reg->fw_status,
&firmware_stat))
ret = -1;
else
ret = 0;
mwifiex_dbg(adapter, INFO, "Try %d if FW is ready <%d,%#x>",
tries, ret, firmware_stat);
if (ret)
continue;
if (firmware_stat == FIRMWARE_READY_PCIE) {
ret = 0;
break;
} else {
msleep(100);
ret = -1;
}
}
return ret;
}
/* This function checks if WLAN is the winner.
*/
static int
mwifiex_check_winner_status(struct mwifiex_adapter *adapter)
{
u32 winner = 0;
int ret = 0;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (mwifiex_read_reg(adapter, reg->fw_status, &winner)) {
ret = -1;
} else if (!winner) {
mwifiex_dbg(adapter, INFO, "PCI-E is the winner\n");
adapter->winner = 1;
} else {
mwifiex_dbg(adapter, ERROR,
"PCI-E is not the winner <%#x>", winner);
}
return ret;
}
/*
* This function reads the interrupt status from card.
*/
static void mwifiex_interrupt_status(struct mwifiex_adapter *adapter,
int msg_id)
{
u32 pcie_ireg;
unsigned long flags;
struct pcie_service_card *card = adapter->card;
if (card->msi_enable) {
spin_lock_irqsave(&adapter->int_lock, flags);
adapter->int_status = 1;
spin_unlock_irqrestore(&adapter->int_lock, flags);
return;
}
if (!mwifiex_pcie_ok_to_access_hw(adapter))
return;
if (card->msix_enable && msg_id >= 0) {
pcie_ireg = BIT(msg_id);
} else {
if (mwifiex_read_reg(adapter, PCIE_HOST_INT_STATUS,
&pcie_ireg)) {
mwifiex_dbg(adapter, ERROR, "Read register failed\n");
return;
}
if ((pcie_ireg == 0xFFFFFFFF) || !pcie_ireg)
return;
mwifiex_pcie_disable_host_int(adapter);
/* Clear the pending interrupts */
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_STATUS,
~pcie_ireg)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return;
}
}
if (!adapter->pps_uapsd_mode &&
adapter->ps_state == PS_STATE_SLEEP &&
mwifiex_pcie_ok_to_access_hw(adapter)) {
/* Potentially for PCIe we could get other
* interrupts like shared. Don't change power
* state until cookie is set
*/
adapter->ps_state = PS_STATE_AWAKE;
adapter->pm_wakeup_fw_try = false;
del_timer(&adapter->wakeup_timer);
}
spin_lock_irqsave(&adapter->int_lock, flags);
adapter->int_status |= pcie_ireg;
spin_unlock_irqrestore(&adapter->int_lock, flags);
mwifiex_dbg(adapter, INTR, "ireg: 0x%08x\n", pcie_ireg);
}
/*
* Interrupt handler for PCIe root port
*
* This function reads the interrupt status from firmware and assigns
* the main process in workqueue which will handle the interrupt.
*/
static irqreturn_t mwifiex_pcie_interrupt(int irq, void *context)
{
struct mwifiex_msix_context *ctx = context;
struct pci_dev *pdev = ctx->dev;
struct pcie_service_card *card;
struct mwifiex_adapter *adapter;
card = pci_get_drvdata(pdev);
if (!card->adapter) {
pr_err("info: %s: card=%p adapter=%p\n", __func__, card,
card ? card->adapter : NULL);
goto exit;
}
adapter = card->adapter;
if (test_bit(MWIFIEX_SURPRISE_REMOVED, &adapter->work_flags))
goto exit;
if (card->msix_enable)
mwifiex_interrupt_status(adapter, ctx->msg_id);
else
mwifiex_interrupt_status(adapter, -1);
mwifiex_queue_main_work(adapter);
exit:
return IRQ_HANDLED;
}
/*
* This function checks the current interrupt status.
*
* The following interrupts are checked and handled by this function -
* - Data sent
* - Command sent
* - Command received
* - Packets received
* - Events received
*
* In case of Rx packets received, the packets are uploaded from card to
* host and processed accordingly.
*/
static int mwifiex_process_int_status(struct mwifiex_adapter *adapter)
{
int ret;
u32 pcie_ireg = 0;
unsigned long flags;
struct pcie_service_card *card = adapter->card;
spin_lock_irqsave(&adapter->int_lock, flags);
if (!card->msi_enable) {
/* Clear out unused interrupts */
pcie_ireg = adapter->int_status;
}
adapter->int_status = 0;
spin_unlock_irqrestore(&adapter->int_lock, flags);
if (card->msi_enable) {
if (mwifiex_pcie_ok_to_access_hw(adapter)) {
if (mwifiex_read_reg(adapter, PCIE_HOST_INT_STATUS,
&pcie_ireg)) {
mwifiex_dbg(adapter, ERROR,
"Read register failed\n");
return -1;
}
if ((pcie_ireg != 0xFFFFFFFF) && (pcie_ireg)) {
if (mwifiex_write_reg(adapter,
PCIE_HOST_INT_STATUS,
~pcie_ireg)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
if (!adapter->pps_uapsd_mode &&
adapter->ps_state == PS_STATE_SLEEP) {
adapter->ps_state = PS_STATE_AWAKE;
adapter->pm_wakeup_fw_try = false;
del_timer(&adapter->wakeup_timer);
}
}
}
}
if (pcie_ireg & HOST_INTR_DNLD_DONE) {
mwifiex_dbg(adapter, INTR, "info: TX DNLD Done\n");
ret = mwifiex_pcie_send_data_complete(adapter);
if (ret)
return ret;
}
if (pcie_ireg & HOST_INTR_UPLD_RDY) {
mwifiex_dbg(adapter, INTR, "info: Rx DATA\n");
ret = mwifiex_pcie_process_recv_data(adapter);
if (ret)
return ret;
}
if (pcie_ireg & HOST_INTR_EVENT_RDY) {
mwifiex_dbg(adapter, INTR, "info: Rx EVENT\n");
ret = mwifiex_pcie_process_event_ready(adapter);
if (ret)
return ret;
}
if (pcie_ireg & HOST_INTR_CMD_DONE) {
if (adapter->cmd_sent) {
mwifiex_dbg(adapter, INTR,
"info: CMD sent Interrupt\n");
adapter->cmd_sent = false;
}
/* Handle command response */
ret = mwifiex_pcie_process_cmd_complete(adapter);
if (ret)
return ret;
}
mwifiex_dbg(adapter, INTR,
"info: cmd_sent=%d data_sent=%d\n",
adapter->cmd_sent, adapter->data_sent);
if (!card->msi_enable && !card->msix_enable &&
adapter->ps_state != PS_STATE_SLEEP)
mwifiex_pcie_enable_host_int(adapter);
return 0;
}
/*
* This function downloads data from driver to card.
*
* Both commands and data packets are transferred to the card by this
* function.
*
* This function adds the PCIE specific header to the front of the buffer
* before transferring. The header contains the length of the packet and
* the type. The firmware handles the packets based upon this set type.
*/
static int mwifiex_pcie_host_to_card(struct mwifiex_adapter *adapter, u8 type,
struct sk_buff *skb,
struct mwifiex_tx_param *tx_param)
{
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Passed NULL skb to %s\n", __func__);
return -1;
}
if (type == MWIFIEX_TYPE_DATA)
return mwifiex_pcie_send_data(adapter, skb, tx_param);
else if (type == MWIFIEX_TYPE_CMD)
return mwifiex_pcie_send_cmd(adapter, skb);
return 0;
}
/* Function to dump PCIE scratch registers in case of FW crash
*/
static int
mwifiex_pcie_reg_dump(struct mwifiex_adapter *adapter, char *drv_buf)
{
char *p = drv_buf;
char buf[256], *ptr;
int i;
u32 value;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int pcie_scratch_reg[] = {PCIE_SCRATCH_12_REG,
PCIE_SCRATCH_14_REG,
PCIE_SCRATCH_15_REG};
if (!p)
return 0;
mwifiex_dbg(adapter, MSG, "PCIE register dump start\n");
if (mwifiex_read_reg(adapter, reg->fw_status, &value)) {
mwifiex_dbg(adapter, ERROR, "failed to read firmware status");
return 0;
}
ptr = buf;
mwifiex_dbg(adapter, MSG, "pcie scratch register:");
for (i = 0; i < ARRAY_SIZE(pcie_scratch_reg); i++) {
mwifiex_read_reg(adapter, pcie_scratch_reg[i], &value);
ptr += sprintf(ptr, "reg:0x%x, value=0x%x\n",
pcie_scratch_reg[i], value);
}
mwifiex_dbg(adapter, MSG, "%s\n", buf);
p += sprintf(p, "%s\n", buf);
mwifiex_dbg(adapter, MSG, "PCIE register dump end\n");
return p - drv_buf;
}
/* This function read/write firmware */
static enum rdwr_status
mwifiex_pcie_rdwr_firmware(struct mwifiex_adapter *adapter, u8 doneflag)
{
int ret, tries;
u8 ctrl_data;
u32 fw_status;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (mwifiex_read_reg(adapter, reg->fw_status, &fw_status))
return RDWR_STATUS_FAILURE;
ret = mwifiex_write_reg(adapter, reg->fw_dump_ctrl,
reg->fw_dump_host_ready);
if (ret) {
mwifiex_dbg(adapter, ERROR,
"PCIE write err\n");
return RDWR_STATUS_FAILURE;
}
for (tries = 0; tries < MAX_POLL_TRIES; tries++) {
mwifiex_read_reg_byte(adapter, reg->fw_dump_ctrl, &ctrl_data);
if (ctrl_data == FW_DUMP_DONE)
return RDWR_STATUS_SUCCESS;
if (doneflag && ctrl_data == doneflag)
return RDWR_STATUS_DONE;
if (ctrl_data != reg->fw_dump_host_ready) {
mwifiex_dbg(adapter, WARN,
"The ctrl reg was changed, re-try again!\n");
ret = mwifiex_write_reg(adapter, reg->fw_dump_ctrl,
reg->fw_dump_host_ready);
if (ret) {
mwifiex_dbg(adapter, ERROR,
"PCIE write err\n");
return RDWR_STATUS_FAILURE;
}
}
usleep_range(100, 200);
}
mwifiex_dbg(adapter, ERROR, "Fail to pull ctrl_data\n");
return RDWR_STATUS_FAILURE;
}
/* This function dump firmware memory to file */
static void mwifiex_pcie_fw_dump(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *creg = card->pcie.reg;
unsigned int reg, reg_start, reg_end;
u8 *dbg_ptr, *end_ptr, *tmp_ptr, fw_dump_num, dump_num;
u8 idx, i, read_reg, doneflag = 0;
enum rdwr_status stat;
u32 memory_size;
int ret;
if (!card->pcie.can_dump_fw)
return;
for (idx = 0; idx < adapter->num_mem_types; idx++) {
struct memory_type_mapping *entry =
&adapter->mem_type_mapping_tbl[idx];
if (entry->mem_ptr) {
vfree(entry->mem_ptr);
entry->mem_ptr = NULL;
}
entry->mem_size = 0;
}
mwifiex_dbg(adapter, MSG, "== mwifiex firmware dump start ==\n");
/* Read the number of the memories which will dump */
stat = mwifiex_pcie_rdwr_firmware(adapter, doneflag);
if (stat == RDWR_STATUS_FAILURE)
return;
reg = creg->fw_dump_start;
mwifiex_read_reg_byte(adapter, reg, &fw_dump_num);
/* W8997 chipset firmware dump will be restore in single region*/
if (fw_dump_num == 0)
dump_num = 1;
else
dump_num = fw_dump_num;
/* Read the length of every memory which will dump */
for (idx = 0; idx < dump_num; idx++) {
struct memory_type_mapping *entry =
&adapter->mem_type_mapping_tbl[idx];
memory_size = 0;
if (fw_dump_num != 0) {
stat = mwifiex_pcie_rdwr_firmware(adapter, doneflag);
if (stat == RDWR_STATUS_FAILURE)
return;
reg = creg->fw_dump_start;
for (i = 0; i < 4; i++) {
mwifiex_read_reg_byte(adapter, reg, &read_reg);
memory_size |= (read_reg << (i * 8));
reg++;
}
} else {
memory_size = MWIFIEX_FW_DUMP_MAX_MEMSIZE;
}
if (memory_size == 0) {
mwifiex_dbg(adapter, MSG, "Firmware dump Finished!\n");
ret = mwifiex_write_reg(adapter, creg->fw_dump_ctrl,
creg->fw_dump_read_done);
if (ret) {
mwifiex_dbg(adapter, ERROR, "PCIE write err\n");
return;
}
break;
}
mwifiex_dbg(adapter, DUMP,
"%s_SIZE=0x%x\n", entry->mem_name, memory_size);
entry->mem_ptr = vmalloc(memory_size + 1);
entry->mem_size = memory_size;
if (!entry->mem_ptr) {
mwifiex_dbg(adapter, ERROR,
"Vmalloc %s failed\n", entry->mem_name);
return;
}
dbg_ptr = entry->mem_ptr;
end_ptr = dbg_ptr + memory_size;
doneflag = entry->done_flag;
mwifiex_dbg(adapter, DUMP, "Start %s output, please wait...\n",
entry->mem_name);
do {
stat = mwifiex_pcie_rdwr_firmware(adapter, doneflag);
if (RDWR_STATUS_FAILURE == stat)
return;
reg_start = creg->fw_dump_start;
reg_end = creg->fw_dump_end;
for (reg = reg_start; reg <= reg_end; reg++) {
mwifiex_read_reg_byte(adapter, reg, dbg_ptr);
if (dbg_ptr < end_ptr) {
dbg_ptr++;
continue;
}
mwifiex_dbg(adapter, ERROR,
"pre-allocated buf not enough\n");
tmp_ptr =
vzalloc(memory_size + MWIFIEX_SIZE_4K);
if (!tmp_ptr)
return;
memcpy(tmp_ptr, entry->mem_ptr, memory_size);
vfree(entry->mem_ptr);
entry->mem_ptr = tmp_ptr;
tmp_ptr = NULL;
dbg_ptr = entry->mem_ptr + memory_size;
memory_size += MWIFIEX_SIZE_4K;
end_ptr = entry->mem_ptr + memory_size;
}
if (stat != RDWR_STATUS_DONE)
continue;
mwifiex_dbg(adapter, DUMP,
"%s done: size=0x%tx\n",
entry->mem_name, dbg_ptr - entry->mem_ptr);
break;
} while (true);
}
mwifiex_dbg(adapter, MSG, "== mwifiex firmware dump end ==\n");
}
static void mwifiex_pcie_device_dump_work(struct mwifiex_adapter *adapter)
{
adapter->devdump_data = vzalloc(MWIFIEX_FW_DUMP_SIZE);
if (!adapter->devdump_data) {
mwifiex_dbg(adapter, ERROR,
"vzalloc devdump data failure!\n");
return;
}
mwifiex_drv_info_dump(adapter);
mwifiex_pcie_fw_dump(adapter);
mwifiex_prepare_fw_dump_info(adapter);
mwifiex_upload_device_dump(adapter);
}
static void mwifiex_pcie_card_reset_work(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
/* We can't afford to wait here; remove() might be waiting on us. If we
* can't grab the device lock, maybe we'll get another chance later.
*/
pci_try_reset_function(card->dev);
}
static void mwifiex_pcie_work(struct work_struct *work)
{
struct pcie_service_card *card =
container_of(work, struct pcie_service_card, work);
if (test_and_clear_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP,
&card->work_flags))
mwifiex_pcie_device_dump_work(card->adapter);
if (test_and_clear_bit(MWIFIEX_IFACE_WORK_CARD_RESET,
&card->work_flags))
mwifiex_pcie_card_reset_work(card->adapter);
}
/* This function dumps FW information */
static void mwifiex_pcie_device_dump(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
if (!test_and_set_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP,
&card->work_flags))
schedule_work(&card->work);
}
static void mwifiex_pcie_card_reset(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
if (!test_and_set_bit(MWIFIEX_IFACE_WORK_CARD_RESET, &card->work_flags))
schedule_work(&card->work);
}
static int mwifiex_pcie_alloc_buffers(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret;
card->cmdrsp_buf = NULL;
ret = mwifiex_pcie_create_txbd_ring(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to create txbd ring\n");
goto err_cre_txbd;
}
ret = mwifiex_pcie_create_rxbd_ring(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to create rxbd ring\n");
goto err_cre_rxbd;
}
ret = mwifiex_pcie_create_evtbd_ring(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to create evtbd ring\n");
goto err_cre_evtbd;
}
ret = mwifiex_pcie_alloc_cmdrsp_buf(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to allocate cmdbuf buffer\n");
goto err_alloc_cmdbuf;
}
if (reg->sleep_cookie) {
ret = mwifiex_pcie_alloc_sleep_cookie_buf(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to allocate sleep_cookie buffer\n");
goto err_alloc_cookie;
}
} else {
card->sleep_cookie_vbase = NULL;
}
return 0;
err_alloc_cookie:
mwifiex_pcie_delete_cmdrsp_buf(adapter);
err_alloc_cmdbuf:
mwifiex_pcie_delete_evtbd_ring(adapter);
err_cre_evtbd:
mwifiex_pcie_delete_rxbd_ring(adapter);
err_cre_rxbd:
mwifiex_pcie_delete_txbd_ring(adapter);
err_cre_txbd:
return ret;
}
static void mwifiex_pcie_free_buffers(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (reg->sleep_cookie)
mwifiex_pcie_delete_sleep_cookie_buf(adapter);
mwifiex_pcie_delete_cmdrsp_buf(adapter);
mwifiex_pcie_delete_evtbd_ring(adapter);
mwifiex_pcie_delete_rxbd_ring(adapter);
mwifiex_pcie_delete_txbd_ring(adapter);
}
/*
* This function initializes the PCI-E host memory space, WCB rings, etc.
*/
static int mwifiex_init_pcie(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
int ret;
struct pci_dev *pdev = card->dev;
pci_set_drvdata(pdev, card);
ret = pci_enable_device(pdev);
if (ret)
goto err_enable_dev;
pci_set_master(pdev);
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
pr_err("set_dma_mask(32) failed: %d\n", ret);
goto err_set_dma_mask;
}
ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
pr_err("set_consistent_dma_mask(64) failed\n");
goto err_set_dma_mask;
}
ret = pci_request_region(pdev, 0, DRV_NAME);
if (ret) {
pr_err("req_reg(0) error\n");
goto err_req_region0;
}
card->pci_mmap = pci_iomap(pdev, 0, 0);
if (!card->pci_mmap) {
pr_err("iomap(0) error\n");
ret = -EIO;
goto err_iomap0;
}
ret = pci_request_region(pdev, 2, DRV_NAME);
if (ret) {
pr_err("req_reg(2) error\n");
goto err_req_region2;
}
card->pci_mmap1 = pci_iomap(pdev, 2, 0);
if (!card->pci_mmap1) {
pr_err("iomap(2) error\n");
ret = -EIO;
goto err_iomap2;
}
pr_notice("PCI memory map Virt0: %pK PCI memory map Virt2: %pK\n",
card->pci_mmap, card->pci_mmap1);
ret = mwifiex_pcie_alloc_buffers(adapter);
if (ret)
goto err_alloc_buffers;
return 0;
err_alloc_buffers:
pci_iounmap(pdev, card->pci_mmap1);
err_iomap2:
pci_release_region(pdev, 2);
err_req_region2:
pci_iounmap(pdev, card->pci_mmap);
err_iomap0:
pci_release_region(pdev, 0);
err_req_region0:
err_set_dma_mask:
pci_disable_device(pdev);
err_enable_dev:
return ret;
}
/*
* This function cleans up the allocated card buffers.
*/
static void mwifiex_cleanup_pcie(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret;
u32 fw_status;
cancel_work_sync(&card->work);
ret = mwifiex_read_reg(adapter, reg->fw_status, &fw_status);
if (fw_status == FIRMWARE_READY_PCIE) {
mwifiex_dbg(adapter, INFO,
"Clearing driver ready signature\n");
if (mwifiex_write_reg(adapter, reg->drv_rdy, 0x00000000))
mwifiex_dbg(adapter, ERROR,
"Failed to write driver not-ready signature\n");
}
pci_disable_device(pdev);
pci_iounmap(pdev, card->pci_mmap);
pci_iounmap(pdev, card->pci_mmap1);
pci_release_region(pdev, 2);
pci_release_region(pdev, 0);
mwifiex_pcie_free_buffers(adapter);
}
static int mwifiex_pcie_request_irq(struct mwifiex_adapter *adapter)
{
int ret, i, j;
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
if (card->pcie.reg->msix_support) {
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++)
card->msix_entries[i].entry = i;
ret = pci_enable_msix_exact(pdev, card->msix_entries,
MWIFIEX_NUM_MSIX_VECTORS);
if (!ret) {
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++) {
card->msix_ctx[i].dev = pdev;
card->msix_ctx[i].msg_id = i;
ret = request_irq(card->msix_entries[i].vector,
mwifiex_pcie_interrupt, 0,
"MWIFIEX_PCIE_MSIX",
&card->msix_ctx[i]);
if (ret)
break;
}
if (ret) {
mwifiex_dbg(adapter, INFO, "request_irq fail: %d\n",
ret);
for (j = 0; j < i; j++)
free_irq(card->msix_entries[j].vector,
&card->msix_ctx[i]);
pci_disable_msix(pdev);
} else {
mwifiex_dbg(adapter, MSG, "MSIx enabled!");
card->msix_enable = 1;
return 0;
}
}
}
if (pci_enable_msi(pdev) != 0)
pci_disable_msi(pdev);
else
card->msi_enable = 1;
mwifiex_dbg(adapter, INFO, "msi_enable = %d\n", card->msi_enable);
card->share_irq_ctx.dev = pdev;
card->share_irq_ctx.msg_id = -1;
ret = request_irq(pdev->irq, mwifiex_pcie_interrupt, IRQF_SHARED,
"MRVL_PCIE", &card->share_irq_ctx);
if (ret) {
pr_err("request_irq failed: ret=%d\n", ret);
return -1;
}
return 0;
}
/*
* This function gets the firmware name for downloading by revision id
*
* Read revision id register to get revision id
*/
static void mwifiex_pcie_get_fw_name(struct mwifiex_adapter *adapter)
{
int revision_id = 0;
int version, magic;
struct pcie_service_card *card = adapter->card;
switch (card->dev->device) {
case PCIE_DEVICE_ID_MARVELL_88W8766P:
strcpy(adapter->fw_name, PCIE8766_DEFAULT_FW_NAME);
break;
case PCIE_DEVICE_ID_MARVELL_88W8897:
mwifiex_write_reg(adapter, 0x0c58, 0x80c00000);
mwifiex_read_reg(adapter, 0x0c58, &revision_id);
revision_id &= 0xff00;
switch (revision_id) {
case PCIE8897_A0:
strcpy(adapter->fw_name, PCIE8897_A0_FW_NAME);
break;
case PCIE8897_B0:
strcpy(adapter->fw_name, PCIE8897_B0_FW_NAME);
break;
default:
strcpy(adapter->fw_name, PCIE8897_DEFAULT_FW_NAME);
break;
}
break;
case PCIE_DEVICE_ID_MARVELL_88W8997:
mwifiex_read_reg(adapter, 0x8, &revision_id);
mwifiex_read_reg(adapter, 0x0cd0, &version);
mwifiex_read_reg(adapter, 0x0cd4, &magic);
revision_id &= 0xff;
version &= 0x7;
magic &= 0xff;
if (revision_id == PCIE8997_A1 &&
magic == CHIP_MAGIC_VALUE &&
version == CHIP_VER_PCIEUART)
strcpy(adapter->fw_name, PCIEUART8997_FW_NAME_V4);
else
strcpy(adapter->fw_name, PCIEUSB8997_FW_NAME_V4);
break;
default:
break;
}
}
/*
* This function registers the PCIE device.
*
* PCIE IRQ is claimed, block size is set and driver data is initialized.
*/
static int mwifiex_register_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
/* save adapter pointer in card */
card->adapter = adapter;
if (mwifiex_pcie_request_irq(adapter))
return -1;
adapter->tx_buf_size = card->pcie.tx_buf_size;
adapter->mem_type_mapping_tbl = card->pcie.mem_type_mapping_tbl;
adapter->num_mem_types = card->pcie.num_mem_types;
adapter->ext_scan = card->pcie.can_ext_scan;
mwifiex_pcie_get_fw_name(adapter);
return 0;
}
/*
* This function unregisters the PCIE device.
*
* The PCIE IRQ is released, the function is disabled and driver
* data is set to null.
*/
static void mwifiex_unregister_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
int i;
if (card->msix_enable) {
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++)
synchronize_irq(card->msix_entries[i].vector);
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++)
free_irq(card->msix_entries[i].vector,
&card->msix_ctx[i]);
card->msix_enable = 0;
pci_disable_msix(pdev);
} else {
mwifiex_dbg(adapter, INFO,
"%s(): calling free_irq()\n", __func__);
free_irq(card->dev->irq, &card->share_irq_ctx);
if (card->msi_enable)
pci_disable_msi(pdev);
}
card->adapter = NULL;
}
/*
* This function initializes the PCI-E host memory space, WCB rings, etc.,
* similar to mwifiex_init_pcie(), but without resetting PCI-E state.
*/
static void mwifiex_pcie_up_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
/* tx_buf_size might be changed to 3584 by firmware during
* data transfer, we should reset it to default size.
*/
adapter->tx_buf_size = card->pcie.tx_buf_size;
mwifiex_pcie_alloc_buffers(adapter);
pci_set_master(pdev);
}
/* This function cleans up the PCI-E host memory space. */
static void mwifiex_pcie_down_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct pci_dev *pdev = card->dev;
if (mwifiex_write_reg(adapter, reg->drv_rdy, 0x00000000))
mwifiex_dbg(adapter, ERROR, "Failed to write driver not-ready signature\n");
pci_clear_master(pdev);
adapter->seq_num = 0;
mwifiex_pcie_free_buffers(adapter);
}
static struct mwifiex_if_ops pcie_ops = {
.init_if = mwifiex_init_pcie,
.cleanup_if = mwifiex_cleanup_pcie,
.check_fw_status = mwifiex_check_fw_status,
.check_winner_status = mwifiex_check_winner_status,
.prog_fw = mwifiex_prog_fw_w_helper,
.register_dev = mwifiex_register_dev,
.unregister_dev = mwifiex_unregister_dev,
.enable_int = mwifiex_pcie_enable_host_int,
.disable_int = mwifiex_pcie_disable_host_int_noerr,
.process_int_status = mwifiex_process_int_status,
.host_to_card = mwifiex_pcie_host_to_card,
.wakeup = mwifiex_pm_wakeup_card,
.wakeup_complete = mwifiex_pm_wakeup_card_complete,
/* PCIE specific */
.cmdrsp_complete = mwifiex_pcie_cmdrsp_complete,
.event_complete = mwifiex_pcie_event_complete,
.update_mp_end_port = NULL,
.cleanup_mpa_buf = NULL,
.init_fw_port = mwifiex_pcie_init_fw_port,
.clean_pcie_ring = mwifiex_clean_pcie_ring_buf,
.card_reset = mwifiex_pcie_card_reset,
.reg_dump = mwifiex_pcie_reg_dump,
.device_dump = mwifiex_pcie_device_dump,
.down_dev = mwifiex_pcie_down_dev,
.up_dev = mwifiex_pcie_up_dev,
};
module_pci_driver(mwifiex_pcie);
MODULE_AUTHOR("Marvell International Ltd.");
MODULE_DESCRIPTION("Marvell WiFi-Ex PCI-Express Driver version " PCIE_VERSION);
MODULE_VERSION(PCIE_VERSION);
MODULE_LICENSE("GPL v2");
| ./CrossVul/dataset_final_sorted/CWE-400/c/bad_1247_0 |
crossvul-cpp_data_bad_1266_0 | // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
/* Copyright (C) 2018 Netronome Systems, Inc. */
#include <linux/bitfield.h>
#include <net/pkt_cls.h>
#include "../nfpcore/nfp_cpp.h"
#include "../nfp_app.h"
#include "../nfp_net_repr.h"
#include "main.h"
struct nfp_abm_u32_match {
u32 handle;
u32 band;
u8 mask;
u8 val;
struct list_head list;
};
static bool
nfp_abm_u32_check_knode(struct nfp_abm *abm, struct tc_cls_u32_knode *knode,
__be16 proto, struct netlink_ext_ack *extack)
{
struct tc_u32_key *k;
unsigned int tos_off;
if (knode->exts && tcf_exts_has_actions(knode->exts)) {
NL_SET_ERR_MSG_MOD(extack, "action offload not supported");
return false;
}
if (knode->link_handle) {
NL_SET_ERR_MSG_MOD(extack, "linking not supported");
return false;
}
if (knode->sel->flags != TC_U32_TERMINAL) {
NL_SET_ERR_MSG_MOD(extack,
"flags must be equal to TC_U32_TERMINAL");
return false;
}
if (knode->sel->off || knode->sel->offshift || knode->sel->offmask ||
knode->sel->offoff || knode->fshift) {
NL_SET_ERR_MSG_MOD(extack, "variable offsetting not supported");
return false;
}
if (knode->sel->hoff || knode->sel->hmask) {
NL_SET_ERR_MSG_MOD(extack, "hashing not supported");
return false;
}
if (knode->val || knode->mask) {
NL_SET_ERR_MSG_MOD(extack, "matching on mark not supported");
return false;
}
if (knode->res && knode->res->class) {
NL_SET_ERR_MSG_MOD(extack, "setting non-0 class not supported");
return false;
}
if (knode->res && knode->res->classid >= abm->num_bands) {
NL_SET_ERR_MSG_MOD(extack,
"classid higher than number of bands");
return false;
}
if (knode->sel->nkeys != 1) {
NL_SET_ERR_MSG_MOD(extack, "exactly one key required");
return false;
}
switch (proto) {
case htons(ETH_P_IP):
tos_off = 16;
break;
case htons(ETH_P_IPV6):
tos_off = 20;
break;
default:
NL_SET_ERR_MSG_MOD(extack, "only IP and IPv6 supported as filter protocol");
return false;
}
k = &knode->sel->keys[0];
if (k->offmask) {
NL_SET_ERR_MSG_MOD(extack, "offset mask - variable offsetting not supported");
return false;
}
if (k->off) {
NL_SET_ERR_MSG_MOD(extack, "only DSCP fields can be matched");
return false;
}
if (k->val & ~k->mask) {
NL_SET_ERR_MSG_MOD(extack, "mask does not cover the key");
return false;
}
if (be32_to_cpu(k->mask) >> tos_off & ~abm->dscp_mask) {
NL_SET_ERR_MSG_MOD(extack, "only high DSCP class selector bits can be used");
nfp_err(abm->app->cpp,
"u32 offload: requested mask %x FW can support only %x\n",
be32_to_cpu(k->mask) >> tos_off, abm->dscp_mask);
return false;
}
return true;
}
/* This filter list -> map conversion is O(n * m), we expect single digit or
* low double digit number of prios and likewise for the filters. Also u32
* doesn't report stats, so it's really only setup time cost.
*/
static unsigned int
nfp_abm_find_band_for_prio(struct nfp_abm_link *alink, unsigned int prio)
{
struct nfp_abm_u32_match *iter;
list_for_each_entry(iter, &alink->dscp_map, list)
if ((prio & iter->mask) == iter->val)
return iter->band;
return alink->def_band;
}
static int nfp_abm_update_band_map(struct nfp_abm_link *alink)
{
unsigned int i, bits_per_prio, prios_per_word, base_shift;
struct nfp_abm *abm = alink->abm;
u32 field_mask;
alink->has_prio = !list_empty(&alink->dscp_map);
bits_per_prio = roundup_pow_of_two(order_base_2(abm->num_bands));
field_mask = (1 << bits_per_prio) - 1;
prios_per_word = sizeof(u32) * BITS_PER_BYTE / bits_per_prio;
/* FW mask applies from top bits */
base_shift = 8 - order_base_2(abm->num_prios);
for (i = 0; i < abm->num_prios; i++) {
unsigned int offset;
u32 *word;
u8 band;
word = &alink->prio_map[i / prios_per_word];
offset = (i % prios_per_word) * bits_per_prio;
band = nfp_abm_find_band_for_prio(alink, i << base_shift);
*word &= ~(field_mask << offset);
*word |= band << offset;
}
/* Qdisc offload status may change if has_prio changed */
nfp_abm_qdisc_offload_update(alink);
return nfp_abm_ctrl_prio_map_update(alink, alink->prio_map);
}
static void
nfp_abm_u32_knode_delete(struct nfp_abm_link *alink,
struct tc_cls_u32_knode *knode)
{
struct nfp_abm_u32_match *iter;
list_for_each_entry(iter, &alink->dscp_map, list)
if (iter->handle == knode->handle) {
list_del(&iter->list);
kfree(iter);
nfp_abm_update_band_map(alink);
return;
}
}
static int
nfp_abm_u32_knode_replace(struct nfp_abm_link *alink,
struct tc_cls_u32_knode *knode,
__be16 proto, struct netlink_ext_ack *extack)
{
struct nfp_abm_u32_match *match = NULL, *iter;
unsigned int tos_off;
u8 mask, val;
int err;
if (!nfp_abm_u32_check_knode(alink->abm, knode, proto, extack))
goto err_delete;
tos_off = proto == htons(ETH_P_IP) ? 16 : 20;
/* Extract the DSCP Class Selector bits */
val = be32_to_cpu(knode->sel->keys[0].val) >> tos_off & 0xff;
mask = be32_to_cpu(knode->sel->keys[0].mask) >> tos_off & 0xff;
/* Check if there is no conflicting mapping and find match by handle */
list_for_each_entry(iter, &alink->dscp_map, list) {
u32 cmask;
if (iter->handle == knode->handle) {
match = iter;
continue;
}
cmask = iter->mask & mask;
if ((iter->val & cmask) == (val & cmask) &&
iter->band != knode->res->classid) {
NL_SET_ERR_MSG_MOD(extack, "conflict with already offloaded filter");
goto err_delete;
}
}
if (!match) {
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
return -ENOMEM;
list_add(&match->list, &alink->dscp_map);
}
match->handle = knode->handle;
match->band = knode->res->classid;
match->mask = mask;
match->val = val;
err = nfp_abm_update_band_map(alink);
if (err)
goto err_delete;
return 0;
err_delete:
nfp_abm_u32_knode_delete(alink, knode);
return -EOPNOTSUPP;
}
static int nfp_abm_setup_tc_block_cb(enum tc_setup_type type,
void *type_data, void *cb_priv)
{
struct tc_cls_u32_offload *cls_u32 = type_data;
struct nfp_repr *repr = cb_priv;
struct nfp_abm_link *alink;
alink = repr->app_priv;
if (type != TC_SETUP_CLSU32) {
NL_SET_ERR_MSG_MOD(cls_u32->common.extack,
"only offload of u32 classifier supported");
return -EOPNOTSUPP;
}
if (!tc_cls_can_offload_and_chain0(repr->netdev, &cls_u32->common))
return -EOPNOTSUPP;
if (cls_u32->common.protocol != htons(ETH_P_IP) &&
cls_u32->common.protocol != htons(ETH_P_IPV6)) {
NL_SET_ERR_MSG_MOD(cls_u32->common.extack,
"only IP and IPv6 supported as filter protocol");
return -EOPNOTSUPP;
}
switch (cls_u32->command) {
case TC_CLSU32_NEW_KNODE:
case TC_CLSU32_REPLACE_KNODE:
return nfp_abm_u32_knode_replace(alink, &cls_u32->knode,
cls_u32->common.protocol,
cls_u32->common.extack);
case TC_CLSU32_DELETE_KNODE:
nfp_abm_u32_knode_delete(alink, &cls_u32->knode);
return 0;
default:
return -EOPNOTSUPP;
}
}
static LIST_HEAD(nfp_abm_block_cb_list);
int nfp_abm_setup_cls_block(struct net_device *netdev, struct nfp_repr *repr,
struct flow_block_offload *f)
{
return flow_block_cb_setup_simple(f, &nfp_abm_block_cb_list,
nfp_abm_setup_tc_block_cb,
repr, repr, true);
}
| ./CrossVul/dataset_final_sorted/CWE-400/c/bad_1266_0 |
crossvul-cpp_data_bad_1271_0 | // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
/* Copyright (C) 2017-2018 Netronome Systems, Inc. */
#include <linux/etherdevice.h>
#include <linux/lockdep.h>
#include <linux/pci.h>
#include <linux/skbuff.h>
#include <linux/vmalloc.h>
#include <net/devlink.h>
#include <net/dst_metadata.h>
#include "main.h"
#include "../nfpcore/nfp_cpp.h"
#include "../nfpcore/nfp_nffw.h"
#include "../nfpcore/nfp_nsp.h"
#include "../nfp_app.h"
#include "../nfp_main.h"
#include "../nfp_net.h"
#include "../nfp_net_repr.h"
#include "../nfp_port.h"
#include "./cmsg.h"
#define NFP_FLOWER_ALLOWED_VER 0x0001000000010000UL
#define NFP_MIN_INT_PORT_ID 1
#define NFP_MAX_INT_PORT_ID 256
static const char *nfp_flower_extra_cap(struct nfp_app *app, struct nfp_net *nn)
{
return "FLOWER";
}
static enum devlink_eswitch_mode eswitch_mode_get(struct nfp_app *app)
{
return DEVLINK_ESWITCH_MODE_SWITCHDEV;
}
static int
nfp_flower_lookup_internal_port_id(struct nfp_flower_priv *priv,
struct net_device *netdev)
{
struct net_device *entry;
int i, id = 0;
rcu_read_lock();
idr_for_each_entry(&priv->internal_ports.port_ids, entry, i)
if (entry == netdev) {
id = i;
break;
}
rcu_read_unlock();
return id;
}
static int
nfp_flower_get_internal_port_id(struct nfp_app *app, struct net_device *netdev)
{
struct nfp_flower_priv *priv = app->priv;
int id;
id = nfp_flower_lookup_internal_port_id(priv, netdev);
if (id > 0)
return id;
idr_preload(GFP_ATOMIC);
spin_lock_bh(&priv->internal_ports.lock);
id = idr_alloc(&priv->internal_ports.port_ids, netdev,
NFP_MIN_INT_PORT_ID, NFP_MAX_INT_PORT_ID, GFP_ATOMIC);
spin_unlock_bh(&priv->internal_ports.lock);
idr_preload_end();
return id;
}
u32 nfp_flower_get_port_id_from_netdev(struct nfp_app *app,
struct net_device *netdev)
{
int ext_port;
if (nfp_netdev_is_nfp_repr(netdev)) {
return nfp_repr_get_port_id(netdev);
} else if (nfp_flower_internal_port_can_offload(app, netdev)) {
ext_port = nfp_flower_get_internal_port_id(app, netdev);
if (ext_port < 0)
return 0;
return nfp_flower_internal_port_get_port_id(ext_port);
}
return 0;
}
static struct net_device *
nfp_flower_get_netdev_from_internal_port_id(struct nfp_app *app, int port_id)
{
struct nfp_flower_priv *priv = app->priv;
struct net_device *netdev;
rcu_read_lock();
netdev = idr_find(&priv->internal_ports.port_ids, port_id);
rcu_read_unlock();
return netdev;
}
static void
nfp_flower_free_internal_port_id(struct nfp_app *app, struct net_device *netdev)
{
struct nfp_flower_priv *priv = app->priv;
int id;
id = nfp_flower_lookup_internal_port_id(priv, netdev);
if (!id)
return;
spin_lock_bh(&priv->internal_ports.lock);
idr_remove(&priv->internal_ports.port_ids, id);
spin_unlock_bh(&priv->internal_ports.lock);
}
static int
nfp_flower_internal_port_event_handler(struct nfp_app *app,
struct net_device *netdev,
unsigned long event)
{
if (event == NETDEV_UNREGISTER &&
nfp_flower_internal_port_can_offload(app, netdev))
nfp_flower_free_internal_port_id(app, netdev);
return NOTIFY_OK;
}
static void nfp_flower_internal_port_init(struct nfp_flower_priv *priv)
{
spin_lock_init(&priv->internal_ports.lock);
idr_init(&priv->internal_ports.port_ids);
}
static void nfp_flower_internal_port_cleanup(struct nfp_flower_priv *priv)
{
idr_destroy(&priv->internal_ports.port_ids);
}
static struct nfp_flower_non_repr_priv *
nfp_flower_non_repr_priv_lookup(struct nfp_app *app, struct net_device *netdev)
{
struct nfp_flower_priv *priv = app->priv;
struct nfp_flower_non_repr_priv *entry;
ASSERT_RTNL();
list_for_each_entry(entry, &priv->non_repr_priv, list)
if (entry->netdev == netdev)
return entry;
return NULL;
}
void
__nfp_flower_non_repr_priv_get(struct nfp_flower_non_repr_priv *non_repr_priv)
{
non_repr_priv->ref_count++;
}
struct nfp_flower_non_repr_priv *
nfp_flower_non_repr_priv_get(struct nfp_app *app, struct net_device *netdev)
{
struct nfp_flower_priv *priv = app->priv;
struct nfp_flower_non_repr_priv *entry;
entry = nfp_flower_non_repr_priv_lookup(app, netdev);
if (entry)
goto inc_ref;
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return NULL;
entry->netdev = netdev;
list_add(&entry->list, &priv->non_repr_priv);
inc_ref:
__nfp_flower_non_repr_priv_get(entry);
return entry;
}
void
__nfp_flower_non_repr_priv_put(struct nfp_flower_non_repr_priv *non_repr_priv)
{
if (--non_repr_priv->ref_count)
return;
list_del(&non_repr_priv->list);
kfree(non_repr_priv);
}
void
nfp_flower_non_repr_priv_put(struct nfp_app *app, struct net_device *netdev)
{
struct nfp_flower_non_repr_priv *entry;
entry = nfp_flower_non_repr_priv_lookup(app, netdev);
if (!entry)
return;
__nfp_flower_non_repr_priv_put(entry);
}
static enum nfp_repr_type
nfp_flower_repr_get_type_and_port(struct nfp_app *app, u32 port_id, u8 *port)
{
switch (FIELD_GET(NFP_FLOWER_CMSG_PORT_TYPE, port_id)) {
case NFP_FLOWER_CMSG_PORT_TYPE_PHYS_PORT:
*port = FIELD_GET(NFP_FLOWER_CMSG_PORT_PHYS_PORT_NUM,
port_id);
return NFP_REPR_TYPE_PHYS_PORT;
case NFP_FLOWER_CMSG_PORT_TYPE_PCIE_PORT:
*port = FIELD_GET(NFP_FLOWER_CMSG_PORT_VNIC, port_id);
if (FIELD_GET(NFP_FLOWER_CMSG_PORT_VNIC_TYPE, port_id) ==
NFP_FLOWER_CMSG_PORT_VNIC_TYPE_PF)
return NFP_REPR_TYPE_PF;
else
return NFP_REPR_TYPE_VF;
}
return __NFP_REPR_TYPE_MAX;
}
static struct net_device *
nfp_flower_dev_get(struct nfp_app *app, u32 port_id, bool *redir_egress)
{
enum nfp_repr_type repr_type;
struct nfp_reprs *reprs;
u8 port = 0;
/* Check if the port is internal. */
if (FIELD_GET(NFP_FLOWER_CMSG_PORT_TYPE, port_id) ==
NFP_FLOWER_CMSG_PORT_TYPE_OTHER_PORT) {
if (redir_egress)
*redir_egress = true;
port = FIELD_GET(NFP_FLOWER_CMSG_PORT_PHYS_PORT_NUM, port_id);
return nfp_flower_get_netdev_from_internal_port_id(app, port);
}
repr_type = nfp_flower_repr_get_type_and_port(app, port_id, &port);
if (repr_type > NFP_REPR_TYPE_MAX)
return NULL;
reprs = rcu_dereference(app->reprs[repr_type]);
if (!reprs)
return NULL;
if (port >= reprs->num_reprs)
return NULL;
return rcu_dereference(reprs->reprs[port]);
}
static int
nfp_flower_reprs_reify(struct nfp_app *app, enum nfp_repr_type type,
bool exists)
{
struct nfp_reprs *reprs;
int i, err, count = 0;
reprs = rcu_dereference_protected(app->reprs[type],
lockdep_is_held(&app->pf->lock));
if (!reprs)
return 0;
for (i = 0; i < reprs->num_reprs; i++) {
struct net_device *netdev;
netdev = nfp_repr_get_locked(app, reprs, i);
if (netdev) {
struct nfp_repr *repr = netdev_priv(netdev);
err = nfp_flower_cmsg_portreify(repr, exists);
if (err)
return err;
count++;
}
}
return count;
}
static int
nfp_flower_wait_repr_reify(struct nfp_app *app, atomic_t *replies, int tot_repl)
{
struct nfp_flower_priv *priv = app->priv;
if (!tot_repl)
return 0;
lockdep_assert_held(&app->pf->lock);
if (!wait_event_timeout(priv->reify_wait_queue,
atomic_read(replies) >= tot_repl,
NFP_FL_REPLY_TIMEOUT)) {
nfp_warn(app->cpp, "Not all reprs responded to reify\n");
return -EIO;
}
return 0;
}
static int
nfp_flower_repr_netdev_open(struct nfp_app *app, struct nfp_repr *repr)
{
int err;
err = nfp_flower_cmsg_portmod(repr, true, repr->netdev->mtu, false);
if (err)
return err;
netif_tx_wake_all_queues(repr->netdev);
return 0;
}
static int
nfp_flower_repr_netdev_stop(struct nfp_app *app, struct nfp_repr *repr)
{
netif_tx_disable(repr->netdev);
return nfp_flower_cmsg_portmod(repr, false, repr->netdev->mtu, false);
}
static void
nfp_flower_repr_netdev_clean(struct nfp_app *app, struct net_device *netdev)
{
struct nfp_repr *repr = netdev_priv(netdev);
kfree(repr->app_priv);
}
static void
nfp_flower_repr_netdev_preclean(struct nfp_app *app, struct net_device *netdev)
{
struct nfp_repr *repr = netdev_priv(netdev);
struct nfp_flower_priv *priv = app->priv;
atomic_t *replies = &priv->reify_replies;
int err;
atomic_set(replies, 0);
err = nfp_flower_cmsg_portreify(repr, false);
if (err) {
nfp_warn(app->cpp, "Failed to notify firmware about repr destruction\n");
return;
}
nfp_flower_wait_repr_reify(app, replies, 1);
}
static void nfp_flower_sriov_disable(struct nfp_app *app)
{
struct nfp_flower_priv *priv = app->priv;
if (!priv->nn)
return;
nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_VF);
}
static int
nfp_flower_spawn_vnic_reprs(struct nfp_app *app,
enum nfp_flower_cmsg_port_vnic_type vnic_type,
enum nfp_repr_type repr_type, unsigned int cnt)
{
u8 nfp_pcie = nfp_cppcore_pcie_unit(app->pf->cpp);
struct nfp_flower_priv *priv = app->priv;
atomic_t *replies = &priv->reify_replies;
struct nfp_flower_repr_priv *repr_priv;
enum nfp_port_type port_type;
struct nfp_repr *nfp_repr;
struct nfp_reprs *reprs;
int i, err, reify_cnt;
const u8 queue = 0;
port_type = repr_type == NFP_REPR_TYPE_PF ? NFP_PORT_PF_PORT :
NFP_PORT_VF_PORT;
reprs = nfp_reprs_alloc(cnt);
if (!reprs)
return -ENOMEM;
for (i = 0; i < cnt; i++) {
struct net_device *repr;
struct nfp_port *port;
u32 port_id;
repr = nfp_repr_alloc(app);
if (!repr) {
err = -ENOMEM;
goto err_reprs_clean;
}
repr_priv = kzalloc(sizeof(*repr_priv), GFP_KERNEL);
if (!repr_priv) {
err = -ENOMEM;
goto err_reprs_clean;
}
nfp_repr = netdev_priv(repr);
nfp_repr->app_priv = repr_priv;
repr_priv->nfp_repr = nfp_repr;
/* For now we only support 1 PF */
WARN_ON(repr_type == NFP_REPR_TYPE_PF && i);
port = nfp_port_alloc(app, port_type, repr);
if (IS_ERR(port)) {
err = PTR_ERR(port);
nfp_repr_free(repr);
goto err_reprs_clean;
}
if (repr_type == NFP_REPR_TYPE_PF) {
port->pf_id = i;
port->vnic = priv->nn->dp.ctrl_bar;
} else {
port->pf_id = 0;
port->vf_id = i;
port->vnic =
app->pf->vf_cfg_mem + i * NFP_NET_CFG_BAR_SZ;
}
eth_hw_addr_random(repr);
port_id = nfp_flower_cmsg_pcie_port(nfp_pcie, vnic_type,
i, queue);
err = nfp_repr_init(app, repr,
port_id, port, priv->nn->dp.netdev);
if (err) {
nfp_port_free(port);
nfp_repr_free(repr);
goto err_reprs_clean;
}
RCU_INIT_POINTER(reprs->reprs[i], repr);
nfp_info(app->cpp, "%s%d Representor(%s) created\n",
repr_type == NFP_REPR_TYPE_PF ? "PF" : "VF", i,
repr->name);
}
nfp_app_reprs_set(app, repr_type, reprs);
atomic_set(replies, 0);
reify_cnt = nfp_flower_reprs_reify(app, repr_type, true);
if (reify_cnt < 0) {
err = reify_cnt;
nfp_warn(app->cpp, "Failed to notify firmware about repr creation\n");
goto err_reprs_remove;
}
err = nfp_flower_wait_repr_reify(app, replies, reify_cnt);
if (err)
goto err_reprs_remove;
return 0;
err_reprs_remove:
reprs = nfp_app_reprs_set(app, repr_type, NULL);
err_reprs_clean:
nfp_reprs_clean_and_free(app, reprs);
return err;
}
static int nfp_flower_sriov_enable(struct nfp_app *app, int num_vfs)
{
struct nfp_flower_priv *priv = app->priv;
if (!priv->nn)
return 0;
return nfp_flower_spawn_vnic_reprs(app,
NFP_FLOWER_CMSG_PORT_VNIC_TYPE_VF,
NFP_REPR_TYPE_VF, num_vfs);
}
static int
nfp_flower_spawn_phy_reprs(struct nfp_app *app, struct nfp_flower_priv *priv)
{
struct nfp_eth_table *eth_tbl = app->pf->eth_tbl;
atomic_t *replies = &priv->reify_replies;
struct nfp_flower_repr_priv *repr_priv;
struct nfp_repr *nfp_repr;
struct sk_buff *ctrl_skb;
struct nfp_reprs *reprs;
int err, reify_cnt;
unsigned int i;
ctrl_skb = nfp_flower_cmsg_mac_repr_start(app, eth_tbl->count);
if (!ctrl_skb)
return -ENOMEM;
reprs = nfp_reprs_alloc(eth_tbl->max_index + 1);
if (!reprs) {
err = -ENOMEM;
goto err_free_ctrl_skb;
}
for (i = 0; i < eth_tbl->count; i++) {
unsigned int phys_port = eth_tbl->ports[i].index;
struct net_device *repr;
struct nfp_port *port;
u32 cmsg_port_id;
repr = nfp_repr_alloc(app);
if (!repr) {
err = -ENOMEM;
goto err_reprs_clean;
}
repr_priv = kzalloc(sizeof(*repr_priv), GFP_KERNEL);
if (!repr_priv) {
err = -ENOMEM;
nfp_repr_free(repr);
goto err_reprs_clean;
}
nfp_repr = netdev_priv(repr);
nfp_repr->app_priv = repr_priv;
repr_priv->nfp_repr = nfp_repr;
port = nfp_port_alloc(app, NFP_PORT_PHYS_PORT, repr);
if (IS_ERR(port)) {
err = PTR_ERR(port);
kfree(repr_priv);
nfp_repr_free(repr);
goto err_reprs_clean;
}
err = nfp_port_init_phy_port(app->pf, app, port, i);
if (err) {
kfree(repr_priv);
nfp_port_free(port);
nfp_repr_free(repr);
goto err_reprs_clean;
}
SET_NETDEV_DEV(repr, &priv->nn->pdev->dev);
nfp_net_get_mac_addr(app->pf, repr, port);
cmsg_port_id = nfp_flower_cmsg_phys_port(phys_port);
err = nfp_repr_init(app, repr,
cmsg_port_id, port, priv->nn->dp.netdev);
if (err) {
kfree(repr_priv);
nfp_port_free(port);
nfp_repr_free(repr);
goto err_reprs_clean;
}
nfp_flower_cmsg_mac_repr_add(ctrl_skb, i,
eth_tbl->ports[i].nbi,
eth_tbl->ports[i].base,
phys_port);
RCU_INIT_POINTER(reprs->reprs[phys_port], repr);
nfp_info(app->cpp, "Phys Port %d Representor(%s) created\n",
phys_port, repr->name);
}
nfp_app_reprs_set(app, NFP_REPR_TYPE_PHYS_PORT, reprs);
/* The REIFY/MAC_REPR control messages should be sent after the MAC
* representors are registered using nfp_app_reprs_set(). This is
* because the firmware may respond with control messages for the
* MAC representors, f.e. to provide the driver with information
* about their state, and without registration the driver will drop
* any such messages.
*/
atomic_set(replies, 0);
reify_cnt = nfp_flower_reprs_reify(app, NFP_REPR_TYPE_PHYS_PORT, true);
if (reify_cnt < 0) {
err = reify_cnt;
nfp_warn(app->cpp, "Failed to notify firmware about repr creation\n");
goto err_reprs_remove;
}
err = nfp_flower_wait_repr_reify(app, replies, reify_cnt);
if (err)
goto err_reprs_remove;
nfp_ctrl_tx(app->ctrl, ctrl_skb);
return 0;
err_reprs_remove:
reprs = nfp_app_reprs_set(app, NFP_REPR_TYPE_PHYS_PORT, NULL);
err_reprs_clean:
nfp_reprs_clean_and_free(app, reprs);
err_free_ctrl_skb:
kfree_skb(ctrl_skb);
return err;
}
static int nfp_flower_vnic_alloc(struct nfp_app *app, struct nfp_net *nn,
unsigned int id)
{
if (id > 0) {
nfp_warn(app->cpp, "FlowerNIC doesn't support more than one data vNIC\n");
goto err_invalid_port;
}
eth_hw_addr_random(nn->dp.netdev);
netif_keep_dst(nn->dp.netdev);
nn->vnic_no_name = true;
return 0;
err_invalid_port:
nn->port = nfp_port_alloc(app, NFP_PORT_INVALID, nn->dp.netdev);
return PTR_ERR_OR_ZERO(nn->port);
}
static void nfp_flower_vnic_clean(struct nfp_app *app, struct nfp_net *nn)
{
struct nfp_flower_priv *priv = app->priv;
if (app->pf->num_vfs)
nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_VF);
nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PF);
nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PHYS_PORT);
priv->nn = NULL;
}
static int nfp_flower_vnic_init(struct nfp_app *app, struct nfp_net *nn)
{
struct nfp_flower_priv *priv = app->priv;
int err;
priv->nn = nn;
err = nfp_flower_spawn_phy_reprs(app, app->priv);
if (err)
goto err_clear_nn;
err = nfp_flower_spawn_vnic_reprs(app,
NFP_FLOWER_CMSG_PORT_VNIC_TYPE_PF,
NFP_REPR_TYPE_PF, 1);
if (err)
goto err_destroy_reprs_phy;
if (app->pf->num_vfs) {
err = nfp_flower_spawn_vnic_reprs(app,
NFP_FLOWER_CMSG_PORT_VNIC_TYPE_VF,
NFP_REPR_TYPE_VF,
app->pf->num_vfs);
if (err)
goto err_destroy_reprs_pf;
}
return 0;
err_destroy_reprs_pf:
nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PF);
err_destroy_reprs_phy:
nfp_reprs_clean_and_free_by_type(app, NFP_REPR_TYPE_PHYS_PORT);
err_clear_nn:
priv->nn = NULL;
return err;
}
static int nfp_flower_init(struct nfp_app *app)
{
u64 version, features, ctx_count, num_mems;
const struct nfp_pf *pf = app->pf;
struct nfp_flower_priv *app_priv;
int err;
if (!pf->eth_tbl) {
nfp_warn(app->cpp, "FlowerNIC requires eth table\n");
return -EINVAL;
}
if (!pf->mac_stats_bar) {
nfp_warn(app->cpp, "FlowerNIC requires mac_stats BAR\n");
return -EINVAL;
}
if (!pf->vf_cfg_bar) {
nfp_warn(app->cpp, "FlowerNIC requires vf_cfg BAR\n");
return -EINVAL;
}
version = nfp_rtsym_read_le(app->pf->rtbl, "hw_flower_version", &err);
if (err) {
nfp_warn(app->cpp, "FlowerNIC requires hw_flower_version memory symbol\n");
return err;
}
num_mems = nfp_rtsym_read_le(app->pf->rtbl, "CONFIG_FC_HOST_CTX_SPLIT",
&err);
if (err) {
nfp_warn(app->cpp,
"FlowerNIC: unsupported host context memory: %d\n",
err);
err = 0;
num_mems = 1;
}
if (!FIELD_FIT(NFP_FL_STAT_ID_MU_NUM, num_mems) || !num_mems) {
nfp_warn(app->cpp,
"FlowerNIC: invalid host context memory: %llu\n",
num_mems);
return -EINVAL;
}
ctx_count = nfp_rtsym_read_le(app->pf->rtbl, "CONFIG_FC_HOST_CTX_COUNT",
&err);
if (err) {
nfp_warn(app->cpp,
"FlowerNIC: unsupported host context count: %d\n",
err);
err = 0;
ctx_count = BIT(17);
}
/* We need to ensure hardware has enough flower capabilities. */
if (version != NFP_FLOWER_ALLOWED_VER) {
nfp_warn(app->cpp, "FlowerNIC: unsupported firmware version\n");
return -EINVAL;
}
app_priv = vzalloc(sizeof(struct nfp_flower_priv));
if (!app_priv)
return -ENOMEM;
app_priv->total_mem_units = num_mems;
app_priv->active_mem_unit = 0;
app_priv->stats_ring_size = roundup_pow_of_two(ctx_count);
app->priv = app_priv;
app_priv->app = app;
skb_queue_head_init(&app_priv->cmsg_skbs_high);
skb_queue_head_init(&app_priv->cmsg_skbs_low);
INIT_WORK(&app_priv->cmsg_work, nfp_flower_cmsg_process_rx);
init_waitqueue_head(&app_priv->reify_wait_queue);
init_waitqueue_head(&app_priv->mtu_conf.wait_q);
spin_lock_init(&app_priv->mtu_conf.lock);
err = nfp_flower_metadata_init(app, ctx_count, num_mems);
if (err)
goto err_free_app_priv;
/* Extract the extra features supported by the firmware. */
features = nfp_rtsym_read_le(app->pf->rtbl,
"_abi_flower_extra_features", &err);
if (err)
app_priv->flower_ext_feats = 0;
else
app_priv->flower_ext_feats = features;
/* Tell the firmware that the driver supports lag. */
err = nfp_rtsym_write_le(app->pf->rtbl,
"_abi_flower_balance_sync_enable", 1);
if (!err) {
app_priv->flower_ext_feats |= NFP_FL_FEATS_LAG;
nfp_flower_lag_init(&app_priv->nfp_lag);
} else if (err == -ENOENT) {
nfp_warn(app->cpp, "LAG not supported by FW.\n");
} else {
goto err_cleanup_metadata;
}
if (app_priv->flower_ext_feats & NFP_FL_FEATS_FLOW_MOD) {
/* Tell the firmware that the driver supports flow merging. */
err = nfp_rtsym_write_le(app->pf->rtbl,
"_abi_flower_merge_hint_enable", 1);
if (!err) {
app_priv->flower_ext_feats |= NFP_FL_FEATS_FLOW_MERGE;
nfp_flower_internal_port_init(app_priv);
} else if (err == -ENOENT) {
nfp_warn(app->cpp, "Flow merge not supported by FW.\n");
} else {
goto err_lag_clean;
}
} else {
nfp_warn(app->cpp, "Flow mod/merge not supported by FW.\n");
}
if (app_priv->flower_ext_feats & NFP_FL_FEATS_VF_RLIM)
nfp_flower_qos_init(app);
INIT_LIST_HEAD(&app_priv->indr_block_cb_priv);
INIT_LIST_HEAD(&app_priv->non_repr_priv);
app_priv->pre_tun_rule_cnt = 0;
return 0;
err_lag_clean:
if (app_priv->flower_ext_feats & NFP_FL_FEATS_LAG)
nfp_flower_lag_cleanup(&app_priv->nfp_lag);
err_cleanup_metadata:
nfp_flower_metadata_cleanup(app);
err_free_app_priv:
vfree(app->priv);
return err;
}
static void nfp_flower_clean(struct nfp_app *app)
{
struct nfp_flower_priv *app_priv = app->priv;
skb_queue_purge(&app_priv->cmsg_skbs_high);
skb_queue_purge(&app_priv->cmsg_skbs_low);
flush_work(&app_priv->cmsg_work);
if (app_priv->flower_ext_feats & NFP_FL_FEATS_VF_RLIM)
nfp_flower_qos_cleanup(app);
if (app_priv->flower_ext_feats & NFP_FL_FEATS_LAG)
nfp_flower_lag_cleanup(&app_priv->nfp_lag);
if (app_priv->flower_ext_feats & NFP_FL_FEATS_FLOW_MERGE)
nfp_flower_internal_port_cleanup(app_priv);
nfp_flower_metadata_cleanup(app);
vfree(app->priv);
app->priv = NULL;
}
static bool nfp_flower_check_ack(struct nfp_flower_priv *app_priv)
{
bool ret;
spin_lock_bh(&app_priv->mtu_conf.lock);
ret = app_priv->mtu_conf.ack;
spin_unlock_bh(&app_priv->mtu_conf.lock);
return ret;
}
static int
nfp_flower_repr_change_mtu(struct nfp_app *app, struct net_device *netdev,
int new_mtu)
{
struct nfp_flower_priv *app_priv = app->priv;
struct nfp_repr *repr = netdev_priv(netdev);
int err;
/* Only need to config FW for physical port MTU change. */
if (repr->port->type != NFP_PORT_PHYS_PORT)
return 0;
if (!(app_priv->flower_ext_feats & NFP_FL_NBI_MTU_SETTING)) {
nfp_err(app->cpp, "Physical port MTU setting not supported\n");
return -EINVAL;
}
spin_lock_bh(&app_priv->mtu_conf.lock);
app_priv->mtu_conf.ack = false;
app_priv->mtu_conf.requested_val = new_mtu;
app_priv->mtu_conf.portnum = repr->dst->u.port_info.port_id;
spin_unlock_bh(&app_priv->mtu_conf.lock);
err = nfp_flower_cmsg_portmod(repr, netif_carrier_ok(netdev), new_mtu,
true);
if (err) {
spin_lock_bh(&app_priv->mtu_conf.lock);
app_priv->mtu_conf.requested_val = 0;
spin_unlock_bh(&app_priv->mtu_conf.lock);
return err;
}
/* Wait for fw to ack the change. */
if (!wait_event_timeout(app_priv->mtu_conf.wait_q,
nfp_flower_check_ack(app_priv),
NFP_FL_REPLY_TIMEOUT)) {
spin_lock_bh(&app_priv->mtu_conf.lock);
app_priv->mtu_conf.requested_val = 0;
spin_unlock_bh(&app_priv->mtu_conf.lock);
nfp_warn(app->cpp, "MTU change not verified with fw\n");
return -EIO;
}
return 0;
}
static int nfp_flower_start(struct nfp_app *app)
{
struct nfp_flower_priv *app_priv = app->priv;
int err;
if (app_priv->flower_ext_feats & NFP_FL_FEATS_LAG) {
err = nfp_flower_lag_reset(&app_priv->nfp_lag);
if (err)
return err;
}
return nfp_tunnel_config_start(app);
}
static void nfp_flower_stop(struct nfp_app *app)
{
nfp_tunnel_config_stop(app);
}
static int
nfp_flower_netdev_event(struct nfp_app *app, struct net_device *netdev,
unsigned long event, void *ptr)
{
struct nfp_flower_priv *app_priv = app->priv;
int ret;
if (app_priv->flower_ext_feats & NFP_FL_FEATS_LAG) {
ret = nfp_flower_lag_netdev_event(app_priv, netdev, event, ptr);
if (ret & NOTIFY_STOP_MASK)
return ret;
}
ret = nfp_flower_reg_indir_block_handler(app, netdev, event);
if (ret & NOTIFY_STOP_MASK)
return ret;
ret = nfp_flower_internal_port_event_handler(app, netdev, event);
if (ret & NOTIFY_STOP_MASK)
return ret;
return nfp_tunnel_mac_event_handler(app, netdev, event, ptr);
}
const struct nfp_app_type app_flower = {
.id = NFP_APP_FLOWER_NIC,
.name = "flower",
.ctrl_cap_mask = ~0U,
.ctrl_has_meta = true,
.extra_cap = nfp_flower_extra_cap,
.init = nfp_flower_init,
.clean = nfp_flower_clean,
.repr_change_mtu = nfp_flower_repr_change_mtu,
.vnic_alloc = nfp_flower_vnic_alloc,
.vnic_init = nfp_flower_vnic_init,
.vnic_clean = nfp_flower_vnic_clean,
.repr_preclean = nfp_flower_repr_netdev_preclean,
.repr_clean = nfp_flower_repr_netdev_clean,
.repr_open = nfp_flower_repr_netdev_open,
.repr_stop = nfp_flower_repr_netdev_stop,
.start = nfp_flower_start,
.stop = nfp_flower_stop,
.netdev_event = nfp_flower_netdev_event,
.ctrl_msg_rx = nfp_flower_cmsg_rx,
.sriov_enable = nfp_flower_sriov_enable,
.sriov_disable = nfp_flower_sriov_disable,
.eswitch_mode_get = eswitch_mode_get,
.dev_get = nfp_flower_dev_get,
.setup_tc = nfp_flower_setup_tc,
};
| ./CrossVul/dataset_final_sorted/CWE-400/c/bad_1271_0 |
crossvul-cpp_data_good_1246_0 | /*
* Marvell Wireless LAN device driver: PCIE specific handling
*
* Copyright (C) 2011-2014, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include <linux/firmware.h>
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
#include "pcie.h"
#define PCIE_VERSION "1.0"
#define DRV_NAME "Marvell mwifiex PCIe"
static struct mwifiex_if_ops pcie_ops;
static const struct of_device_id mwifiex_pcie_of_match_table[] = {
{ .compatible = "pci11ab,2b42" },
{ .compatible = "pci1b4b,2b42" },
{ }
};
static int mwifiex_pcie_probe_of(struct device *dev)
{
if (!of_match_node(mwifiex_pcie_of_match_table, dev->of_node)) {
dev_err(dev, "required compatible string missing\n");
return -EINVAL;
}
return 0;
}
static void mwifiex_pcie_work(struct work_struct *work);
static int
mwifiex_map_pci_memory(struct mwifiex_adapter *adapter, struct sk_buff *skb,
size_t size, int flags)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_dma_mapping mapping;
mapping.addr = pci_map_single(card->dev, skb->data, size, flags);
if (pci_dma_mapping_error(card->dev, mapping.addr)) {
mwifiex_dbg(adapter, ERROR, "failed to map pci memory!\n");
return -1;
}
mapping.len = size;
mwifiex_store_mapping(skb, &mapping);
return 0;
}
static void mwifiex_unmap_pci_memory(struct mwifiex_adapter *adapter,
struct sk_buff *skb, int flags)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_dma_mapping mapping;
mwifiex_get_mapping(skb, &mapping);
pci_unmap_single(card->dev, mapping.addr, mapping.len, flags);
}
/*
* This function writes data into PCIE card register.
*/
static int mwifiex_write_reg(struct mwifiex_adapter *adapter, int reg, u32 data)
{
struct pcie_service_card *card = adapter->card;
iowrite32(data, card->pci_mmap1 + reg);
return 0;
}
/* This function reads data from PCIE card register.
*/
static int mwifiex_read_reg(struct mwifiex_adapter *adapter, int reg, u32 *data)
{
struct pcie_service_card *card = adapter->card;
*data = ioread32(card->pci_mmap1 + reg);
if (*data == 0xffffffff)
return 0xffffffff;
return 0;
}
/* This function reads u8 data from PCIE card register. */
static int mwifiex_read_reg_byte(struct mwifiex_adapter *adapter,
int reg, u8 *data)
{
struct pcie_service_card *card = adapter->card;
*data = ioread8(card->pci_mmap1 + reg);
return 0;
}
/*
* This function reads sleep cookie and checks if FW is ready
*/
static bool mwifiex_pcie_ok_to_access_hw(struct mwifiex_adapter *adapter)
{
u32 cookie_value;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!reg->sleep_cookie)
return true;
if (card->sleep_cookie_vbase) {
cookie_value = get_unaligned_le32(card->sleep_cookie_vbase);
mwifiex_dbg(adapter, INFO,
"info: ACCESS_HW: sleep cookie=0x%x\n",
cookie_value);
if (cookie_value == FW_AWAKE_COOKIE)
return true;
}
return false;
}
#ifdef CONFIG_PM_SLEEP
/*
* Kernel needs to suspend all functions separately. Therefore all
* registered functions must have drivers with suspend and resume
* methods. Failing that the kernel simply removes the whole card.
*
* If already not suspended, this function allocates and sends a host
* sleep activate request to the firmware and turns off the traffic.
*/
static int mwifiex_pcie_suspend(struct device *dev)
{
struct mwifiex_adapter *adapter;
struct pcie_service_card *card = dev_get_drvdata(dev);
/* Might still be loading firmware */
wait_for_completion(&card->fw_done);
adapter = card->adapter;
if (!adapter) {
dev_err(dev, "adapter is not valid\n");
return 0;
}
mwifiex_enable_wake(adapter);
/* Enable the Host Sleep */
if (!mwifiex_enable_hs(adapter)) {
mwifiex_dbg(adapter, ERROR,
"cmd: failed to suspend\n");
clear_bit(MWIFIEX_IS_HS_ENABLING, &adapter->work_flags);
mwifiex_disable_wake(adapter);
return -EFAULT;
}
flush_workqueue(adapter->workqueue);
/* Indicate device suspended */
set_bit(MWIFIEX_IS_SUSPENDED, &adapter->work_flags);
clear_bit(MWIFIEX_IS_HS_ENABLING, &adapter->work_flags);
return 0;
}
/*
* Kernel needs to suspend all functions separately. Therefore all
* registered functions must have drivers with suspend and resume
* methods. Failing that the kernel simply removes the whole card.
*
* If already not resumed, this function turns on the traffic and
* sends a host sleep cancel request to the firmware.
*/
static int mwifiex_pcie_resume(struct device *dev)
{
struct mwifiex_adapter *adapter;
struct pcie_service_card *card = dev_get_drvdata(dev);
if (!card->adapter) {
dev_err(dev, "adapter structure is not valid\n");
return 0;
}
adapter = card->adapter;
if (!test_bit(MWIFIEX_IS_SUSPENDED, &adapter->work_flags)) {
mwifiex_dbg(adapter, WARN,
"Device already resumed\n");
return 0;
}
clear_bit(MWIFIEX_IS_SUSPENDED, &adapter->work_flags);
mwifiex_cancel_hs(mwifiex_get_priv(adapter, MWIFIEX_BSS_ROLE_STA),
MWIFIEX_ASYNC_CMD);
mwifiex_disable_wake(adapter);
return 0;
}
#endif
/*
* This function probes an mwifiex device and registers it. It allocates
* the card structure, enables PCIE function number and initiates the
* device registration and initialization procedure by adding a logical
* interface.
*/
static int mwifiex_pcie_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct pcie_service_card *card;
int ret;
pr_debug("info: vendor=0x%4.04X device=0x%4.04X rev=%d\n",
pdev->vendor, pdev->device, pdev->revision);
card = devm_kzalloc(&pdev->dev, sizeof(*card), GFP_KERNEL);
if (!card)
return -ENOMEM;
init_completion(&card->fw_done);
card->dev = pdev;
if (ent->driver_data) {
struct mwifiex_pcie_device *data = (void *)ent->driver_data;
card->pcie.reg = data->reg;
card->pcie.blksz_fw_dl = data->blksz_fw_dl;
card->pcie.tx_buf_size = data->tx_buf_size;
card->pcie.can_dump_fw = data->can_dump_fw;
card->pcie.mem_type_mapping_tbl = data->mem_type_mapping_tbl;
card->pcie.num_mem_types = data->num_mem_types;
card->pcie.can_ext_scan = data->can_ext_scan;
INIT_WORK(&card->work, mwifiex_pcie_work);
}
/* device tree node parsing and platform specific configuration*/
if (pdev->dev.of_node) {
ret = mwifiex_pcie_probe_of(&pdev->dev);
if (ret)
return ret;
}
if (mwifiex_add_card(card, &card->fw_done, &pcie_ops,
MWIFIEX_PCIE, &pdev->dev)) {
pr_err("%s failed\n", __func__);
return -1;
}
return 0;
}
/*
* This function removes the interface and frees up the card structure.
*/
static void mwifiex_pcie_remove(struct pci_dev *pdev)
{
struct pcie_service_card *card;
struct mwifiex_adapter *adapter;
struct mwifiex_private *priv;
const struct mwifiex_pcie_card_reg *reg;
u32 fw_status;
int ret;
card = pci_get_drvdata(pdev);
wait_for_completion(&card->fw_done);
adapter = card->adapter;
if (!adapter || !adapter->priv_num)
return;
reg = card->pcie.reg;
if (reg)
ret = mwifiex_read_reg(adapter, reg->fw_status, &fw_status);
else
fw_status = -1;
if (fw_status == FIRMWARE_READY_PCIE && !adapter->mfg_mode) {
mwifiex_deauthenticate_all(adapter);
priv = mwifiex_get_priv(adapter, MWIFIEX_BSS_ROLE_ANY);
mwifiex_disable_auto_ds(priv);
mwifiex_init_shutdown_fw(priv, MWIFIEX_FUNC_SHUTDOWN);
}
mwifiex_remove_card(adapter);
}
static void mwifiex_pcie_shutdown(struct pci_dev *pdev)
{
mwifiex_pcie_remove(pdev);
return;
}
static void mwifiex_pcie_coredump(struct device *dev)
{
struct pci_dev *pdev;
struct pcie_service_card *card;
pdev = container_of(dev, struct pci_dev, dev);
card = pci_get_drvdata(pdev);
if (!test_and_set_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP,
&card->work_flags))
schedule_work(&card->work);
}
static const struct pci_device_id mwifiex_ids[] = {
{
PCIE_VENDOR_ID_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8766P,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8766,
},
{
PCIE_VENDOR_ID_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8897,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8897,
},
{
PCIE_VENDOR_ID_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8997,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8997,
},
{
PCIE_VENDOR_ID_V2_MARVELL, PCIE_DEVICE_ID_MARVELL_88W8997,
PCI_ANY_ID, PCI_ANY_ID, 0, 0,
.driver_data = (unsigned long)&mwifiex_pcie8997,
},
{},
};
MODULE_DEVICE_TABLE(pci, mwifiex_ids);
/*
* Cleanup all software without cleaning anything related to PCIe and HW.
*/
static void mwifiex_pcie_reset_prepare(struct pci_dev *pdev)
{
struct pcie_service_card *card = pci_get_drvdata(pdev);
struct mwifiex_adapter *adapter = card->adapter;
if (!adapter) {
dev_err(&pdev->dev, "%s: adapter structure is not valid\n",
__func__);
return;
}
mwifiex_dbg(adapter, INFO,
"%s: vendor=0x%4.04x device=0x%4.04x rev=%d Pre-FLR\n",
__func__, pdev->vendor, pdev->device, pdev->revision);
mwifiex_shutdown_sw(adapter);
clear_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP, &card->work_flags);
clear_bit(MWIFIEX_IFACE_WORK_CARD_RESET, &card->work_flags);
mwifiex_dbg(adapter, INFO, "%s, successful\n", __func__);
}
/*
* Kernel stores and restores PCIe function context before and after performing
* FLR respectively. Reconfigure the software and firmware including firmware
* redownload.
*/
static void mwifiex_pcie_reset_done(struct pci_dev *pdev)
{
struct pcie_service_card *card = pci_get_drvdata(pdev);
struct mwifiex_adapter *adapter = card->adapter;
int ret;
if (!adapter) {
dev_err(&pdev->dev, "%s: adapter structure is not valid\n",
__func__);
return;
}
mwifiex_dbg(adapter, INFO,
"%s: vendor=0x%4.04x device=0x%4.04x rev=%d Post-FLR\n",
__func__, pdev->vendor, pdev->device, pdev->revision);
ret = mwifiex_reinit_sw(adapter);
if (ret)
dev_err(&pdev->dev, "reinit failed: %d\n", ret);
else
mwifiex_dbg(adapter, INFO, "%s, successful\n", __func__);
}
static const struct pci_error_handlers mwifiex_pcie_err_handler = {
.reset_prepare = mwifiex_pcie_reset_prepare,
.reset_done = mwifiex_pcie_reset_done,
};
#ifdef CONFIG_PM_SLEEP
/* Power Management Hooks */
static SIMPLE_DEV_PM_OPS(mwifiex_pcie_pm_ops, mwifiex_pcie_suspend,
mwifiex_pcie_resume);
#endif
/* PCI Device Driver */
static struct pci_driver __refdata mwifiex_pcie = {
.name = "mwifiex_pcie",
.id_table = mwifiex_ids,
.probe = mwifiex_pcie_probe,
.remove = mwifiex_pcie_remove,
.driver = {
.coredump = mwifiex_pcie_coredump,
#ifdef CONFIG_PM_SLEEP
.pm = &mwifiex_pcie_pm_ops,
#endif
},
.shutdown = mwifiex_pcie_shutdown,
.err_handler = &mwifiex_pcie_err_handler,
};
/*
* This function adds delay loop to ensure FW is awake before proceeding.
*/
static void mwifiex_pcie_dev_wakeup_delay(struct mwifiex_adapter *adapter)
{
int i = 0;
while (mwifiex_pcie_ok_to_access_hw(adapter)) {
i++;
usleep_range(10, 20);
/* 50ms max wait */
if (i == 5000)
break;
}
return;
}
static void mwifiex_delay_for_sleep_cookie(struct mwifiex_adapter *adapter,
u32 max_delay_loop_cnt)
{
struct pcie_service_card *card = adapter->card;
u8 *buffer;
u32 sleep_cookie, count;
struct sk_buff *cmdrsp = card->cmdrsp_buf;
for (count = 0; count < max_delay_loop_cnt; count++) {
pci_dma_sync_single_for_cpu(card->dev,
MWIFIEX_SKB_DMA_ADDR(cmdrsp),
sizeof(sleep_cookie),
PCI_DMA_FROMDEVICE);
buffer = cmdrsp->data;
sleep_cookie = get_unaligned_le32(buffer);
if (sleep_cookie == MWIFIEX_DEF_SLEEP_COOKIE) {
mwifiex_dbg(adapter, INFO,
"sleep cookie found at count %d\n", count);
break;
}
pci_dma_sync_single_for_device(card->dev,
MWIFIEX_SKB_DMA_ADDR(cmdrsp),
sizeof(sleep_cookie),
PCI_DMA_FROMDEVICE);
usleep_range(20, 30);
}
if (count >= max_delay_loop_cnt)
mwifiex_dbg(adapter, INFO,
"max count reached while accessing sleep cookie\n");
}
/* This function wakes up the card by reading fw_status register. */
static int mwifiex_pm_wakeup_card(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_dbg(adapter, EVENT,
"event: Wakeup device...\n");
if (reg->sleep_cookie)
mwifiex_pcie_dev_wakeup_delay(adapter);
/* Accessing fw_status register will wakeup device */
if (mwifiex_write_reg(adapter, reg->fw_status, FIRMWARE_READY_PCIE)) {
mwifiex_dbg(adapter, ERROR,
"Writing fw_status register failed\n");
return -1;
}
if (reg->sleep_cookie) {
mwifiex_pcie_dev_wakeup_delay(adapter);
mwifiex_dbg(adapter, INFO,
"PCIE wakeup: Setting PS_STATE_AWAKE\n");
adapter->ps_state = PS_STATE_AWAKE;
}
return 0;
}
/*
* This function is called after the card has woken up.
*
* The card configuration register is reset.
*/
static int mwifiex_pm_wakeup_card_complete(struct mwifiex_adapter *adapter)
{
mwifiex_dbg(adapter, CMD,
"cmd: Wakeup device completed\n");
return 0;
}
/*
* This function disables the host interrupt.
*
* The host interrupt mask is read, the disable bit is reset and
* written back to the card host interrupt mask register.
*/
static int mwifiex_pcie_disable_host_int(struct mwifiex_adapter *adapter)
{
if (mwifiex_pcie_ok_to_access_hw(adapter)) {
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_MASK,
0x00000000)) {
mwifiex_dbg(adapter, ERROR,
"Disable host interrupt failed\n");
return -1;
}
}
atomic_set(&adapter->tx_hw_pending, 0);
return 0;
}
static void mwifiex_pcie_disable_host_int_noerr(struct mwifiex_adapter *adapter)
{
WARN_ON(mwifiex_pcie_disable_host_int(adapter));
}
/*
* This function enables the host interrupt.
*
* The host interrupt enable mask is written to the card
* host interrupt mask register.
*/
static int mwifiex_pcie_enable_host_int(struct mwifiex_adapter *adapter)
{
if (mwifiex_pcie_ok_to_access_hw(adapter)) {
/* Simply write the mask to the register */
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_MASK,
HOST_INTR_MASK)) {
mwifiex_dbg(adapter, ERROR,
"Enable host interrupt failed\n");
return -1;
}
}
return 0;
}
/*
* This function initializes TX buffer ring descriptors
*/
static int mwifiex_init_txq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
card->tx_buf_list[i] = NULL;
if (reg->pfu_enabled) {
card->txbd_ring[i] = (void *)card->txbd_ring_vbase +
(sizeof(*desc2) * i);
desc2 = card->txbd_ring[i];
memset(desc2, 0, sizeof(*desc2));
} else {
card->txbd_ring[i] = (void *)card->txbd_ring_vbase +
(sizeof(*desc) * i);
desc = card->txbd_ring[i];
memset(desc, 0, sizeof(*desc));
}
}
return 0;
}
/* This function initializes RX buffer ring descriptors. Each SKB is allocated
* here and after mapping PCI memory, its physical address is assigned to
* PCIE Rx buffer descriptor's physical address.
*/
static int mwifiex_init_rxq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct sk_buff *skb;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
dma_addr_t buf_pa;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
/* Allocate skb here so that firmware can DMA data from it */
skb = mwifiex_alloc_dma_align_buf(MWIFIEX_RX_DATA_BUF_SIZE,
GFP_KERNEL);
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb for RX ring.\n");
kfree(card->rxbd_ring_vbase);
return -ENOMEM;
}
if (mwifiex_map_pci_memory(adapter, skb,
MWIFIEX_RX_DATA_BUF_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
mwifiex_dbg(adapter, INFO,
"info: RX ring: skb=%p len=%d data=%p buf_pa=%#x:%x\n",
skb, skb->len, skb->data, (u32)buf_pa,
(u32)((u64)buf_pa >> 32));
card->rx_buf_list[i] = skb;
if (reg->pfu_enabled) {
card->rxbd_ring[i] = (void *)card->rxbd_ring_vbase +
(sizeof(*desc2) * i);
desc2 = card->rxbd_ring[i];
desc2->paddr = buf_pa;
desc2->len = (u16)skb->len;
desc2->frag_len = (u16)skb->len;
desc2->flags = reg->ring_flag_eop | reg->ring_flag_sop;
desc2->offset = 0;
} else {
card->rxbd_ring[i] = (void *)(card->rxbd_ring_vbase +
(sizeof(*desc) * i));
desc = card->rxbd_ring[i];
desc->paddr = buf_pa;
desc->len = (u16)skb->len;
desc->flags = 0;
}
}
return 0;
}
/* This function initializes event buffer ring descriptors. Each SKB is
* allocated here and after mapping PCI memory, its physical address is assigned
* to PCIE Rx buffer descriptor's physical address
*/
static int mwifiex_pcie_init_evt_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_evt_buf_desc *desc;
struct sk_buff *skb;
dma_addr_t buf_pa;
int i;
for (i = 0; i < MWIFIEX_MAX_EVT_BD; i++) {
/* Allocate skb here so that firmware can DMA data from it */
skb = dev_alloc_skb(MAX_EVENT_SIZE);
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb for EVENT buf.\n");
kfree(card->evtbd_ring_vbase);
return -ENOMEM;
}
skb_put(skb, MAX_EVENT_SIZE);
if (mwifiex_map_pci_memory(adapter, skb, MAX_EVENT_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
mwifiex_dbg(adapter, EVENT,
"info: EVT ring: skb=%p len=%d data=%p buf_pa=%#x:%x\n",
skb, skb->len, skb->data, (u32)buf_pa,
(u32)((u64)buf_pa >> 32));
card->evt_buf_list[i] = skb;
card->evtbd_ring[i] = (void *)(card->evtbd_ring_vbase +
(sizeof(*desc) * i));
desc = card->evtbd_ring[i];
desc->paddr = buf_pa;
desc->len = (u16)skb->len;
desc->flags = 0;
}
return 0;
}
/* This function cleans up TX buffer rings. If any of the buffer list has valid
* SKB address, associated SKB is freed.
*/
static void mwifiex_cleanup_txq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct sk_buff *skb;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
if (reg->pfu_enabled) {
desc2 = card->txbd_ring[i];
if (card->tx_buf_list[i]) {
skb = card->tx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(skb);
}
memset(desc2, 0, sizeof(*desc2));
} else {
desc = card->txbd_ring[i];
if (card->tx_buf_list[i]) {
skb = card->tx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(skb);
}
memset(desc, 0, sizeof(*desc));
}
card->tx_buf_list[i] = NULL;
}
atomic_set(&adapter->tx_hw_pending, 0);
return;
}
/* This function cleans up RX buffer rings. If any of the buffer list has valid
* SKB address, associated SKB is freed.
*/
static void mwifiex_cleanup_rxq_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
struct sk_buff *skb;
int i;
for (i = 0; i < MWIFIEX_MAX_TXRX_BD; i++) {
if (reg->pfu_enabled) {
desc2 = card->rxbd_ring[i];
if (card->rx_buf_list[i]) {
skb = card->rx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(skb);
}
memset(desc2, 0, sizeof(*desc2));
} else {
desc = card->rxbd_ring[i];
if (card->rx_buf_list[i]) {
skb = card->rx_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(skb);
}
memset(desc, 0, sizeof(*desc));
}
card->rx_buf_list[i] = NULL;
}
return;
}
/* This function cleans up event buffer rings. If any of the buffer list has
* valid SKB address, associated SKB is freed.
*/
static void mwifiex_cleanup_evt_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct mwifiex_evt_buf_desc *desc;
struct sk_buff *skb;
int i;
for (i = 0; i < MWIFIEX_MAX_EVT_BD; i++) {
desc = card->evtbd_ring[i];
if (card->evt_buf_list[i]) {
skb = card->evt_buf_list[i];
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(skb);
}
card->evt_buf_list[i] = NULL;
memset(desc, 0, sizeof(*desc));
}
return;
}
/* This function creates buffer descriptor ring for TX
*/
static int mwifiex_pcie_create_txbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
/*
* driver maintaines the write pointer and firmware maintaines the read
* pointer. The write pointer starts at 0 (zero) while the read pointer
* starts at zero with rollover bit set
*/
card->txbd_wrptr = 0;
if (reg->pfu_enabled)
card->txbd_rdptr = 0;
else
card->txbd_rdptr |= reg->tx_rollover_ind;
/* allocate shared memory for the BD ring and divide the same in to
several descriptors */
if (reg->pfu_enabled)
card->txbd_ring_size = sizeof(struct mwifiex_pfu_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
else
card->txbd_ring_size = sizeof(struct mwifiex_pcie_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
mwifiex_dbg(adapter, INFO,
"info: txbd_ring: Allocating %d bytes\n",
card->txbd_ring_size);
card->txbd_ring_vbase = pci_alloc_consistent(card->dev,
card->txbd_ring_size,
&card->txbd_ring_pbase);
if (!card->txbd_ring_vbase) {
mwifiex_dbg(adapter, ERROR,
"allocate consistent memory (%d bytes) failed!\n",
card->txbd_ring_size);
return -ENOMEM;
}
mwifiex_dbg(adapter, DATA,
"info: txbd_ring - base: %p, pbase: %#x:%x, len: %x\n",
card->txbd_ring_vbase, (unsigned int)card->txbd_ring_pbase,
(u32)((u64)card->txbd_ring_pbase >> 32),
card->txbd_ring_size);
return mwifiex_init_txq_ring(adapter);
}
static int mwifiex_pcie_delete_txbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_cleanup_txq_ring(adapter);
if (card->txbd_ring_vbase)
pci_free_consistent(card->dev, card->txbd_ring_size,
card->txbd_ring_vbase,
card->txbd_ring_pbase);
card->txbd_ring_size = 0;
card->txbd_wrptr = 0;
card->txbd_rdptr = 0 | reg->tx_rollover_ind;
card->txbd_ring_vbase = NULL;
card->txbd_ring_pbase = 0;
return 0;
}
/*
* This function creates buffer descriptor ring for RX
*/
static int mwifiex_pcie_create_rxbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
/*
* driver maintaines the read pointer and firmware maintaines the write
* pointer. The write pointer starts at 0 (zero) while the read pointer
* starts at zero with rollover bit set
*/
card->rxbd_wrptr = 0;
card->rxbd_rdptr = reg->rx_rollover_ind;
if (reg->pfu_enabled)
card->rxbd_ring_size = sizeof(struct mwifiex_pfu_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
else
card->rxbd_ring_size = sizeof(struct mwifiex_pcie_buf_desc) *
MWIFIEX_MAX_TXRX_BD;
mwifiex_dbg(adapter, INFO,
"info: rxbd_ring: Allocating %d bytes\n",
card->rxbd_ring_size);
card->rxbd_ring_vbase = pci_alloc_consistent(card->dev,
card->rxbd_ring_size,
&card->rxbd_ring_pbase);
if (!card->rxbd_ring_vbase) {
mwifiex_dbg(adapter, ERROR,
"allocate consistent memory (%d bytes) failed!\n",
card->rxbd_ring_size);
return -ENOMEM;
}
mwifiex_dbg(adapter, DATA,
"info: rxbd_ring - base: %p, pbase: %#x:%x, len: %#x\n",
card->rxbd_ring_vbase, (u32)card->rxbd_ring_pbase,
(u32)((u64)card->rxbd_ring_pbase >> 32),
card->rxbd_ring_size);
return mwifiex_init_rxq_ring(adapter);
}
/*
* This function deletes Buffer descriptor ring for RX
*/
static int mwifiex_pcie_delete_rxbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_cleanup_rxq_ring(adapter);
if (card->rxbd_ring_vbase)
pci_free_consistent(card->dev, card->rxbd_ring_size,
card->rxbd_ring_vbase,
card->rxbd_ring_pbase);
card->rxbd_ring_size = 0;
card->rxbd_wrptr = 0;
card->rxbd_rdptr = 0 | reg->rx_rollover_ind;
card->rxbd_ring_vbase = NULL;
card->rxbd_ring_pbase = 0;
return 0;
}
/*
* This function creates buffer descriptor ring for Events
*/
static int mwifiex_pcie_create_evtbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
/*
* driver maintaines the read pointer and firmware maintaines the write
* pointer. The write pointer starts at 0 (zero) while the read pointer
* starts at zero with rollover bit set
*/
card->evtbd_wrptr = 0;
card->evtbd_rdptr = reg->evt_rollover_ind;
card->evtbd_ring_size = sizeof(struct mwifiex_evt_buf_desc) *
MWIFIEX_MAX_EVT_BD;
mwifiex_dbg(adapter, INFO,
"info: evtbd_ring: Allocating %d bytes\n",
card->evtbd_ring_size);
card->evtbd_ring_vbase = pci_alloc_consistent(card->dev,
card->evtbd_ring_size,
&card->evtbd_ring_pbase);
if (!card->evtbd_ring_vbase) {
mwifiex_dbg(adapter, ERROR,
"allocate consistent memory (%d bytes) failed!\n",
card->evtbd_ring_size);
return -ENOMEM;
}
mwifiex_dbg(adapter, EVENT,
"info: CMDRSP/EVT bd_ring - base: %p pbase: %#x:%x len: %#x\n",
card->evtbd_ring_vbase, (u32)card->evtbd_ring_pbase,
(u32)((u64)card->evtbd_ring_pbase >> 32),
card->evtbd_ring_size);
return mwifiex_pcie_init_evt_ring(adapter);
}
/*
* This function deletes Buffer descriptor ring for Events
*/
static int mwifiex_pcie_delete_evtbd_ring(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
mwifiex_cleanup_evt_ring(adapter);
if (card->evtbd_ring_vbase)
pci_free_consistent(card->dev, card->evtbd_ring_size,
card->evtbd_ring_vbase,
card->evtbd_ring_pbase);
card->evtbd_wrptr = 0;
card->evtbd_rdptr = 0 | reg->evt_rollover_ind;
card->evtbd_ring_size = 0;
card->evtbd_ring_vbase = NULL;
card->evtbd_ring_pbase = 0;
return 0;
}
/*
* This function allocates a buffer for CMDRSP
*/
static int mwifiex_pcie_alloc_cmdrsp_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct sk_buff *skb;
/* Allocate memory for receiving command response data */
skb = dev_alloc_skb(MWIFIEX_UPLD_SIZE);
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb for command response data.\n");
return -ENOMEM;
}
skb_put(skb, MWIFIEX_UPLD_SIZE);
if (mwifiex_map_pci_memory(adapter, skb, MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE)) {
kfree_skb(skb);
return -1;
}
card->cmdrsp_buf = skb;
return 0;
}
/*
* This function deletes a buffer for CMDRSP
*/
static int mwifiex_pcie_delete_cmdrsp_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card;
if (!adapter)
return 0;
card = adapter->card;
if (card && card->cmdrsp_buf) {
mwifiex_unmap_pci_memory(adapter, card->cmdrsp_buf,
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(card->cmdrsp_buf);
card->cmdrsp_buf = NULL;
}
if (card && card->cmd_buf) {
mwifiex_unmap_pci_memory(adapter, card->cmd_buf,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(card->cmd_buf);
card->cmd_buf = NULL;
}
return 0;
}
/*
* This function allocates a buffer for sleep cookie
*/
static int mwifiex_pcie_alloc_sleep_cookie_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
u32 tmp;
card->sleep_cookie_vbase = pci_alloc_consistent(card->dev, sizeof(u32),
&card->sleep_cookie_pbase);
if (!card->sleep_cookie_vbase) {
mwifiex_dbg(adapter, ERROR,
"pci_alloc_consistent failed!\n");
return -ENOMEM;
}
/* Init val of Sleep Cookie */
tmp = FW_AWAKE_COOKIE;
put_unaligned(tmp, card->sleep_cookie_vbase);
mwifiex_dbg(adapter, INFO,
"alloc_scook: sleep cookie=0x%x\n",
get_unaligned(card->sleep_cookie_vbase));
return 0;
}
/*
* This function deletes buffer for sleep cookie
*/
static int mwifiex_pcie_delete_sleep_cookie_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card;
if (!adapter)
return 0;
card = adapter->card;
if (card && card->sleep_cookie_vbase) {
pci_free_consistent(card->dev, sizeof(u32),
card->sleep_cookie_vbase,
card->sleep_cookie_pbase);
card->sleep_cookie_vbase = NULL;
}
return 0;
}
/* This function flushes the TX buffer descriptor ring
* This function defined as handler is also called while cleaning TXRX
* during disconnect/ bss stop.
*/
static int mwifiex_clean_pcie_ring_buf(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
if (!mwifiex_pcie_txbd_empty(card, card->txbd_rdptr)) {
card->txbd_flush = 1;
/* write pointer already set at last send
* send dnld-rdy intr again, wait for completion.
*/
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DNLD_RDY)) {
mwifiex_dbg(adapter, ERROR,
"failed to assert dnld-rdy interrupt.\n");
return -1;
}
}
return 0;
}
/*
* This function unmaps and frees downloaded data buffer
*/
static int mwifiex_pcie_send_data_complete(struct mwifiex_adapter *adapter)
{
struct sk_buff *skb;
u32 wrdoneidx, rdptr, num_tx_buffs, unmap_count = 0;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
/* Read the TX ring read pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->tx_rdptr, &rdptr)) {
mwifiex_dbg(adapter, ERROR,
"SEND COMP: failed to read reg->tx_rdptr\n");
return -1;
}
mwifiex_dbg(adapter, DATA,
"SEND COMP: rdptr_prev=0x%x, rdptr=0x%x\n",
card->txbd_rdptr, rdptr);
num_tx_buffs = MWIFIEX_MAX_TXRX_BD << reg->tx_start_ptr;
/* free from previous txbd_rdptr to current txbd_rdptr */
while (((card->txbd_rdptr & reg->tx_mask) !=
(rdptr & reg->tx_mask)) ||
((card->txbd_rdptr & reg->tx_rollover_ind) !=
(rdptr & reg->tx_rollover_ind))) {
wrdoneidx = (card->txbd_rdptr & reg->tx_mask) >>
reg->tx_start_ptr;
skb = card->tx_buf_list[wrdoneidx];
if (skb) {
mwifiex_dbg(adapter, DATA,
"SEND COMP: Detach skb %p at txbd_rdidx=%d\n",
skb, wrdoneidx);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
unmap_count++;
if (card->txbd_flush)
mwifiex_write_data_complete(adapter, skb, 0,
-1);
else
mwifiex_write_data_complete(adapter, skb, 0, 0);
atomic_dec(&adapter->tx_hw_pending);
}
card->tx_buf_list[wrdoneidx] = NULL;
if (reg->pfu_enabled) {
desc2 = card->txbd_ring[wrdoneidx];
memset(desc2, 0, sizeof(*desc2));
} else {
desc = card->txbd_ring[wrdoneidx];
memset(desc, 0, sizeof(*desc));
}
switch (card->dev->device) {
case PCIE_DEVICE_ID_MARVELL_88W8766P:
card->txbd_rdptr++;
break;
case PCIE_DEVICE_ID_MARVELL_88W8897:
case PCIE_DEVICE_ID_MARVELL_88W8997:
card->txbd_rdptr += reg->ring_tx_start_ptr;
break;
}
if ((card->txbd_rdptr & reg->tx_mask) == num_tx_buffs)
card->txbd_rdptr = ((card->txbd_rdptr &
reg->tx_rollover_ind) ^
reg->tx_rollover_ind);
}
if (unmap_count)
adapter->data_sent = false;
if (card->txbd_flush) {
if (mwifiex_pcie_txbd_empty(card, card->txbd_rdptr))
card->txbd_flush = 0;
else
mwifiex_clean_pcie_ring_buf(adapter);
}
return 0;
}
/* This function sends data buffer to device. First 4 bytes of payload
* are filled with payload length and payload type. Then this payload
* is mapped to PCI device memory. Tx ring pointers are advanced accordingly.
* Download ready interrupt to FW is deffered if Tx ring is not full and
* additional payload can be accomodated.
* Caller must ensure tx_param parameter to this function is not NULL.
*/
static int
mwifiex_pcie_send_data(struct mwifiex_adapter *adapter, struct sk_buff *skb,
struct mwifiex_tx_param *tx_param)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 wrindx, num_tx_buffs, rx_val;
int ret;
dma_addr_t buf_pa;
struct mwifiex_pcie_buf_desc *desc = NULL;
struct mwifiex_pfu_buf_desc *desc2 = NULL;
if (!(skb->data && skb->len)) {
mwifiex_dbg(adapter, ERROR,
"%s(): invalid parameter <%p, %#x>\n",
__func__, skb->data, skb->len);
return -1;
}
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
num_tx_buffs = MWIFIEX_MAX_TXRX_BD << reg->tx_start_ptr;
mwifiex_dbg(adapter, DATA,
"info: SEND DATA: <Rd: %#x, Wr: %#x>\n",
card->txbd_rdptr, card->txbd_wrptr);
if (mwifiex_pcie_txbd_not_full(card)) {
u8 *payload;
adapter->data_sent = true;
payload = skb->data;
put_unaligned_le16((u16)skb->len, payload + 0);
put_unaligned_le16(MWIFIEX_TYPE_DATA, payload + 2);
if (mwifiex_map_pci_memory(adapter, skb, skb->len,
PCI_DMA_TODEVICE))
return -1;
wrindx = (card->txbd_wrptr & reg->tx_mask) >> reg->tx_start_ptr;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
card->tx_buf_list[wrindx] = skb;
atomic_inc(&adapter->tx_hw_pending);
if (reg->pfu_enabled) {
desc2 = card->txbd_ring[wrindx];
desc2->paddr = buf_pa;
desc2->len = (u16)skb->len;
desc2->frag_len = (u16)skb->len;
desc2->offset = 0;
desc2->flags = MWIFIEX_BD_FLAG_FIRST_DESC |
MWIFIEX_BD_FLAG_LAST_DESC;
} else {
desc = card->txbd_ring[wrindx];
desc->paddr = buf_pa;
desc->len = (u16)skb->len;
desc->flags = MWIFIEX_BD_FLAG_FIRST_DESC |
MWIFIEX_BD_FLAG_LAST_DESC;
}
switch (card->dev->device) {
case PCIE_DEVICE_ID_MARVELL_88W8766P:
card->txbd_wrptr++;
break;
case PCIE_DEVICE_ID_MARVELL_88W8897:
case PCIE_DEVICE_ID_MARVELL_88W8997:
card->txbd_wrptr += reg->ring_tx_start_ptr;
break;
}
if ((card->txbd_wrptr & reg->tx_mask) == num_tx_buffs)
card->txbd_wrptr = ((card->txbd_wrptr &
reg->tx_rollover_ind) ^
reg->tx_rollover_ind);
rx_val = card->rxbd_rdptr & reg->rx_wrap_mask;
/* Write the TX ring write pointer in to reg->tx_wrptr */
if (mwifiex_write_reg(adapter, reg->tx_wrptr,
card->txbd_wrptr | rx_val)) {
mwifiex_dbg(adapter, ERROR,
"SEND DATA: failed to write reg->tx_wrptr\n");
ret = -1;
goto done_unmap;
}
if ((mwifiex_pcie_txbd_not_full(card)) &&
tx_param->next_pkt_len) {
/* have more packets and TxBD still can hold more */
mwifiex_dbg(adapter, DATA,
"SEND DATA: delay dnld-rdy interrupt.\n");
adapter->data_sent = false;
} else {
/* Send the TX ready interrupt */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DNLD_RDY)) {
mwifiex_dbg(adapter, ERROR,
"SEND DATA: failed to assert dnld-rdy interrupt.\n");
ret = -1;
goto done_unmap;
}
}
mwifiex_dbg(adapter, DATA,
"info: SEND DATA: Updated <Rd: %#x, Wr:\t"
"%#x> and sent packet to firmware successfully\n",
card->txbd_rdptr, card->txbd_wrptr);
} else {
mwifiex_dbg(adapter, DATA,
"info: TX Ring full, can't send packets to fw\n");
adapter->data_sent = true;
/* Send the TX ready interrupt */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DNLD_RDY))
mwifiex_dbg(adapter, ERROR,
"SEND DATA: failed to assert door-bell intr\n");
return -EBUSY;
}
return -EINPROGRESS;
done_unmap:
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
card->tx_buf_list[wrindx] = NULL;
atomic_dec(&adapter->tx_hw_pending);
if (reg->pfu_enabled)
memset(desc2, 0, sizeof(*desc2));
else
memset(desc, 0, sizeof(*desc));
return ret;
}
/*
* This function handles received buffer ring and
* dispatches packets to upper
*/
static int mwifiex_pcie_process_recv_data(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 wrptr, rd_index, tx_val;
dma_addr_t buf_pa;
int ret = 0;
struct sk_buff *skb_tmp = NULL;
struct mwifiex_pcie_buf_desc *desc;
struct mwifiex_pfu_buf_desc *desc2;
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
/* Read the RX ring Write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->rx_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"RECV DATA: failed to read reg->rx_wrptr\n");
ret = -1;
goto done;
}
card->rxbd_wrptr = wrptr;
while (((wrptr & reg->rx_mask) !=
(card->rxbd_rdptr & reg->rx_mask)) ||
((wrptr & reg->rx_rollover_ind) ==
(card->rxbd_rdptr & reg->rx_rollover_ind))) {
struct sk_buff *skb_data;
u16 rx_len;
rd_index = card->rxbd_rdptr & reg->rx_mask;
skb_data = card->rx_buf_list[rd_index];
/* If skb allocation was failed earlier for Rx packet,
* rx_buf_list[rd_index] would have been left with a NULL.
*/
if (!skb_data)
return -ENOMEM;
mwifiex_unmap_pci_memory(adapter, skb_data, PCI_DMA_FROMDEVICE);
card->rx_buf_list[rd_index] = NULL;
/* Get data length from interface header -
* first 2 bytes for len, next 2 bytes is for type
*/
rx_len = get_unaligned_le16(skb_data->data);
if (WARN_ON(rx_len <= adapter->intf_hdr_len ||
rx_len > MWIFIEX_RX_DATA_BUF_SIZE)) {
mwifiex_dbg(adapter, ERROR,
"Invalid RX len %d, Rd=%#x, Wr=%#x\n",
rx_len, card->rxbd_rdptr, wrptr);
dev_kfree_skb_any(skb_data);
} else {
skb_put(skb_data, rx_len);
mwifiex_dbg(adapter, DATA,
"info: RECV DATA: Rd=%#x, Wr=%#x, Len=%d\n",
card->rxbd_rdptr, wrptr, rx_len);
skb_pull(skb_data, adapter->intf_hdr_len);
if (adapter->rx_work_enabled) {
skb_queue_tail(&adapter->rx_data_q, skb_data);
adapter->data_received = true;
atomic_inc(&adapter->rx_pending);
} else {
mwifiex_handle_rx_packet(adapter, skb_data);
}
}
skb_tmp = mwifiex_alloc_dma_align_buf(MWIFIEX_RX_DATA_BUF_SIZE,
GFP_KERNEL);
if (!skb_tmp) {
mwifiex_dbg(adapter, ERROR,
"Unable to allocate skb.\n");
return -ENOMEM;
}
if (mwifiex_map_pci_memory(adapter, skb_tmp,
MWIFIEX_RX_DATA_BUF_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb_tmp);
mwifiex_dbg(adapter, INFO,
"RECV DATA: Attach new sk_buff %p at rxbd_rdidx=%d\n",
skb_tmp, rd_index);
card->rx_buf_list[rd_index] = skb_tmp;
if (reg->pfu_enabled) {
desc2 = card->rxbd_ring[rd_index];
desc2->paddr = buf_pa;
desc2->len = skb_tmp->len;
desc2->frag_len = skb_tmp->len;
desc2->offset = 0;
desc2->flags = reg->ring_flag_sop | reg->ring_flag_eop;
} else {
desc = card->rxbd_ring[rd_index];
desc->paddr = buf_pa;
desc->len = skb_tmp->len;
desc->flags = 0;
}
if ((++card->rxbd_rdptr & reg->rx_mask) ==
MWIFIEX_MAX_TXRX_BD) {
card->rxbd_rdptr = ((card->rxbd_rdptr &
reg->rx_rollover_ind) ^
reg->rx_rollover_ind);
}
mwifiex_dbg(adapter, DATA,
"info: RECV DATA: <Rd: %#x, Wr: %#x>\n",
card->rxbd_rdptr, wrptr);
tx_val = card->txbd_wrptr & reg->tx_wrap_mask;
/* Write the RX ring read pointer in to reg->rx_rdptr */
if (mwifiex_write_reg(adapter, reg->rx_rdptr,
card->rxbd_rdptr | tx_val)) {
mwifiex_dbg(adapter, DATA,
"RECV DATA: failed to write reg->rx_rdptr\n");
ret = -1;
goto done;
}
/* Read the RX ring Write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->rx_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"RECV DATA: failed to read reg->rx_wrptr\n");
ret = -1;
goto done;
}
mwifiex_dbg(adapter, DATA,
"info: RECV DATA: Rcvd packet from fw successfully\n");
card->rxbd_wrptr = wrptr;
}
done:
return ret;
}
/*
* This function downloads the boot command to device
*/
static int
mwifiex_pcie_send_boot_cmd(struct mwifiex_adapter *adapter, struct sk_buff *skb)
{
dma_addr_t buf_pa;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!(skb->data && skb->len)) {
mwifiex_dbg(adapter, ERROR,
"Invalid parameter in %s <%p. len %d>\n",
__func__, skb->data, skb->len);
return -1;
}
if (mwifiex_map_pci_memory(adapter, skb, skb->len, PCI_DMA_TODEVICE))
return -1;
buf_pa = MWIFIEX_SKB_DMA_ADDR(skb);
/* Write the lower 32bits of the physical address to low command
* address scratch register
*/
if (mwifiex_write_reg(adapter, reg->cmd_addr_lo, (u32)buf_pa)) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to write download command to boot code.\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
/* Write the upper 32bits of the physical address to high command
* address scratch register
*/
if (mwifiex_write_reg(adapter, reg->cmd_addr_hi,
(u32)((u64)buf_pa >> 32))) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to write download command to boot code.\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
/* Write the command length to cmd_size scratch register */
if (mwifiex_write_reg(adapter, reg->cmd_size, skb->len)) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to write command len to cmd_size scratch reg\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
/* Ring the door bell */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DOOR_BELL)) {
mwifiex_dbg(adapter, ERROR,
"%s: failed to assert door-bell intr\n", __func__);
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
return -1;
}
return 0;
}
/* This function init rx port in firmware which in turn enables to receive data
* from device before transmitting any packet.
*/
static int mwifiex_pcie_init_fw_port(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int tx_wrap = card->txbd_wrptr & reg->tx_wrap_mask;
/* Write the RX ring read pointer in to reg->rx_rdptr */
if (mwifiex_write_reg(adapter, reg->rx_rdptr, card->rxbd_rdptr |
tx_wrap)) {
mwifiex_dbg(adapter, ERROR,
"RECV DATA: failed to write reg->rx_rdptr\n");
return -1;
}
return 0;
}
/* This function downloads commands to the device
*/
static int
mwifiex_pcie_send_cmd(struct mwifiex_adapter *adapter, struct sk_buff *skb)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret = 0;
dma_addr_t cmd_buf_pa, cmdrsp_buf_pa;
u8 *payload = (u8 *)skb->data;
if (!(skb->data && skb->len)) {
mwifiex_dbg(adapter, ERROR,
"Invalid parameter in %s <%p, %#x>\n",
__func__, skb->data, skb->len);
return -1;
}
/* Make sure a command response buffer is available */
if (!card->cmdrsp_buf) {
mwifiex_dbg(adapter, ERROR,
"No response buffer available, send command failed\n");
return -EBUSY;
}
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
adapter->cmd_sent = true;
put_unaligned_le16((u16)skb->len, &payload[0]);
put_unaligned_le16(MWIFIEX_TYPE_CMD, &payload[2]);
if (mwifiex_map_pci_memory(adapter, skb, skb->len, PCI_DMA_TODEVICE))
return -1;
card->cmd_buf = skb;
/*
* Need to keep a reference, since core driver might free up this
* buffer before we've unmapped it.
*/
skb_get(skb);
/* To send a command, the driver will:
1. Write the 64bit physical address of the data buffer to
cmd response address low + cmd response address high
2. Ring the door bell (i.e. set the door bell interrupt)
In response to door bell interrupt, the firmware will perform
the DMA of the command packet (first header to obtain the total
length and then rest of the command).
*/
if (card->cmdrsp_buf) {
cmdrsp_buf_pa = MWIFIEX_SKB_DMA_ADDR(card->cmdrsp_buf);
/* Write the lower 32bits of the cmdrsp buffer physical
address */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_lo,
(u32)cmdrsp_buf_pa)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
/* Write the upper 32bits of the cmdrsp buffer physical
address */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_hi,
(u32)((u64)cmdrsp_buf_pa >> 32))) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
}
cmd_buf_pa = MWIFIEX_SKB_DMA_ADDR(card->cmd_buf);
/* Write the lower 32bits of the physical address to reg->cmd_addr_lo */
if (mwifiex_write_reg(adapter, reg->cmd_addr_lo,
(u32)cmd_buf_pa)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
/* Write the upper 32bits of the physical address to reg->cmd_addr_hi */
if (mwifiex_write_reg(adapter, reg->cmd_addr_hi,
(u32)((u64)cmd_buf_pa >> 32))) {
mwifiex_dbg(adapter, ERROR,
"Failed to write download cmd to boot code.\n");
ret = -1;
goto done;
}
/* Write the command length to reg->cmd_size */
if (mwifiex_write_reg(adapter, reg->cmd_size,
card->cmd_buf->len)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write cmd len to reg->cmd_size\n");
ret = -1;
goto done;
}
/* Ring the door bell */
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_DOOR_BELL)) {
mwifiex_dbg(adapter, ERROR,
"Failed to assert door-bell intr\n");
ret = -1;
goto done;
}
done:
if (ret)
adapter->cmd_sent = false;
return 0;
}
/*
* This function handles command complete interrupt
*/
static int mwifiex_pcie_process_cmd_complete(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct sk_buff *skb = card->cmdrsp_buf;
int count = 0;
u16 rx_len;
mwifiex_dbg(adapter, CMD,
"info: Rx CMD Response\n");
if (adapter->curr_cmd)
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_FROMDEVICE);
else
pci_dma_sync_single_for_cpu(card->dev,
MWIFIEX_SKB_DMA_ADDR(skb),
MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE);
/* Unmap the command as a response has been received. */
if (card->cmd_buf) {
mwifiex_unmap_pci_memory(adapter, card->cmd_buf,
PCI_DMA_TODEVICE);
dev_kfree_skb_any(card->cmd_buf);
card->cmd_buf = NULL;
}
rx_len = get_unaligned_le16(skb->data);
skb_put(skb, MWIFIEX_UPLD_SIZE - skb->len);
skb_trim(skb, rx_len);
if (!adapter->curr_cmd) {
if (adapter->ps_state == PS_STATE_SLEEP_CFM) {
pci_dma_sync_single_for_device(card->dev,
MWIFIEX_SKB_DMA_ADDR(skb),
MWIFIEX_SLEEP_COOKIE_SIZE,
PCI_DMA_FROMDEVICE);
if (mwifiex_write_reg(adapter,
PCIE_CPU_INT_EVENT,
CPU_INTR_SLEEP_CFM_DONE)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
mwifiex_delay_for_sleep_cookie(adapter,
MWIFIEX_MAX_DELAY_COUNT);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_FROMDEVICE);
skb_pull(skb, adapter->intf_hdr_len);
while (reg->sleep_cookie && (count++ < 10) &&
mwifiex_pcie_ok_to_access_hw(adapter))
usleep_range(50, 60);
mwifiex_pcie_enable_host_int(adapter);
mwifiex_process_sleep_confirm_resp(adapter, skb->data,
skb->len);
} else {
mwifiex_dbg(adapter, ERROR,
"There is no command but got cmdrsp\n");
}
memcpy(adapter->upld_buf, skb->data,
min_t(u32, MWIFIEX_SIZE_OF_CMD_BUFFER, skb->len));
skb_push(skb, adapter->intf_hdr_len);
if (mwifiex_map_pci_memory(adapter, skb, MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
} else if (mwifiex_pcie_ok_to_access_hw(adapter)) {
skb_pull(skb, adapter->intf_hdr_len);
adapter->curr_cmd->resp_skb = skb;
adapter->cmd_resp_received = true;
/* Take the pointer and set it to CMD node and will
return in the response complete callback */
card->cmdrsp_buf = NULL;
/* Clear the cmd-rsp buffer address in scratch registers. This
will prevent firmware from writing to the same response
buffer again. */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_lo, 0)) {
mwifiex_dbg(adapter, ERROR,
"cmd_done: failed to clear cmd_rsp_addr_lo\n");
return -1;
}
/* Write the upper 32bits of the cmdrsp buffer physical
address */
if (mwifiex_write_reg(adapter, reg->cmdrsp_addr_hi, 0)) {
mwifiex_dbg(adapter, ERROR,
"cmd_done: failed to clear cmd_rsp_addr_hi\n");
return -1;
}
}
return 0;
}
/*
* Command Response processing complete handler
*/
static int mwifiex_pcie_cmdrsp_complete(struct mwifiex_adapter *adapter,
struct sk_buff *skb)
{
struct pcie_service_card *card = adapter->card;
if (skb) {
card->cmdrsp_buf = skb;
skb_push(card->cmdrsp_buf, adapter->intf_hdr_len);
if (mwifiex_map_pci_memory(adapter, skb, MWIFIEX_UPLD_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
}
return 0;
}
/*
* This function handles firmware event ready interrupt
*/
static int mwifiex_pcie_process_event_ready(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 rdptr = card->evtbd_rdptr & MWIFIEX_EVTBD_MASK;
u32 wrptr, event;
struct mwifiex_evt_buf_desc *desc;
if (!mwifiex_pcie_ok_to_access_hw(adapter))
mwifiex_pm_wakeup_card(adapter);
if (adapter->event_received) {
mwifiex_dbg(adapter, EVENT,
"info: Event being processed,\t"
"do not process this interrupt just yet\n");
return 0;
}
if (rdptr >= MWIFIEX_MAX_EVT_BD) {
mwifiex_dbg(adapter, ERROR,
"info: Invalid read pointer...\n");
return -1;
}
/* Read the event ring write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->evt_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"EventReady: failed to read reg->evt_wrptr\n");
return -1;
}
mwifiex_dbg(adapter, EVENT,
"info: EventReady: Initial <Rd: 0x%x, Wr: 0x%x>",
card->evtbd_rdptr, wrptr);
if (((wrptr & MWIFIEX_EVTBD_MASK) != (card->evtbd_rdptr
& MWIFIEX_EVTBD_MASK)) ||
((wrptr & reg->evt_rollover_ind) ==
(card->evtbd_rdptr & reg->evt_rollover_ind))) {
struct sk_buff *skb_cmd;
__le16 data_len = 0;
u16 evt_len;
mwifiex_dbg(adapter, INFO,
"info: Read Index: %d\n", rdptr);
skb_cmd = card->evt_buf_list[rdptr];
mwifiex_unmap_pci_memory(adapter, skb_cmd, PCI_DMA_FROMDEVICE);
/* Take the pointer and set it to event pointer in adapter
and will return back after event handling callback */
card->evt_buf_list[rdptr] = NULL;
desc = card->evtbd_ring[rdptr];
memset(desc, 0, sizeof(*desc));
event = get_unaligned_le32(
&skb_cmd->data[adapter->intf_hdr_len]);
adapter->event_cause = event;
/* The first 4bytes will be the event transfer header
len is 2 bytes followed by type which is 2 bytes */
memcpy(&data_len, skb_cmd->data, sizeof(__le16));
evt_len = le16_to_cpu(data_len);
skb_trim(skb_cmd, evt_len);
skb_pull(skb_cmd, adapter->intf_hdr_len);
mwifiex_dbg(adapter, EVENT,
"info: Event length: %d\n", evt_len);
if (evt_len > MWIFIEX_EVENT_HEADER_LEN &&
evt_len < MAX_EVENT_SIZE)
memcpy(adapter->event_body, skb_cmd->data +
MWIFIEX_EVENT_HEADER_LEN, evt_len -
MWIFIEX_EVENT_HEADER_LEN);
adapter->event_received = true;
adapter->event_skb = skb_cmd;
/* Do not update the event read pointer here, wait till the
buffer is released. This is just to make things simpler,
we need to find a better method of managing these buffers.
*/
} else {
if (mwifiex_write_reg(adapter, PCIE_CPU_INT_EVENT,
CPU_INTR_EVENT_DONE)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
}
return 0;
}
/*
* Event processing complete handler
*/
static int mwifiex_pcie_event_complete(struct mwifiex_adapter *adapter,
struct sk_buff *skb)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret = 0;
u32 rdptr = card->evtbd_rdptr & MWIFIEX_EVTBD_MASK;
u32 wrptr;
struct mwifiex_evt_buf_desc *desc;
if (!skb)
return 0;
if (rdptr >= MWIFIEX_MAX_EVT_BD) {
mwifiex_dbg(adapter, ERROR,
"event_complete: Invalid rdptr 0x%x\n",
rdptr);
return -EINVAL;
}
/* Read the event ring write pointer set by firmware */
if (mwifiex_read_reg(adapter, reg->evt_wrptr, &wrptr)) {
mwifiex_dbg(adapter, ERROR,
"event_complete: failed to read reg->evt_wrptr\n");
return -1;
}
if (!card->evt_buf_list[rdptr]) {
skb_push(skb, adapter->intf_hdr_len);
skb_put(skb, MAX_EVENT_SIZE - skb->len);
if (mwifiex_map_pci_memory(adapter, skb,
MAX_EVENT_SIZE,
PCI_DMA_FROMDEVICE))
return -1;
card->evt_buf_list[rdptr] = skb;
desc = card->evtbd_ring[rdptr];
desc->paddr = MWIFIEX_SKB_DMA_ADDR(skb);
desc->len = (u16)skb->len;
desc->flags = 0;
skb = NULL;
} else {
mwifiex_dbg(adapter, ERROR,
"info: ERROR: buf still valid at index %d, <%p, %p>\n",
rdptr, card->evt_buf_list[rdptr], skb);
}
if ((++card->evtbd_rdptr & MWIFIEX_EVTBD_MASK) == MWIFIEX_MAX_EVT_BD) {
card->evtbd_rdptr = ((card->evtbd_rdptr &
reg->evt_rollover_ind) ^
reg->evt_rollover_ind);
}
mwifiex_dbg(adapter, EVENT,
"info: Updated <Rd: 0x%x, Wr: 0x%x>",
card->evtbd_rdptr, wrptr);
/* Write the event ring read pointer in to reg->evt_rdptr */
if (mwifiex_write_reg(adapter, reg->evt_rdptr,
card->evtbd_rdptr)) {
mwifiex_dbg(adapter, ERROR,
"event_complete: failed to read reg->evt_rdptr\n");
return -1;
}
mwifiex_dbg(adapter, EVENT,
"info: Check Events Again\n");
ret = mwifiex_pcie_process_event_ready(adapter);
return ret;
}
/* Combo firmware image is a combination of
* (1) combo crc heaer, start with CMD5
* (2) bluetooth image, start with CMD7, end with CMD6, data wrapped in CMD1.
* (3) wifi image.
*
* This function bypass the header and bluetooth part, return
* the offset of tail wifi-only part. If the image is already wifi-only,
* that is start with CMD1, return 0.
*/
static int mwifiex_extract_wifi_fw(struct mwifiex_adapter *adapter,
const void *firmware, u32 firmware_len) {
const struct mwifiex_fw_data *fwdata;
u32 offset = 0, data_len, dnld_cmd;
int ret = 0;
bool cmd7_before = false, first_cmd = false;
while (1) {
/* Check for integer and buffer overflow */
if (offset + sizeof(fwdata->header) < sizeof(fwdata->header) ||
offset + sizeof(fwdata->header) >= firmware_len) {
mwifiex_dbg(adapter, ERROR,
"extract wifi-only fw failure!\n");
ret = -1;
goto done;
}
fwdata = firmware + offset;
dnld_cmd = le32_to_cpu(fwdata->header.dnld_cmd);
data_len = le32_to_cpu(fwdata->header.data_length);
/* Skip past header */
offset += sizeof(fwdata->header);
switch (dnld_cmd) {
case MWIFIEX_FW_DNLD_CMD_1:
if (offset + data_len < data_len) {
mwifiex_dbg(adapter, ERROR, "bad FW parse\n");
ret = -1;
goto done;
}
/* Image start with cmd1, already wifi-only firmware */
if (!first_cmd) {
mwifiex_dbg(adapter, MSG,
"input wifi-only firmware\n");
return 0;
}
if (!cmd7_before) {
mwifiex_dbg(adapter, ERROR,
"no cmd7 before cmd1!\n");
ret = -1;
goto done;
}
offset += data_len;
break;
case MWIFIEX_FW_DNLD_CMD_5:
first_cmd = true;
/* Check for integer overflow */
if (offset + data_len < data_len) {
mwifiex_dbg(adapter, ERROR, "bad FW parse\n");
ret = -1;
goto done;
}
offset += data_len;
break;
case MWIFIEX_FW_DNLD_CMD_6:
first_cmd = true;
/* Check for integer overflow */
if (offset + data_len < data_len) {
mwifiex_dbg(adapter, ERROR, "bad FW parse\n");
ret = -1;
goto done;
}
offset += data_len;
if (offset >= firmware_len) {
mwifiex_dbg(adapter, ERROR,
"extract wifi-only fw failure!\n");
ret = -1;
} else {
ret = offset;
}
goto done;
case MWIFIEX_FW_DNLD_CMD_7:
first_cmd = true;
cmd7_before = true;
break;
default:
mwifiex_dbg(adapter, ERROR, "unknown dnld_cmd %d\n",
dnld_cmd);
ret = -1;
goto done;
}
}
done:
return ret;
}
/*
* This function downloads the firmware to the card.
*
* Firmware is downloaded to the card in blocks. Every block download
* is tested for CRC errors, and retried a number of times before
* returning failure.
*/
static int mwifiex_prog_fw_w_helper(struct mwifiex_adapter *adapter,
struct mwifiex_fw_image *fw)
{
int ret;
u8 *firmware = fw->fw_buf;
u32 firmware_len = fw->fw_len;
u32 offset = 0;
struct sk_buff *skb;
u32 txlen, tx_blocks = 0, tries, len, val;
u32 block_retry_cnt = 0;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (!firmware || !firmware_len) {
mwifiex_dbg(adapter, ERROR,
"No firmware image found! Terminating download\n");
return -1;
}
mwifiex_dbg(adapter, INFO,
"info: Downloading FW image (%d bytes)\n",
firmware_len);
if (mwifiex_pcie_disable_host_int(adapter)) {
mwifiex_dbg(adapter, ERROR,
"%s: Disabling interrupts failed.\n", __func__);
return -1;
}
skb = dev_alloc_skb(MWIFIEX_UPLD_SIZE);
if (!skb) {
ret = -ENOMEM;
goto done;
}
ret = mwifiex_read_reg(adapter, PCIE_SCRATCH_13_REG, &val);
if (ret) {
mwifiex_dbg(adapter, FATAL, "Failed to read scratch register 13\n");
goto done;
}
/* PCIE FLR case: extract wifi part from combo firmware*/
if (val == MWIFIEX_PCIE_FLR_HAPPENS) {
ret = mwifiex_extract_wifi_fw(adapter, firmware, firmware_len);
if (ret < 0) {
mwifiex_dbg(adapter, ERROR, "Failed to extract wifi fw\n");
goto done;
}
offset = ret;
mwifiex_dbg(adapter, MSG,
"info: dnld wifi firmware from %d bytes\n", offset);
}
/* Perform firmware data transfer */
do {
u32 ireg_intr = 0;
/* More data? */
if (offset >= firmware_len)
break;
for (tries = 0; tries < MAX_POLL_TRIES; tries++) {
ret = mwifiex_read_reg(adapter, reg->cmd_size,
&len);
if (ret) {
mwifiex_dbg(adapter, FATAL,
"Failed reading len from boot code\n");
goto done;
}
if (len)
break;
usleep_range(10, 20);
}
if (!len) {
break;
} else if (len > MWIFIEX_UPLD_SIZE) {
mwifiex_dbg(adapter, ERROR,
"FW download failure @ %d, invalid length %d\n",
offset, len);
ret = -1;
goto done;
}
txlen = len;
if (len & BIT(0)) {
block_retry_cnt++;
if (block_retry_cnt > MAX_WRITE_IOMEM_RETRY) {
mwifiex_dbg(adapter, ERROR,
"FW download failure @ %d, over max\t"
"retry count\n", offset);
ret = -1;
goto done;
}
mwifiex_dbg(adapter, ERROR,
"FW CRC error indicated by the\t"
"helper: len = 0x%04X, txlen = %d\n",
len, txlen);
len &= ~BIT(0);
/* Setting this to 0 to resend from same offset */
txlen = 0;
} else {
block_retry_cnt = 0;
/* Set blocksize to transfer - checking for
last block */
if (firmware_len - offset < txlen)
txlen = firmware_len - offset;
tx_blocks = (txlen + card->pcie.blksz_fw_dl - 1) /
card->pcie.blksz_fw_dl;
/* Copy payload to buffer */
memmove(skb->data, &firmware[offset], txlen);
}
skb_put(skb, MWIFIEX_UPLD_SIZE - skb->len);
skb_trim(skb, tx_blocks * card->pcie.blksz_fw_dl);
/* Send the boot command to device */
if (mwifiex_pcie_send_boot_cmd(adapter, skb)) {
mwifiex_dbg(adapter, ERROR,
"Failed to send firmware download command\n");
ret = -1;
goto done;
}
/* Wait for the command done interrupt */
for (tries = 0; tries < MAX_POLL_TRIES; tries++) {
if (mwifiex_read_reg(adapter, PCIE_CPU_INT_STATUS,
&ireg_intr)) {
mwifiex_dbg(adapter, ERROR,
"%s: Failed to read\t"
"interrupt status during fw dnld.\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
ret = -1;
goto done;
}
if (!(ireg_intr & CPU_INTR_DOOR_BELL))
break;
usleep_range(10, 20);
}
if (ireg_intr & CPU_INTR_DOOR_BELL) {
mwifiex_dbg(adapter, ERROR, "%s: Card failed to ACK download\n",
__func__);
mwifiex_unmap_pci_memory(adapter, skb,
PCI_DMA_TODEVICE);
ret = -1;
goto done;
}
mwifiex_unmap_pci_memory(adapter, skb, PCI_DMA_TODEVICE);
offset += txlen;
} while (true);
mwifiex_dbg(adapter, MSG,
"info: FW download over, size %d bytes\n", offset);
ret = 0;
done:
dev_kfree_skb_any(skb);
return ret;
}
/*
* This function checks the firmware status in card.
*/
static int
mwifiex_check_fw_status(struct mwifiex_adapter *adapter, u32 poll_num)
{
int ret = 0;
u32 firmware_stat;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
u32 tries;
/* Mask spurios interrupts */
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_STATUS_MASK,
HOST_INTR_MASK)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
mwifiex_dbg(adapter, INFO,
"Setting driver ready signature\n");
if (mwifiex_write_reg(adapter, reg->drv_rdy,
FIRMWARE_READY_PCIE)) {
mwifiex_dbg(adapter, ERROR,
"Failed to write driver ready signature\n");
return -1;
}
/* Wait for firmware initialization event */
for (tries = 0; tries < poll_num; tries++) {
if (mwifiex_read_reg(adapter, reg->fw_status,
&firmware_stat))
ret = -1;
else
ret = 0;
mwifiex_dbg(adapter, INFO, "Try %d if FW is ready <%d,%#x>",
tries, ret, firmware_stat);
if (ret)
continue;
if (firmware_stat == FIRMWARE_READY_PCIE) {
ret = 0;
break;
} else {
msleep(100);
ret = -1;
}
}
return ret;
}
/* This function checks if WLAN is the winner.
*/
static int
mwifiex_check_winner_status(struct mwifiex_adapter *adapter)
{
u32 winner = 0;
int ret = 0;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (mwifiex_read_reg(adapter, reg->fw_status, &winner)) {
ret = -1;
} else if (!winner) {
mwifiex_dbg(adapter, INFO, "PCI-E is the winner\n");
adapter->winner = 1;
} else {
mwifiex_dbg(adapter, ERROR,
"PCI-E is not the winner <%#x>", winner);
}
return ret;
}
/*
* This function reads the interrupt status from card.
*/
static void mwifiex_interrupt_status(struct mwifiex_adapter *adapter,
int msg_id)
{
u32 pcie_ireg;
unsigned long flags;
struct pcie_service_card *card = adapter->card;
if (card->msi_enable) {
spin_lock_irqsave(&adapter->int_lock, flags);
adapter->int_status = 1;
spin_unlock_irqrestore(&adapter->int_lock, flags);
return;
}
if (!mwifiex_pcie_ok_to_access_hw(adapter))
return;
if (card->msix_enable && msg_id >= 0) {
pcie_ireg = BIT(msg_id);
} else {
if (mwifiex_read_reg(adapter, PCIE_HOST_INT_STATUS,
&pcie_ireg)) {
mwifiex_dbg(adapter, ERROR, "Read register failed\n");
return;
}
if ((pcie_ireg == 0xFFFFFFFF) || !pcie_ireg)
return;
mwifiex_pcie_disable_host_int(adapter);
/* Clear the pending interrupts */
if (mwifiex_write_reg(adapter, PCIE_HOST_INT_STATUS,
~pcie_ireg)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return;
}
}
if (!adapter->pps_uapsd_mode &&
adapter->ps_state == PS_STATE_SLEEP &&
mwifiex_pcie_ok_to_access_hw(adapter)) {
/* Potentially for PCIe we could get other
* interrupts like shared. Don't change power
* state until cookie is set
*/
adapter->ps_state = PS_STATE_AWAKE;
adapter->pm_wakeup_fw_try = false;
del_timer(&adapter->wakeup_timer);
}
spin_lock_irqsave(&adapter->int_lock, flags);
adapter->int_status |= pcie_ireg;
spin_unlock_irqrestore(&adapter->int_lock, flags);
mwifiex_dbg(adapter, INTR, "ireg: 0x%08x\n", pcie_ireg);
}
/*
* Interrupt handler for PCIe root port
*
* This function reads the interrupt status from firmware and assigns
* the main process in workqueue which will handle the interrupt.
*/
static irqreturn_t mwifiex_pcie_interrupt(int irq, void *context)
{
struct mwifiex_msix_context *ctx = context;
struct pci_dev *pdev = ctx->dev;
struct pcie_service_card *card;
struct mwifiex_adapter *adapter;
card = pci_get_drvdata(pdev);
if (!card->adapter) {
pr_err("info: %s: card=%p adapter=%p\n", __func__, card,
card ? card->adapter : NULL);
goto exit;
}
adapter = card->adapter;
if (test_bit(MWIFIEX_SURPRISE_REMOVED, &adapter->work_flags))
goto exit;
if (card->msix_enable)
mwifiex_interrupt_status(adapter, ctx->msg_id);
else
mwifiex_interrupt_status(adapter, -1);
mwifiex_queue_main_work(adapter);
exit:
return IRQ_HANDLED;
}
/*
* This function checks the current interrupt status.
*
* The following interrupts are checked and handled by this function -
* - Data sent
* - Command sent
* - Command received
* - Packets received
* - Events received
*
* In case of Rx packets received, the packets are uploaded from card to
* host and processed accordingly.
*/
static int mwifiex_process_int_status(struct mwifiex_adapter *adapter)
{
int ret;
u32 pcie_ireg = 0;
unsigned long flags;
struct pcie_service_card *card = adapter->card;
spin_lock_irqsave(&adapter->int_lock, flags);
if (!card->msi_enable) {
/* Clear out unused interrupts */
pcie_ireg = adapter->int_status;
}
adapter->int_status = 0;
spin_unlock_irqrestore(&adapter->int_lock, flags);
if (card->msi_enable) {
if (mwifiex_pcie_ok_to_access_hw(adapter)) {
if (mwifiex_read_reg(adapter, PCIE_HOST_INT_STATUS,
&pcie_ireg)) {
mwifiex_dbg(adapter, ERROR,
"Read register failed\n");
return -1;
}
if ((pcie_ireg != 0xFFFFFFFF) && (pcie_ireg)) {
if (mwifiex_write_reg(adapter,
PCIE_HOST_INT_STATUS,
~pcie_ireg)) {
mwifiex_dbg(adapter, ERROR,
"Write register failed\n");
return -1;
}
if (!adapter->pps_uapsd_mode &&
adapter->ps_state == PS_STATE_SLEEP) {
adapter->ps_state = PS_STATE_AWAKE;
adapter->pm_wakeup_fw_try = false;
del_timer(&adapter->wakeup_timer);
}
}
}
}
if (pcie_ireg & HOST_INTR_DNLD_DONE) {
mwifiex_dbg(adapter, INTR, "info: TX DNLD Done\n");
ret = mwifiex_pcie_send_data_complete(adapter);
if (ret)
return ret;
}
if (pcie_ireg & HOST_INTR_UPLD_RDY) {
mwifiex_dbg(adapter, INTR, "info: Rx DATA\n");
ret = mwifiex_pcie_process_recv_data(adapter);
if (ret)
return ret;
}
if (pcie_ireg & HOST_INTR_EVENT_RDY) {
mwifiex_dbg(adapter, INTR, "info: Rx EVENT\n");
ret = mwifiex_pcie_process_event_ready(adapter);
if (ret)
return ret;
}
if (pcie_ireg & HOST_INTR_CMD_DONE) {
if (adapter->cmd_sent) {
mwifiex_dbg(adapter, INTR,
"info: CMD sent Interrupt\n");
adapter->cmd_sent = false;
}
/* Handle command response */
ret = mwifiex_pcie_process_cmd_complete(adapter);
if (ret)
return ret;
}
mwifiex_dbg(adapter, INTR,
"info: cmd_sent=%d data_sent=%d\n",
adapter->cmd_sent, adapter->data_sent);
if (!card->msi_enable && !card->msix_enable &&
adapter->ps_state != PS_STATE_SLEEP)
mwifiex_pcie_enable_host_int(adapter);
return 0;
}
/*
* This function downloads data from driver to card.
*
* Both commands and data packets are transferred to the card by this
* function.
*
* This function adds the PCIE specific header to the front of the buffer
* before transferring. The header contains the length of the packet and
* the type. The firmware handles the packets based upon this set type.
*/
static int mwifiex_pcie_host_to_card(struct mwifiex_adapter *adapter, u8 type,
struct sk_buff *skb,
struct mwifiex_tx_param *tx_param)
{
if (!skb) {
mwifiex_dbg(adapter, ERROR,
"Passed NULL skb to %s\n", __func__);
return -1;
}
if (type == MWIFIEX_TYPE_DATA)
return mwifiex_pcie_send_data(adapter, skb, tx_param);
else if (type == MWIFIEX_TYPE_CMD)
return mwifiex_pcie_send_cmd(adapter, skb);
return 0;
}
/* Function to dump PCIE scratch registers in case of FW crash
*/
static int
mwifiex_pcie_reg_dump(struct mwifiex_adapter *adapter, char *drv_buf)
{
char *p = drv_buf;
char buf[256], *ptr;
int i;
u32 value;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int pcie_scratch_reg[] = {PCIE_SCRATCH_12_REG,
PCIE_SCRATCH_14_REG,
PCIE_SCRATCH_15_REG};
if (!p)
return 0;
mwifiex_dbg(adapter, MSG, "PCIE register dump start\n");
if (mwifiex_read_reg(adapter, reg->fw_status, &value)) {
mwifiex_dbg(adapter, ERROR, "failed to read firmware status");
return 0;
}
ptr = buf;
mwifiex_dbg(adapter, MSG, "pcie scratch register:");
for (i = 0; i < ARRAY_SIZE(pcie_scratch_reg); i++) {
mwifiex_read_reg(adapter, pcie_scratch_reg[i], &value);
ptr += sprintf(ptr, "reg:0x%x, value=0x%x\n",
pcie_scratch_reg[i], value);
}
mwifiex_dbg(adapter, MSG, "%s\n", buf);
p += sprintf(p, "%s\n", buf);
mwifiex_dbg(adapter, MSG, "PCIE register dump end\n");
return p - drv_buf;
}
/* This function read/write firmware */
static enum rdwr_status
mwifiex_pcie_rdwr_firmware(struct mwifiex_adapter *adapter, u8 doneflag)
{
int ret, tries;
u8 ctrl_data;
u32 fw_status;
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (mwifiex_read_reg(adapter, reg->fw_status, &fw_status))
return RDWR_STATUS_FAILURE;
ret = mwifiex_write_reg(adapter, reg->fw_dump_ctrl,
reg->fw_dump_host_ready);
if (ret) {
mwifiex_dbg(adapter, ERROR,
"PCIE write err\n");
return RDWR_STATUS_FAILURE;
}
for (tries = 0; tries < MAX_POLL_TRIES; tries++) {
mwifiex_read_reg_byte(adapter, reg->fw_dump_ctrl, &ctrl_data);
if (ctrl_data == FW_DUMP_DONE)
return RDWR_STATUS_SUCCESS;
if (doneflag && ctrl_data == doneflag)
return RDWR_STATUS_DONE;
if (ctrl_data != reg->fw_dump_host_ready) {
mwifiex_dbg(adapter, WARN,
"The ctrl reg was changed, re-try again!\n");
ret = mwifiex_write_reg(adapter, reg->fw_dump_ctrl,
reg->fw_dump_host_ready);
if (ret) {
mwifiex_dbg(adapter, ERROR,
"PCIE write err\n");
return RDWR_STATUS_FAILURE;
}
}
usleep_range(100, 200);
}
mwifiex_dbg(adapter, ERROR, "Fail to pull ctrl_data\n");
return RDWR_STATUS_FAILURE;
}
/* This function dump firmware memory to file */
static void mwifiex_pcie_fw_dump(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *creg = card->pcie.reg;
unsigned int reg, reg_start, reg_end;
u8 *dbg_ptr, *end_ptr, *tmp_ptr, fw_dump_num, dump_num;
u8 idx, i, read_reg, doneflag = 0;
enum rdwr_status stat;
u32 memory_size;
int ret;
if (!card->pcie.can_dump_fw)
return;
for (idx = 0; idx < adapter->num_mem_types; idx++) {
struct memory_type_mapping *entry =
&adapter->mem_type_mapping_tbl[idx];
if (entry->mem_ptr) {
vfree(entry->mem_ptr);
entry->mem_ptr = NULL;
}
entry->mem_size = 0;
}
mwifiex_dbg(adapter, MSG, "== mwifiex firmware dump start ==\n");
/* Read the number of the memories which will dump */
stat = mwifiex_pcie_rdwr_firmware(adapter, doneflag);
if (stat == RDWR_STATUS_FAILURE)
return;
reg = creg->fw_dump_start;
mwifiex_read_reg_byte(adapter, reg, &fw_dump_num);
/* W8997 chipset firmware dump will be restore in single region*/
if (fw_dump_num == 0)
dump_num = 1;
else
dump_num = fw_dump_num;
/* Read the length of every memory which will dump */
for (idx = 0; idx < dump_num; idx++) {
struct memory_type_mapping *entry =
&adapter->mem_type_mapping_tbl[idx];
memory_size = 0;
if (fw_dump_num != 0) {
stat = mwifiex_pcie_rdwr_firmware(adapter, doneflag);
if (stat == RDWR_STATUS_FAILURE)
return;
reg = creg->fw_dump_start;
for (i = 0; i < 4; i++) {
mwifiex_read_reg_byte(adapter, reg, &read_reg);
memory_size |= (read_reg << (i * 8));
reg++;
}
} else {
memory_size = MWIFIEX_FW_DUMP_MAX_MEMSIZE;
}
if (memory_size == 0) {
mwifiex_dbg(adapter, MSG, "Firmware dump Finished!\n");
ret = mwifiex_write_reg(adapter, creg->fw_dump_ctrl,
creg->fw_dump_read_done);
if (ret) {
mwifiex_dbg(adapter, ERROR, "PCIE write err\n");
return;
}
break;
}
mwifiex_dbg(adapter, DUMP,
"%s_SIZE=0x%x\n", entry->mem_name, memory_size);
entry->mem_ptr = vmalloc(memory_size + 1);
entry->mem_size = memory_size;
if (!entry->mem_ptr) {
mwifiex_dbg(adapter, ERROR,
"Vmalloc %s failed\n", entry->mem_name);
return;
}
dbg_ptr = entry->mem_ptr;
end_ptr = dbg_ptr + memory_size;
doneflag = entry->done_flag;
mwifiex_dbg(adapter, DUMP, "Start %s output, please wait...\n",
entry->mem_name);
do {
stat = mwifiex_pcie_rdwr_firmware(adapter, doneflag);
if (RDWR_STATUS_FAILURE == stat)
return;
reg_start = creg->fw_dump_start;
reg_end = creg->fw_dump_end;
for (reg = reg_start; reg <= reg_end; reg++) {
mwifiex_read_reg_byte(adapter, reg, dbg_ptr);
if (dbg_ptr < end_ptr) {
dbg_ptr++;
continue;
}
mwifiex_dbg(adapter, ERROR,
"pre-allocated buf not enough\n");
tmp_ptr =
vzalloc(memory_size + MWIFIEX_SIZE_4K);
if (!tmp_ptr)
return;
memcpy(tmp_ptr, entry->mem_ptr, memory_size);
vfree(entry->mem_ptr);
entry->mem_ptr = tmp_ptr;
tmp_ptr = NULL;
dbg_ptr = entry->mem_ptr + memory_size;
memory_size += MWIFIEX_SIZE_4K;
end_ptr = entry->mem_ptr + memory_size;
}
if (stat != RDWR_STATUS_DONE)
continue;
mwifiex_dbg(adapter, DUMP,
"%s done: size=0x%tx\n",
entry->mem_name, dbg_ptr - entry->mem_ptr);
break;
} while (true);
}
mwifiex_dbg(adapter, MSG, "== mwifiex firmware dump end ==\n");
}
static void mwifiex_pcie_device_dump_work(struct mwifiex_adapter *adapter)
{
adapter->devdump_data = vzalloc(MWIFIEX_FW_DUMP_SIZE);
if (!adapter->devdump_data) {
mwifiex_dbg(adapter, ERROR,
"vzalloc devdump data failure!\n");
return;
}
mwifiex_drv_info_dump(adapter);
mwifiex_pcie_fw_dump(adapter);
mwifiex_prepare_fw_dump_info(adapter);
mwifiex_upload_device_dump(adapter);
}
static void mwifiex_pcie_card_reset_work(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
/* We can't afford to wait here; remove() might be waiting on us. If we
* can't grab the device lock, maybe we'll get another chance later.
*/
pci_try_reset_function(card->dev);
}
static void mwifiex_pcie_work(struct work_struct *work)
{
struct pcie_service_card *card =
container_of(work, struct pcie_service_card, work);
if (test_and_clear_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP,
&card->work_flags))
mwifiex_pcie_device_dump_work(card->adapter);
if (test_and_clear_bit(MWIFIEX_IFACE_WORK_CARD_RESET,
&card->work_flags))
mwifiex_pcie_card_reset_work(card->adapter);
}
/* This function dumps FW information */
static void mwifiex_pcie_device_dump(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
if (!test_and_set_bit(MWIFIEX_IFACE_WORK_DEVICE_DUMP,
&card->work_flags))
schedule_work(&card->work);
}
static void mwifiex_pcie_card_reset(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
if (!test_and_set_bit(MWIFIEX_IFACE_WORK_CARD_RESET, &card->work_flags))
schedule_work(&card->work);
}
static int mwifiex_pcie_alloc_buffers(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret;
card->cmdrsp_buf = NULL;
ret = mwifiex_pcie_create_txbd_ring(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to create txbd ring\n");
goto err_cre_txbd;
}
ret = mwifiex_pcie_create_rxbd_ring(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to create rxbd ring\n");
goto err_cre_rxbd;
}
ret = mwifiex_pcie_create_evtbd_ring(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to create evtbd ring\n");
goto err_cre_evtbd;
}
ret = mwifiex_pcie_alloc_cmdrsp_buf(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to allocate cmdbuf buffer\n");
goto err_alloc_cmdbuf;
}
if (reg->sleep_cookie) {
ret = mwifiex_pcie_alloc_sleep_cookie_buf(adapter);
if (ret) {
mwifiex_dbg(adapter, ERROR, "Failed to allocate sleep_cookie buffer\n");
goto err_alloc_cookie;
}
} else {
card->sleep_cookie_vbase = NULL;
}
return 0;
err_alloc_cookie:
mwifiex_pcie_delete_cmdrsp_buf(adapter);
err_alloc_cmdbuf:
mwifiex_pcie_delete_evtbd_ring(adapter);
err_cre_evtbd:
mwifiex_pcie_delete_rxbd_ring(adapter);
err_cre_rxbd:
mwifiex_pcie_delete_txbd_ring(adapter);
err_cre_txbd:
return ret;
}
static void mwifiex_pcie_free_buffers(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
if (reg->sleep_cookie)
mwifiex_pcie_delete_sleep_cookie_buf(adapter);
mwifiex_pcie_delete_cmdrsp_buf(adapter);
mwifiex_pcie_delete_evtbd_ring(adapter);
mwifiex_pcie_delete_rxbd_ring(adapter);
mwifiex_pcie_delete_txbd_ring(adapter);
}
/*
* This function initializes the PCI-E host memory space, WCB rings, etc.
*/
static int mwifiex_init_pcie(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
int ret;
struct pci_dev *pdev = card->dev;
pci_set_drvdata(pdev, card);
ret = pci_enable_device(pdev);
if (ret)
goto err_enable_dev;
pci_set_master(pdev);
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
pr_err("set_dma_mask(32) failed: %d\n", ret);
goto err_set_dma_mask;
}
ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
pr_err("set_consistent_dma_mask(64) failed\n");
goto err_set_dma_mask;
}
ret = pci_request_region(pdev, 0, DRV_NAME);
if (ret) {
pr_err("req_reg(0) error\n");
goto err_req_region0;
}
card->pci_mmap = pci_iomap(pdev, 0, 0);
if (!card->pci_mmap) {
pr_err("iomap(0) error\n");
ret = -EIO;
goto err_iomap0;
}
ret = pci_request_region(pdev, 2, DRV_NAME);
if (ret) {
pr_err("req_reg(2) error\n");
goto err_req_region2;
}
card->pci_mmap1 = pci_iomap(pdev, 2, 0);
if (!card->pci_mmap1) {
pr_err("iomap(2) error\n");
ret = -EIO;
goto err_iomap2;
}
pr_notice("PCI memory map Virt0: %pK PCI memory map Virt2: %pK\n",
card->pci_mmap, card->pci_mmap1);
ret = mwifiex_pcie_alloc_buffers(adapter);
if (ret)
goto err_alloc_buffers;
return 0;
err_alloc_buffers:
pci_iounmap(pdev, card->pci_mmap1);
err_iomap2:
pci_release_region(pdev, 2);
err_req_region2:
pci_iounmap(pdev, card->pci_mmap);
err_iomap0:
pci_release_region(pdev, 0);
err_req_region0:
err_set_dma_mask:
pci_disable_device(pdev);
err_enable_dev:
return ret;
}
/*
* This function cleans up the allocated card buffers.
*/
static void mwifiex_cleanup_pcie(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
int ret;
u32 fw_status;
cancel_work_sync(&card->work);
ret = mwifiex_read_reg(adapter, reg->fw_status, &fw_status);
if (fw_status == FIRMWARE_READY_PCIE) {
mwifiex_dbg(adapter, INFO,
"Clearing driver ready signature\n");
if (mwifiex_write_reg(adapter, reg->drv_rdy, 0x00000000))
mwifiex_dbg(adapter, ERROR,
"Failed to write driver not-ready signature\n");
}
pci_disable_device(pdev);
pci_iounmap(pdev, card->pci_mmap);
pci_iounmap(pdev, card->pci_mmap1);
pci_release_region(pdev, 2);
pci_release_region(pdev, 0);
mwifiex_pcie_free_buffers(adapter);
}
static int mwifiex_pcie_request_irq(struct mwifiex_adapter *adapter)
{
int ret, i, j;
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
if (card->pcie.reg->msix_support) {
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++)
card->msix_entries[i].entry = i;
ret = pci_enable_msix_exact(pdev, card->msix_entries,
MWIFIEX_NUM_MSIX_VECTORS);
if (!ret) {
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++) {
card->msix_ctx[i].dev = pdev;
card->msix_ctx[i].msg_id = i;
ret = request_irq(card->msix_entries[i].vector,
mwifiex_pcie_interrupt, 0,
"MWIFIEX_PCIE_MSIX",
&card->msix_ctx[i]);
if (ret)
break;
}
if (ret) {
mwifiex_dbg(adapter, INFO, "request_irq fail: %d\n",
ret);
for (j = 0; j < i; j++)
free_irq(card->msix_entries[j].vector,
&card->msix_ctx[i]);
pci_disable_msix(pdev);
} else {
mwifiex_dbg(adapter, MSG, "MSIx enabled!");
card->msix_enable = 1;
return 0;
}
}
}
if (pci_enable_msi(pdev) != 0)
pci_disable_msi(pdev);
else
card->msi_enable = 1;
mwifiex_dbg(adapter, INFO, "msi_enable = %d\n", card->msi_enable);
card->share_irq_ctx.dev = pdev;
card->share_irq_ctx.msg_id = -1;
ret = request_irq(pdev->irq, mwifiex_pcie_interrupt, IRQF_SHARED,
"MRVL_PCIE", &card->share_irq_ctx);
if (ret) {
pr_err("request_irq failed: ret=%d\n", ret);
return -1;
}
return 0;
}
/*
* This function gets the firmware name for downloading by revision id
*
* Read revision id register to get revision id
*/
static void mwifiex_pcie_get_fw_name(struct mwifiex_adapter *adapter)
{
int revision_id = 0;
int version, magic;
struct pcie_service_card *card = adapter->card;
switch (card->dev->device) {
case PCIE_DEVICE_ID_MARVELL_88W8766P:
strcpy(adapter->fw_name, PCIE8766_DEFAULT_FW_NAME);
break;
case PCIE_DEVICE_ID_MARVELL_88W8897:
mwifiex_write_reg(adapter, 0x0c58, 0x80c00000);
mwifiex_read_reg(adapter, 0x0c58, &revision_id);
revision_id &= 0xff00;
switch (revision_id) {
case PCIE8897_A0:
strcpy(adapter->fw_name, PCIE8897_A0_FW_NAME);
break;
case PCIE8897_B0:
strcpy(adapter->fw_name, PCIE8897_B0_FW_NAME);
break;
default:
strcpy(adapter->fw_name, PCIE8897_DEFAULT_FW_NAME);
break;
}
break;
case PCIE_DEVICE_ID_MARVELL_88W8997:
mwifiex_read_reg(adapter, 0x8, &revision_id);
mwifiex_read_reg(adapter, 0x0cd0, &version);
mwifiex_read_reg(adapter, 0x0cd4, &magic);
revision_id &= 0xff;
version &= 0x7;
magic &= 0xff;
if (revision_id == PCIE8997_A1 &&
magic == CHIP_MAGIC_VALUE &&
version == CHIP_VER_PCIEUART)
strcpy(adapter->fw_name, PCIEUART8997_FW_NAME_V4);
else
strcpy(adapter->fw_name, PCIEUSB8997_FW_NAME_V4);
break;
default:
break;
}
}
/*
* This function registers the PCIE device.
*
* PCIE IRQ is claimed, block size is set and driver data is initialized.
*/
static int mwifiex_register_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
/* save adapter pointer in card */
card->adapter = adapter;
if (mwifiex_pcie_request_irq(adapter))
return -1;
adapter->tx_buf_size = card->pcie.tx_buf_size;
adapter->mem_type_mapping_tbl = card->pcie.mem_type_mapping_tbl;
adapter->num_mem_types = card->pcie.num_mem_types;
adapter->ext_scan = card->pcie.can_ext_scan;
mwifiex_pcie_get_fw_name(adapter);
return 0;
}
/*
* This function unregisters the PCIE device.
*
* The PCIE IRQ is released, the function is disabled and driver
* data is set to null.
*/
static void mwifiex_unregister_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
int i;
if (card->msix_enable) {
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++)
synchronize_irq(card->msix_entries[i].vector);
for (i = 0; i < MWIFIEX_NUM_MSIX_VECTORS; i++)
free_irq(card->msix_entries[i].vector,
&card->msix_ctx[i]);
card->msix_enable = 0;
pci_disable_msix(pdev);
} else {
mwifiex_dbg(adapter, INFO,
"%s(): calling free_irq()\n", __func__);
free_irq(card->dev->irq, &card->share_irq_ctx);
if (card->msi_enable)
pci_disable_msi(pdev);
}
card->adapter = NULL;
}
/*
* This function initializes the PCI-E host memory space, WCB rings, etc.,
* similar to mwifiex_init_pcie(), but without resetting PCI-E state.
*/
static void mwifiex_pcie_up_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
struct pci_dev *pdev = card->dev;
/* tx_buf_size might be changed to 3584 by firmware during
* data transfer, we should reset it to default size.
*/
adapter->tx_buf_size = card->pcie.tx_buf_size;
mwifiex_pcie_alloc_buffers(adapter);
pci_set_master(pdev);
}
/* This function cleans up the PCI-E host memory space. */
static void mwifiex_pcie_down_dev(struct mwifiex_adapter *adapter)
{
struct pcie_service_card *card = adapter->card;
const struct mwifiex_pcie_card_reg *reg = card->pcie.reg;
struct pci_dev *pdev = card->dev;
if (mwifiex_write_reg(adapter, reg->drv_rdy, 0x00000000))
mwifiex_dbg(adapter, ERROR, "Failed to write driver not-ready signature\n");
pci_clear_master(pdev);
adapter->seq_num = 0;
mwifiex_pcie_free_buffers(adapter);
}
static struct mwifiex_if_ops pcie_ops = {
.init_if = mwifiex_init_pcie,
.cleanup_if = mwifiex_cleanup_pcie,
.check_fw_status = mwifiex_check_fw_status,
.check_winner_status = mwifiex_check_winner_status,
.prog_fw = mwifiex_prog_fw_w_helper,
.register_dev = mwifiex_register_dev,
.unregister_dev = mwifiex_unregister_dev,
.enable_int = mwifiex_pcie_enable_host_int,
.disable_int = mwifiex_pcie_disable_host_int_noerr,
.process_int_status = mwifiex_process_int_status,
.host_to_card = mwifiex_pcie_host_to_card,
.wakeup = mwifiex_pm_wakeup_card,
.wakeup_complete = mwifiex_pm_wakeup_card_complete,
/* PCIE specific */
.cmdrsp_complete = mwifiex_pcie_cmdrsp_complete,
.event_complete = mwifiex_pcie_event_complete,
.update_mp_end_port = NULL,
.cleanup_mpa_buf = NULL,
.init_fw_port = mwifiex_pcie_init_fw_port,
.clean_pcie_ring = mwifiex_clean_pcie_ring_buf,
.card_reset = mwifiex_pcie_card_reset,
.reg_dump = mwifiex_pcie_reg_dump,
.device_dump = mwifiex_pcie_device_dump,
.down_dev = mwifiex_pcie_down_dev,
.up_dev = mwifiex_pcie_up_dev,
};
module_pci_driver(mwifiex_pcie);
MODULE_AUTHOR("Marvell International Ltd.");
MODULE_DESCRIPTION("Marvell WiFi-Ex PCI-Express Driver version " PCIE_VERSION);
MODULE_VERSION(PCIE_VERSION);
MODULE_LICENSE("GPL v2");
| ./CrossVul/dataset_final_sorted/CWE-400/c/good_1246_0 |
crossvul-cpp_data_bad_1273_3 | /*
* Copyright 2012-15 Advanced Micro Devices, Inc.cls
*
*
* 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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: AMD
*
*/
#include <linux/slab.h>
#include "dm_services.h"
#include "stream_encoder.h"
#include "resource.h"
#include "include/irq_service_interface.h"
#include "dce120_resource.h"
#include "dce112/dce112_resource.h"
#include "dce110/dce110_resource.h"
#include "../virtual/virtual_stream_encoder.h"
#include "dce120_timing_generator.h"
#include "irq/dce120/irq_service_dce120.h"
#include "dce/dce_opp.h"
#include "dce/dce_clock_source.h"
#include "dce/dce_ipp.h"
#include "dce/dce_mem_input.h"
#include "dce110/dce110_hw_sequencer.h"
#include "dce120/dce120_hw_sequencer.h"
#include "dce/dce_transform.h"
#include "clk_mgr.h"
#include "dce/dce_audio.h"
#include "dce/dce_link_encoder.h"
#include "dce/dce_stream_encoder.h"
#include "dce/dce_hwseq.h"
#include "dce/dce_abm.h"
#include "dce/dce_dmcu.h"
#include "dce/dce_aux.h"
#include "dce/dce_i2c.h"
#include "dce/dce_12_0_offset.h"
#include "dce/dce_12_0_sh_mask.h"
#include "soc15_hw_ip.h"
#include "vega10_ip_offset.h"
#include "nbio/nbio_6_1_offset.h"
#include "mmhub/mmhub_9_4_0_offset.h"
#include "mmhub/mmhub_9_4_0_sh_mask.h"
#include "reg_helper.h"
#include "dce100/dce100_resource.h"
#ifndef mmDP0_DP_DPHY_INTERNAL_CTRL
#define mmDP0_DP_DPHY_INTERNAL_CTRL 0x210f
#define mmDP0_DP_DPHY_INTERNAL_CTRL_BASE_IDX 2
#define mmDP1_DP_DPHY_INTERNAL_CTRL 0x220f
#define mmDP1_DP_DPHY_INTERNAL_CTRL_BASE_IDX 2
#define mmDP2_DP_DPHY_INTERNAL_CTRL 0x230f
#define mmDP2_DP_DPHY_INTERNAL_CTRL_BASE_IDX 2
#define mmDP3_DP_DPHY_INTERNAL_CTRL 0x240f
#define mmDP3_DP_DPHY_INTERNAL_CTRL_BASE_IDX 2
#define mmDP4_DP_DPHY_INTERNAL_CTRL 0x250f
#define mmDP4_DP_DPHY_INTERNAL_CTRL_BASE_IDX 2
#define mmDP5_DP_DPHY_INTERNAL_CTRL 0x260f
#define mmDP5_DP_DPHY_INTERNAL_CTRL_BASE_IDX 2
#define mmDP6_DP_DPHY_INTERNAL_CTRL 0x270f
#define mmDP6_DP_DPHY_INTERNAL_CTRL_BASE_IDX 2
#endif
enum dce120_clk_src_array_id {
DCE120_CLK_SRC_PLL0,
DCE120_CLK_SRC_PLL1,
DCE120_CLK_SRC_PLL2,
DCE120_CLK_SRC_PLL3,
DCE120_CLK_SRC_PLL4,
DCE120_CLK_SRC_PLL5,
DCE120_CLK_SRC_TOTAL
};
static const struct dce110_timing_generator_offsets dce120_tg_offsets[] = {
{
.crtc = (mmCRTC0_CRTC_CONTROL - mmCRTC0_CRTC_CONTROL),
},
{
.crtc = (mmCRTC1_CRTC_CONTROL - mmCRTC0_CRTC_CONTROL),
},
{
.crtc = (mmCRTC2_CRTC_CONTROL - mmCRTC0_CRTC_CONTROL),
},
{
.crtc = (mmCRTC3_CRTC_CONTROL - mmCRTC0_CRTC_CONTROL),
},
{
.crtc = (mmCRTC4_CRTC_CONTROL - mmCRTC0_CRTC_CONTROL),
},
{
.crtc = (mmCRTC5_CRTC_CONTROL - mmCRTC0_CRTC_CONTROL),
}
};
/* begin *********************
* macros to expend register list macro defined in HW object header file */
#define BASE_INNER(seg) \
DCE_BASE__INST0_SEG ## seg
#define NBIO_BASE_INNER(seg) \
NBIF_BASE__INST0_SEG ## seg
#define NBIO_BASE(seg) \
NBIO_BASE_INNER(seg)
/* compile time expand base address. */
#define BASE(seg) \
BASE_INNER(seg)
#define SR(reg_name)\
.reg_name = BASE(mm ## reg_name ## _BASE_IDX) + \
mm ## reg_name
#define SRI(reg_name, block, id)\
.reg_name = BASE(mm ## block ## id ## _ ## reg_name ## _BASE_IDX) + \
mm ## block ## id ## _ ## reg_name
/* MMHUB */
#define MMHUB_BASE_INNER(seg) \
MMHUB_BASE__INST0_SEG ## seg
#define MMHUB_BASE(seg) \
MMHUB_BASE_INNER(seg)
#define MMHUB_SR(reg_name)\
.reg_name = MMHUB_BASE(mm ## reg_name ## _BASE_IDX) + \
mm ## reg_name
/* macros to expend register list macro defined in HW object header file
* end *********************/
static const struct dce_dmcu_registers dmcu_regs = {
DMCU_DCE110_COMMON_REG_LIST()
};
static const struct dce_dmcu_shift dmcu_shift = {
DMCU_MASK_SH_LIST_DCE110(__SHIFT)
};
static const struct dce_dmcu_mask dmcu_mask = {
DMCU_MASK_SH_LIST_DCE110(_MASK)
};
static const struct dce_abm_registers abm_regs = {
ABM_DCE110_COMMON_REG_LIST()
};
static const struct dce_abm_shift abm_shift = {
ABM_MASK_SH_LIST_DCE110(__SHIFT)
};
static const struct dce_abm_mask abm_mask = {
ABM_MASK_SH_LIST_DCE110(_MASK)
};
#define ipp_regs(id)\
[id] = {\
IPP_DCE110_REG_LIST_DCE_BASE(id)\
}
static const struct dce_ipp_registers ipp_regs[] = {
ipp_regs(0),
ipp_regs(1),
ipp_regs(2),
ipp_regs(3),
ipp_regs(4),
ipp_regs(5)
};
static const struct dce_ipp_shift ipp_shift = {
IPP_DCE120_MASK_SH_LIST_SOC_BASE(__SHIFT)
};
static const struct dce_ipp_mask ipp_mask = {
IPP_DCE120_MASK_SH_LIST_SOC_BASE(_MASK)
};
#define transform_regs(id)\
[id] = {\
XFM_COMMON_REG_LIST_DCE110(id)\
}
static const struct dce_transform_registers xfm_regs[] = {
transform_regs(0),
transform_regs(1),
transform_regs(2),
transform_regs(3),
transform_regs(4),
transform_regs(5)
};
static const struct dce_transform_shift xfm_shift = {
XFM_COMMON_MASK_SH_LIST_SOC_BASE(__SHIFT)
};
static const struct dce_transform_mask xfm_mask = {
XFM_COMMON_MASK_SH_LIST_SOC_BASE(_MASK)
};
#define aux_regs(id)\
[id] = {\
AUX_REG_LIST(id)\
}
static const struct dce110_link_enc_aux_registers link_enc_aux_regs[] = {
aux_regs(0),
aux_regs(1),
aux_regs(2),
aux_regs(3),
aux_regs(4),
aux_regs(5)
};
#define hpd_regs(id)\
[id] = {\
HPD_REG_LIST(id)\
}
static const struct dce110_link_enc_hpd_registers link_enc_hpd_regs[] = {
hpd_regs(0),
hpd_regs(1),
hpd_regs(2),
hpd_regs(3),
hpd_regs(4),
hpd_regs(5)
};
#define link_regs(id)\
[id] = {\
LE_DCE120_REG_LIST(id), \
SRI(DP_DPHY_INTERNAL_CTRL, DP, id) \
}
static const struct dce110_link_enc_registers link_enc_regs[] = {
link_regs(0),
link_regs(1),
link_regs(2),
link_regs(3),
link_regs(4),
link_regs(5),
link_regs(6),
};
#define stream_enc_regs(id)\
[id] = {\
SE_COMMON_REG_LIST(id),\
.TMDS_CNTL = 0,\
}
static const struct dce110_stream_enc_registers stream_enc_regs[] = {
stream_enc_regs(0),
stream_enc_regs(1),
stream_enc_regs(2),
stream_enc_regs(3),
stream_enc_regs(4),
stream_enc_regs(5)
};
static const struct dce_stream_encoder_shift se_shift = {
SE_COMMON_MASK_SH_LIST_DCE120(__SHIFT)
};
static const struct dce_stream_encoder_mask se_mask = {
SE_COMMON_MASK_SH_LIST_DCE120(_MASK)
};
#define opp_regs(id)\
[id] = {\
OPP_DCE_120_REG_LIST(id),\
}
static const struct dce_opp_registers opp_regs[] = {
opp_regs(0),
opp_regs(1),
opp_regs(2),
opp_regs(3),
opp_regs(4),
opp_regs(5)
};
static const struct dce_opp_shift opp_shift = {
OPP_COMMON_MASK_SH_LIST_DCE_120(__SHIFT)
};
static const struct dce_opp_mask opp_mask = {
OPP_COMMON_MASK_SH_LIST_DCE_120(_MASK)
};
#define aux_engine_regs(id)\
[id] = {\
AUX_COMMON_REG_LIST(id), \
.AUX_RESET_MASK = 0 \
}
static const struct dce110_aux_registers aux_engine_regs[] = {
aux_engine_regs(0),
aux_engine_regs(1),
aux_engine_regs(2),
aux_engine_regs(3),
aux_engine_regs(4),
aux_engine_regs(5)
};
#define audio_regs(id)\
[id] = {\
AUD_COMMON_REG_LIST(id)\
}
static const struct dce_audio_registers audio_regs[] = {
audio_regs(0),
audio_regs(1),
audio_regs(2),
audio_regs(3),
audio_regs(4),
audio_regs(5)
};
#define DCE120_AUD_COMMON_MASK_SH_LIST(mask_sh)\
SF(AZF0ENDPOINT0_AZALIA_F0_CODEC_ENDPOINT_INDEX, AZALIA_ENDPOINT_REG_INDEX, mask_sh),\
SF(AZF0ENDPOINT0_AZALIA_F0_CODEC_ENDPOINT_DATA, AZALIA_ENDPOINT_REG_DATA, mask_sh),\
AUD_COMMON_MASK_SH_LIST_BASE(mask_sh)
static const struct dce_audio_shift audio_shift = {
DCE120_AUD_COMMON_MASK_SH_LIST(__SHIFT)
};
static const struct dce_audio_mask audio_mask = {
DCE120_AUD_COMMON_MASK_SH_LIST(_MASK)
};
#define clk_src_regs(index, id)\
[index] = {\
CS_COMMON_REG_LIST_DCE_112(id),\
}
static const struct dce110_clk_src_regs clk_src_regs[] = {
clk_src_regs(0, A),
clk_src_regs(1, B),
clk_src_regs(2, C),
clk_src_regs(3, D),
clk_src_regs(4, E),
clk_src_regs(5, F)
};
static const struct dce110_clk_src_shift cs_shift = {
CS_COMMON_MASK_SH_LIST_DCE_112(__SHIFT)
};
static const struct dce110_clk_src_mask cs_mask = {
CS_COMMON_MASK_SH_LIST_DCE_112(_MASK)
};
struct output_pixel_processor *dce120_opp_create(
struct dc_context *ctx,
uint32_t inst)
{
struct dce110_opp *opp =
kzalloc(sizeof(struct dce110_opp), GFP_KERNEL);
if (!opp)
return NULL;
dce110_opp_construct(opp,
ctx, inst, &opp_regs[inst], &opp_shift, &opp_mask);
return &opp->base;
}
struct dce_aux *dce120_aux_engine_create(
struct dc_context *ctx,
uint32_t inst)
{
struct aux_engine_dce110 *aux_engine =
kzalloc(sizeof(struct aux_engine_dce110), GFP_KERNEL);
if (!aux_engine)
return NULL;
dce110_aux_engine_construct(aux_engine, ctx, inst,
SW_AUX_TIMEOUT_PERIOD_MULTIPLIER * AUX_TIMEOUT_PERIOD,
&aux_engine_regs[inst]);
return &aux_engine->base;
}
#define i2c_inst_regs(id) { I2C_HW_ENGINE_COMMON_REG_LIST(id) }
static const struct dce_i2c_registers i2c_hw_regs[] = {
i2c_inst_regs(1),
i2c_inst_regs(2),
i2c_inst_regs(3),
i2c_inst_regs(4),
i2c_inst_regs(5),
i2c_inst_regs(6),
};
static const struct dce_i2c_shift i2c_shifts = {
I2C_COMMON_MASK_SH_LIST_DCE110(__SHIFT)
};
static const struct dce_i2c_mask i2c_masks = {
I2C_COMMON_MASK_SH_LIST_DCE110(_MASK)
};
struct dce_i2c_hw *dce120_i2c_hw_create(
struct dc_context *ctx,
uint32_t inst)
{
struct dce_i2c_hw *dce_i2c_hw =
kzalloc(sizeof(struct dce_i2c_hw), GFP_KERNEL);
if (!dce_i2c_hw)
return NULL;
dce112_i2c_hw_construct(dce_i2c_hw, ctx, inst,
&i2c_hw_regs[inst], &i2c_shifts, &i2c_masks);
return dce_i2c_hw;
}
static const struct bios_registers bios_regs = {
.BIOS_SCRATCH_3 = mmBIOS_SCRATCH_3 + NBIO_BASE(mmBIOS_SCRATCH_3_BASE_IDX),
.BIOS_SCRATCH_6 = mmBIOS_SCRATCH_6 + NBIO_BASE(mmBIOS_SCRATCH_6_BASE_IDX)
};
static const struct resource_caps res_cap = {
.num_timing_generator = 6,
.num_audio = 7,
.num_stream_encoder = 6,
.num_pll = 6,
.num_ddc = 6,
};
static const struct dc_plane_cap plane_cap = {
.type = DC_PLANE_TYPE_DCE_RGB,
.pixel_format_support = {
.argb8888 = true,
.nv12 = false,
.fp16 = false
},
.max_upscale_factor = {
.argb8888 = 16000,
.nv12 = 1,
.fp16 = 1
},
.max_downscale_factor = {
.argb8888 = 250,
.nv12 = 1,
.fp16 = 1
}
};
static const struct dc_debug_options debug_defaults = {
.disable_clock_gate = true,
};
static struct clock_source *dce120_clock_source_create(
struct dc_context *ctx,
struct dc_bios *bios,
enum clock_source_id id,
const struct dce110_clk_src_regs *regs,
bool dp_clk_src)
{
struct dce110_clk_src *clk_src =
kzalloc(sizeof(*clk_src), GFP_KERNEL);
if (!clk_src)
return NULL;
if (dce112_clk_src_construct(clk_src, ctx, bios, id,
regs, &cs_shift, &cs_mask)) {
clk_src->base.dp_clk_src = dp_clk_src;
return &clk_src->base;
}
BREAK_TO_DEBUGGER();
return NULL;
}
static void dce120_clock_source_destroy(struct clock_source **clk_src)
{
kfree(TO_DCE110_CLK_SRC(*clk_src));
*clk_src = NULL;
}
static bool dce120_hw_sequencer_create(struct dc *dc)
{
/* All registers used by dce11.2 match those in dce11 in offset and
* structure
*/
dce120_hw_sequencer_construct(dc);
/*TODO Move to separate file and Override what is needed */
return true;
}
static struct timing_generator *dce120_timing_generator_create(
struct dc_context *ctx,
uint32_t instance,
const struct dce110_timing_generator_offsets *offsets)
{
struct dce110_timing_generator *tg110 =
kzalloc(sizeof(struct dce110_timing_generator), GFP_KERNEL);
if (!tg110)
return NULL;
dce120_timing_generator_construct(tg110, ctx, instance, offsets);
return &tg110->base;
}
static void dce120_transform_destroy(struct transform **xfm)
{
kfree(TO_DCE_TRANSFORM(*xfm));
*xfm = NULL;
}
static void destruct(struct dce110_resource_pool *pool)
{
unsigned int i;
for (i = 0; i < pool->base.pipe_count; i++) {
if (pool->base.opps[i] != NULL)
dce110_opp_destroy(&pool->base.opps[i]);
if (pool->base.transforms[i] != NULL)
dce120_transform_destroy(&pool->base.transforms[i]);
if (pool->base.ipps[i] != NULL)
dce_ipp_destroy(&pool->base.ipps[i]);
if (pool->base.mis[i] != NULL) {
kfree(TO_DCE_MEM_INPUT(pool->base.mis[i]));
pool->base.mis[i] = NULL;
}
if (pool->base.irqs != NULL) {
dal_irq_service_destroy(&pool->base.irqs);
}
if (pool->base.timing_generators[i] != NULL) {
kfree(DCE110TG_FROM_TG(pool->base.timing_generators[i]));
pool->base.timing_generators[i] = NULL;
}
}
for (i = 0; i < pool->base.res_cap->num_ddc; i++) {
if (pool->base.engines[i] != NULL)
dce110_engine_destroy(&pool->base.engines[i]);
if (pool->base.hw_i2cs[i] != NULL) {
kfree(pool->base.hw_i2cs[i]);
pool->base.hw_i2cs[i] = NULL;
}
if (pool->base.sw_i2cs[i] != NULL) {
kfree(pool->base.sw_i2cs[i]);
pool->base.sw_i2cs[i] = NULL;
}
}
for (i = 0; i < pool->base.audio_count; i++) {
if (pool->base.audios[i])
dce_aud_destroy(&pool->base.audios[i]);
}
for (i = 0; i < pool->base.stream_enc_count; i++) {
if (pool->base.stream_enc[i] != NULL)
kfree(DCE110STRENC_FROM_STRENC(pool->base.stream_enc[i]));
}
for (i = 0; i < pool->base.clk_src_count; i++) {
if (pool->base.clock_sources[i] != NULL)
dce120_clock_source_destroy(
&pool->base.clock_sources[i]);
}
if (pool->base.dp_clock_source != NULL)
dce120_clock_source_destroy(&pool->base.dp_clock_source);
if (pool->base.abm != NULL)
dce_abm_destroy(&pool->base.abm);
if (pool->base.dmcu != NULL)
dce_dmcu_destroy(&pool->base.dmcu);
}
static void read_dce_straps(
struct dc_context *ctx,
struct resource_straps *straps)
{
uint32_t reg_val = dm_read_reg_soc15(ctx, mmCC_DC_MISC_STRAPS, 0);
straps->audio_stream_number = get_reg_field_value(reg_val,
CC_DC_MISC_STRAPS,
AUDIO_STREAM_NUMBER);
straps->hdmi_disable = get_reg_field_value(reg_val,
CC_DC_MISC_STRAPS,
HDMI_DISABLE);
reg_val = dm_read_reg_soc15(ctx, mmDC_PINSTRAPS, 0);
straps->dc_pinstraps_audio = get_reg_field_value(reg_val,
DC_PINSTRAPS,
DC_PINSTRAPS_AUDIO);
}
static struct audio *create_audio(
struct dc_context *ctx, unsigned int inst)
{
return dce_audio_create(ctx, inst,
&audio_regs[inst], &audio_shift, &audio_mask);
}
static const struct encoder_feature_support link_enc_feature = {
.max_hdmi_deep_color = COLOR_DEPTH_121212,
.max_hdmi_pixel_clock = 600000,
.hdmi_ycbcr420_supported = true,
.dp_ycbcr420_supported = false,
.flags.bits.IS_HBR2_CAPABLE = true,
.flags.bits.IS_HBR3_CAPABLE = true,
.flags.bits.IS_TPS3_CAPABLE = true,
.flags.bits.IS_TPS4_CAPABLE = true,
};
static struct link_encoder *dce120_link_encoder_create(
const struct encoder_init_data *enc_init_data)
{
struct dce110_link_encoder *enc110 =
kzalloc(sizeof(struct dce110_link_encoder), GFP_KERNEL);
if (!enc110)
return NULL;
dce110_link_encoder_construct(enc110,
enc_init_data,
&link_enc_feature,
&link_enc_regs[enc_init_data->transmitter],
&link_enc_aux_regs[enc_init_data->channel - 1],
&link_enc_hpd_regs[enc_init_data->hpd_source]);
return &enc110->base;
}
static struct input_pixel_processor *dce120_ipp_create(
struct dc_context *ctx, uint32_t inst)
{
struct dce_ipp *ipp = kzalloc(sizeof(struct dce_ipp), GFP_KERNEL);
if (!ipp) {
BREAK_TO_DEBUGGER();
return NULL;
}
dce_ipp_construct(ipp, ctx, inst,
&ipp_regs[inst], &ipp_shift, &ipp_mask);
return &ipp->base;
}
static struct stream_encoder *dce120_stream_encoder_create(
enum engine_id eng_id,
struct dc_context *ctx)
{
struct dce110_stream_encoder *enc110 =
kzalloc(sizeof(struct dce110_stream_encoder), GFP_KERNEL);
if (!enc110)
return NULL;
dce110_stream_encoder_construct(enc110, ctx, ctx->dc_bios, eng_id,
&stream_enc_regs[eng_id],
&se_shift, &se_mask);
return &enc110->base;
}
#define SRII(reg_name, block, id)\
.reg_name[id] = BASE(mm ## block ## id ## _ ## reg_name ## _BASE_IDX) + \
mm ## block ## id ## _ ## reg_name
static const struct dce_hwseq_registers hwseq_reg = {
HWSEQ_DCE120_REG_LIST()
};
static const struct dce_hwseq_shift hwseq_shift = {
HWSEQ_DCE12_MASK_SH_LIST(__SHIFT)
};
static const struct dce_hwseq_mask hwseq_mask = {
HWSEQ_DCE12_MASK_SH_LIST(_MASK)
};
/* HWSEQ regs for VG20 */
static const struct dce_hwseq_registers dce121_hwseq_reg = {
HWSEQ_VG20_REG_LIST()
};
static const struct dce_hwseq_shift dce121_hwseq_shift = {
HWSEQ_VG20_MASK_SH_LIST(__SHIFT)
};
static const struct dce_hwseq_mask dce121_hwseq_mask = {
HWSEQ_VG20_MASK_SH_LIST(_MASK)
};
static struct dce_hwseq *dce120_hwseq_create(
struct dc_context *ctx)
{
struct dce_hwseq *hws = kzalloc(sizeof(struct dce_hwseq), GFP_KERNEL);
if (hws) {
hws->ctx = ctx;
hws->regs = &hwseq_reg;
hws->shifts = &hwseq_shift;
hws->masks = &hwseq_mask;
}
return hws;
}
static struct dce_hwseq *dce121_hwseq_create(
struct dc_context *ctx)
{
struct dce_hwseq *hws = kzalloc(sizeof(struct dce_hwseq), GFP_KERNEL);
if (hws) {
hws->ctx = ctx;
hws->regs = &dce121_hwseq_reg;
hws->shifts = &dce121_hwseq_shift;
hws->masks = &dce121_hwseq_mask;
}
return hws;
}
static const struct resource_create_funcs res_create_funcs = {
.read_dce_straps = read_dce_straps,
.create_audio = create_audio,
.create_stream_encoder = dce120_stream_encoder_create,
.create_hwseq = dce120_hwseq_create,
};
static const struct resource_create_funcs dce121_res_create_funcs = {
.read_dce_straps = read_dce_straps,
.create_audio = create_audio,
.create_stream_encoder = dce120_stream_encoder_create,
.create_hwseq = dce121_hwseq_create,
};
#define mi_inst_regs(id) { MI_DCE12_REG_LIST(id) }
static const struct dce_mem_input_registers mi_regs[] = {
mi_inst_regs(0),
mi_inst_regs(1),
mi_inst_regs(2),
mi_inst_regs(3),
mi_inst_regs(4),
mi_inst_regs(5),
};
static const struct dce_mem_input_shift mi_shifts = {
MI_DCE12_MASK_SH_LIST(__SHIFT)
};
static const struct dce_mem_input_mask mi_masks = {
MI_DCE12_MASK_SH_LIST(_MASK)
};
static struct mem_input *dce120_mem_input_create(
struct dc_context *ctx,
uint32_t inst)
{
struct dce_mem_input *dce_mi = kzalloc(sizeof(struct dce_mem_input),
GFP_KERNEL);
if (!dce_mi) {
BREAK_TO_DEBUGGER();
return NULL;
}
dce120_mem_input_construct(dce_mi, ctx, inst, &mi_regs[inst], &mi_shifts, &mi_masks);
return &dce_mi->base;
}
static struct transform *dce120_transform_create(
struct dc_context *ctx,
uint32_t inst)
{
struct dce_transform *transform =
kzalloc(sizeof(struct dce_transform), GFP_KERNEL);
if (!transform)
return NULL;
dce_transform_construct(transform, ctx, inst,
&xfm_regs[inst], &xfm_shift, &xfm_mask);
transform->lb_memory_size = 0x1404; /*5124*/
return &transform->base;
}
static void dce120_destroy_resource_pool(struct resource_pool **pool)
{
struct dce110_resource_pool *dce110_pool = TO_DCE110_RES_POOL(*pool);
destruct(dce110_pool);
kfree(dce110_pool);
*pool = NULL;
}
static const struct resource_funcs dce120_res_pool_funcs = {
.destroy = dce120_destroy_resource_pool,
.link_enc_create = dce120_link_encoder_create,
.validate_bandwidth = dce112_validate_bandwidth,
.validate_plane = dce100_validate_plane,
.add_stream_to_ctx = dce112_add_stream_to_ctx,
.find_first_free_match_stream_enc_for_link = dce110_find_first_free_match_stream_enc_for_link
};
static void bw_calcs_data_update_from_pplib(struct dc *dc)
{
struct dm_pp_clock_levels_with_latency eng_clks = {0};
struct dm_pp_clock_levels_with_latency mem_clks = {0};
struct dm_pp_wm_sets_with_clock_ranges clk_ranges = {0};
int i;
unsigned int clk;
unsigned int latency;
/*original logic in dal3*/
int memory_type_multiplier = MEMORY_TYPE_MULTIPLIER_CZ;
/*do system clock*/
if (!dm_pp_get_clock_levels_by_type_with_latency(
dc->ctx,
DM_PP_CLOCK_TYPE_ENGINE_CLK,
&eng_clks) || eng_clks.num_levels == 0) {
eng_clks.num_levels = 8;
clk = 300000;
for (i = 0; i < eng_clks.num_levels; i++) {
eng_clks.data[i].clocks_in_khz = clk;
clk += 100000;
}
}
/* convert all the clock fro kHz to fix point mHz TODO: wloop data */
dc->bw_vbios->high_sclk = bw_frc_to_fixed(
eng_clks.data[eng_clks.num_levels-1].clocks_in_khz, 1000);
dc->bw_vbios->mid1_sclk = bw_frc_to_fixed(
eng_clks.data[eng_clks.num_levels/8].clocks_in_khz, 1000);
dc->bw_vbios->mid2_sclk = bw_frc_to_fixed(
eng_clks.data[eng_clks.num_levels*2/8].clocks_in_khz, 1000);
dc->bw_vbios->mid3_sclk = bw_frc_to_fixed(
eng_clks.data[eng_clks.num_levels*3/8].clocks_in_khz, 1000);
dc->bw_vbios->mid4_sclk = bw_frc_to_fixed(
eng_clks.data[eng_clks.num_levels*4/8].clocks_in_khz, 1000);
dc->bw_vbios->mid5_sclk = bw_frc_to_fixed(
eng_clks.data[eng_clks.num_levels*5/8].clocks_in_khz, 1000);
dc->bw_vbios->mid6_sclk = bw_frc_to_fixed(
eng_clks.data[eng_clks.num_levels*6/8].clocks_in_khz, 1000);
dc->bw_vbios->low_sclk = bw_frc_to_fixed(
eng_clks.data[0].clocks_in_khz, 1000);
/*do memory clock*/
if (!dm_pp_get_clock_levels_by_type_with_latency(
dc->ctx,
DM_PP_CLOCK_TYPE_MEMORY_CLK,
&mem_clks) || mem_clks.num_levels == 0) {
mem_clks.num_levels = 3;
clk = 250000;
latency = 45;
for (i = 0; i < eng_clks.num_levels; i++) {
mem_clks.data[i].clocks_in_khz = clk;
mem_clks.data[i].latency_in_us = latency;
clk += 500000;
latency -= 5;
}
}
/* we don't need to call PPLIB for validation clock since they
* also give us the highest sclk and highest mclk (UMA clock).
* ALSO always convert UMA clock (from PPLIB) to YCLK (HW formula):
* YCLK = UMACLK*m_memoryTypeMultiplier
*/
if (dc->bw_vbios->memory_type == bw_def_hbm)
memory_type_multiplier = MEMORY_TYPE_HBM;
dc->bw_vbios->low_yclk = bw_frc_to_fixed(
mem_clks.data[0].clocks_in_khz * memory_type_multiplier, 1000);
dc->bw_vbios->mid_yclk = bw_frc_to_fixed(
mem_clks.data[mem_clks.num_levels>>1].clocks_in_khz * memory_type_multiplier,
1000);
dc->bw_vbios->high_yclk = bw_frc_to_fixed(
mem_clks.data[mem_clks.num_levels-1].clocks_in_khz * memory_type_multiplier,
1000);
/* Now notify PPLib/SMU about which Watermarks sets they should select
* depending on DPM state they are in. And update BW MGR GFX Engine and
* Memory clock member variables for Watermarks calculations for each
* Watermark Set
*/
clk_ranges.num_wm_sets = 4;
clk_ranges.wm_clk_ranges[0].wm_set_id = WM_SET_A;
clk_ranges.wm_clk_ranges[0].wm_min_eng_clk_in_khz =
eng_clks.data[0].clocks_in_khz;
clk_ranges.wm_clk_ranges[0].wm_max_eng_clk_in_khz =
eng_clks.data[eng_clks.num_levels*3/8].clocks_in_khz - 1;
clk_ranges.wm_clk_ranges[0].wm_min_mem_clk_in_khz =
mem_clks.data[0].clocks_in_khz;
clk_ranges.wm_clk_ranges[0].wm_max_mem_clk_in_khz =
mem_clks.data[mem_clks.num_levels>>1].clocks_in_khz - 1;
clk_ranges.wm_clk_ranges[1].wm_set_id = WM_SET_B;
clk_ranges.wm_clk_ranges[1].wm_min_eng_clk_in_khz =
eng_clks.data[eng_clks.num_levels*3/8].clocks_in_khz;
/* 5 GHz instead of data[7].clockInKHz to cover Overdrive */
clk_ranges.wm_clk_ranges[1].wm_max_eng_clk_in_khz = 5000000;
clk_ranges.wm_clk_ranges[1].wm_min_mem_clk_in_khz =
mem_clks.data[0].clocks_in_khz;
clk_ranges.wm_clk_ranges[1].wm_max_mem_clk_in_khz =
mem_clks.data[mem_clks.num_levels>>1].clocks_in_khz - 1;
clk_ranges.wm_clk_ranges[2].wm_set_id = WM_SET_C;
clk_ranges.wm_clk_ranges[2].wm_min_eng_clk_in_khz =
eng_clks.data[0].clocks_in_khz;
clk_ranges.wm_clk_ranges[2].wm_max_eng_clk_in_khz =
eng_clks.data[eng_clks.num_levels*3/8].clocks_in_khz - 1;
clk_ranges.wm_clk_ranges[2].wm_min_mem_clk_in_khz =
mem_clks.data[mem_clks.num_levels>>1].clocks_in_khz;
/* 5 GHz instead of data[2].clockInKHz to cover Overdrive */
clk_ranges.wm_clk_ranges[2].wm_max_mem_clk_in_khz = 5000000;
clk_ranges.wm_clk_ranges[3].wm_set_id = WM_SET_D;
clk_ranges.wm_clk_ranges[3].wm_min_eng_clk_in_khz =
eng_clks.data[eng_clks.num_levels*3/8].clocks_in_khz;
/* 5 GHz instead of data[7].clockInKHz to cover Overdrive */
clk_ranges.wm_clk_ranges[3].wm_max_eng_clk_in_khz = 5000000;
clk_ranges.wm_clk_ranges[3].wm_min_mem_clk_in_khz =
mem_clks.data[mem_clks.num_levels>>1].clocks_in_khz;
/* 5 GHz instead of data[2].clockInKHz to cover Overdrive */
clk_ranges.wm_clk_ranges[3].wm_max_mem_clk_in_khz = 5000000;
/* Notify PP Lib/SMU which Watermarks to use for which clock ranges */
dm_pp_notify_wm_clock_changes(dc->ctx, &clk_ranges);
}
static uint32_t read_pipe_fuses(struct dc_context *ctx)
{
uint32_t value = dm_read_reg_soc15(ctx, mmCC_DC_PIPE_DIS, 0);
/* VG20 support max 6 pipes */
value = value & 0x3f;
return value;
}
static bool construct(
uint8_t num_virtual_links,
struct dc *dc,
struct dce110_resource_pool *pool)
{
unsigned int i;
int j;
struct dc_context *ctx = dc->ctx;
struct irq_service_init_data irq_init_data;
static const struct resource_create_funcs *res_funcs;
bool is_vg20 = ASICREV_IS_VEGA20_P(ctx->asic_id.hw_internal_rev);
uint32_t pipe_fuses;
ctx->dc_bios->regs = &bios_regs;
pool->base.res_cap = &res_cap;
pool->base.funcs = &dce120_res_pool_funcs;
/* TODO: Fill more data from GreenlandAsicCapability.cpp */
pool->base.pipe_count = res_cap.num_timing_generator;
pool->base.timing_generator_count = pool->base.res_cap->num_timing_generator;
pool->base.underlay_pipe_index = NO_UNDERLAY_PIPE;
dc->caps.max_downscale_ratio = 200;
dc->caps.i2c_speed_in_khz = 100;
dc->caps.max_cursor_size = 128;
dc->caps.dual_link_dvi = true;
dc->caps.psp_setup_panel_mode = true;
dc->debug = debug_defaults;
/*************************************************
* Create resources *
*************************************************/
pool->base.clock_sources[DCE120_CLK_SRC_PLL0] =
dce120_clock_source_create(ctx, ctx->dc_bios,
CLOCK_SOURCE_COMBO_PHY_PLL0,
&clk_src_regs[0], false);
pool->base.clock_sources[DCE120_CLK_SRC_PLL1] =
dce120_clock_source_create(ctx, ctx->dc_bios,
CLOCK_SOURCE_COMBO_PHY_PLL1,
&clk_src_regs[1], false);
pool->base.clock_sources[DCE120_CLK_SRC_PLL2] =
dce120_clock_source_create(ctx, ctx->dc_bios,
CLOCK_SOURCE_COMBO_PHY_PLL2,
&clk_src_regs[2], false);
pool->base.clock_sources[DCE120_CLK_SRC_PLL3] =
dce120_clock_source_create(ctx, ctx->dc_bios,
CLOCK_SOURCE_COMBO_PHY_PLL3,
&clk_src_regs[3], false);
pool->base.clock_sources[DCE120_CLK_SRC_PLL4] =
dce120_clock_source_create(ctx, ctx->dc_bios,
CLOCK_SOURCE_COMBO_PHY_PLL4,
&clk_src_regs[4], false);
pool->base.clock_sources[DCE120_CLK_SRC_PLL5] =
dce120_clock_source_create(ctx, ctx->dc_bios,
CLOCK_SOURCE_COMBO_PHY_PLL5,
&clk_src_regs[5], false);
pool->base.clk_src_count = DCE120_CLK_SRC_TOTAL;
pool->base.dp_clock_source =
dce120_clock_source_create(ctx, ctx->dc_bios,
CLOCK_SOURCE_ID_DP_DTO,
&clk_src_regs[0], true);
for (i = 0; i < pool->base.clk_src_count; i++) {
if (pool->base.clock_sources[i] == NULL) {
dm_error("DC: failed to create clock sources!\n");
BREAK_TO_DEBUGGER();
goto clk_src_create_fail;
}
}
pool->base.dmcu = dce_dmcu_create(ctx,
&dmcu_regs,
&dmcu_shift,
&dmcu_mask);
if (pool->base.dmcu == NULL) {
dm_error("DC: failed to create dmcu!\n");
BREAK_TO_DEBUGGER();
goto res_create_fail;
}
pool->base.abm = dce_abm_create(ctx,
&abm_regs,
&abm_shift,
&abm_mask);
if (pool->base.abm == NULL) {
dm_error("DC: failed to create abm!\n");
BREAK_TO_DEBUGGER();
goto res_create_fail;
}
irq_init_data.ctx = dc->ctx;
pool->base.irqs = dal_irq_service_dce120_create(&irq_init_data);
if (!pool->base.irqs)
goto irqs_create_fail;
/* VG20: Pipe harvesting enabled, retrieve valid pipe fuses */
if (is_vg20)
pipe_fuses = read_pipe_fuses(ctx);
/* index to valid pipe resource */
j = 0;
for (i = 0; i < pool->base.pipe_count; i++) {
if (is_vg20) {
if ((pipe_fuses & (1 << i)) != 0) {
dm_error("DC: skip invalid pipe %d!\n", i);
continue;
}
}
pool->base.timing_generators[j] =
dce120_timing_generator_create(
ctx,
i,
&dce120_tg_offsets[i]);
if (pool->base.timing_generators[j] == NULL) {
BREAK_TO_DEBUGGER();
dm_error("DC: failed to create tg!\n");
goto controller_create_fail;
}
pool->base.mis[j] = dce120_mem_input_create(ctx, i);
if (pool->base.mis[j] == NULL) {
BREAK_TO_DEBUGGER();
dm_error(
"DC: failed to create memory input!\n");
goto controller_create_fail;
}
pool->base.ipps[j] = dce120_ipp_create(ctx, i);
if (pool->base.ipps[i] == NULL) {
BREAK_TO_DEBUGGER();
dm_error(
"DC: failed to create input pixel processor!\n");
goto controller_create_fail;
}
pool->base.transforms[j] = dce120_transform_create(ctx, i);
if (pool->base.transforms[i] == NULL) {
BREAK_TO_DEBUGGER();
dm_error(
"DC: failed to create transform!\n");
goto res_create_fail;
}
pool->base.opps[j] = dce120_opp_create(
ctx,
i);
if (pool->base.opps[j] == NULL) {
BREAK_TO_DEBUGGER();
dm_error(
"DC: failed to create output pixel processor!\n");
}
/* check next valid pipe */
j++;
}
for (i = 0; i < pool->base.res_cap->num_ddc; i++) {
pool->base.engines[i] = dce120_aux_engine_create(ctx, i);
if (pool->base.engines[i] == NULL) {
BREAK_TO_DEBUGGER();
dm_error(
"DC:failed to create aux engine!!\n");
goto res_create_fail;
}
pool->base.hw_i2cs[i] = dce120_i2c_hw_create(ctx, i);
if (pool->base.hw_i2cs[i] == NULL) {
BREAK_TO_DEBUGGER();
dm_error(
"DC:failed to create i2c engine!!\n");
goto res_create_fail;
}
pool->base.sw_i2cs[i] = NULL;
}
/* valid pipe num */
pool->base.pipe_count = j;
pool->base.timing_generator_count = j;
if (is_vg20)
res_funcs = &dce121_res_create_funcs;
else
res_funcs = &res_create_funcs;
if (!resource_construct(num_virtual_links, dc, &pool->base, res_funcs))
goto res_create_fail;
/* Create hardware sequencer */
if (!dce120_hw_sequencer_create(dc))
goto controller_create_fail;
dc->caps.max_planes = pool->base.pipe_count;
for (i = 0; i < dc->caps.max_planes; ++i)
dc->caps.planes[i] = plane_cap;
bw_calcs_init(dc->bw_dceip, dc->bw_vbios, dc->ctx->asic_id);
bw_calcs_data_update_from_pplib(dc);
return true;
irqs_create_fail:
controller_create_fail:
clk_src_create_fail:
res_create_fail:
destruct(pool);
return false;
}
struct resource_pool *dce120_create_resource_pool(
uint8_t num_virtual_links,
struct dc *dc)
{
struct dce110_resource_pool *pool =
kzalloc(sizeof(struct dce110_resource_pool), GFP_KERNEL);
if (!pool)
return NULL;
if (construct(num_virtual_links, dc, pool))
return &pool->base;
kfree(pool);
BREAK_TO_DEBUGGER();
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-400/c/bad_1273_3 |
crossvul-cpp_data_good_1362_0 | /**
* @file resolve.c
* @author Michal Vasko <mvasko@cesnet.cz>
* @brief libyang resolve functions
*
* Copyright (c) 2015 - 2018 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "libyang.h"
#include "resolve.h"
#include "common.h"
#include "xpath.h"
#include "parser.h"
#include "parser_yang.h"
#include "xml_internal.h"
#include "hash_table.h"
#include "tree_internal.h"
#include "extensions.h"
#include "validation.h"
/* internal parsed predicate structure */
struct parsed_pred {
const struct lys_node *schema;
int len;
struct {
const char *mod_name;
int mod_name_len;
const char *name;
int nam_len;
const char *value;
int val_len;
} *pred;
};
int
parse_range_dec64(const char **str_num, uint8_t dig, int64_t *num)
{
const char *ptr;
int minus = 0;
int64_t ret = 0, prev_ret;
int8_t str_exp, str_dig = -1, trailing_zeros = 0;
ptr = *str_num;
if (ptr[0] == '-') {
minus = 1;
++ptr;
} else if (ptr[0] == '+') {
++ptr;
}
if (!isdigit(ptr[0])) {
/* there must be at least one */
return 1;
}
for (str_exp = 0; isdigit(ptr[0]) || ((ptr[0] == '.') && (str_dig < 0)); ++ptr) {
if (str_exp > 18) {
return 1;
}
if (ptr[0] == '.') {
if (ptr[1] == '.') {
/* it's the next interval */
break;
}
++str_dig;
} else {
prev_ret = ret;
if (minus) {
ret = ret * 10 - (ptr[0] - '0');
if (ret > prev_ret) {
return 1;
}
} else {
ret = ret * 10 + (ptr[0] - '0');
if (ret < prev_ret) {
return 1;
}
}
if (str_dig > -1) {
++str_dig;
if (ptr[0] == '0') {
/* possibly trailing zero */
trailing_zeros++;
} else {
trailing_zeros = 0;
}
}
++str_exp;
}
}
if (str_dig == 0) {
/* no digits after '.' */
return 1;
} else if (str_dig == -1) {
/* there are 0 numbers after the floating point */
str_dig = 0;
}
/* remove trailing zeros */
if (trailing_zeros) {
str_dig -= trailing_zeros;
str_exp -= trailing_zeros;
ret = ret / dec_pow(trailing_zeros);
}
/* it's parsed, now adjust the number based on fraction-digits, if needed */
if (str_dig < dig) {
if ((str_exp - 1) + (dig - str_dig) > 18) {
return 1;
}
prev_ret = ret;
ret *= dec_pow(dig - str_dig);
if ((minus && (ret > prev_ret)) || (!minus && (ret < prev_ret))) {
return 1;
}
}
if (str_dig > dig) {
return 1;
}
*str_num = ptr;
*num = ret;
return 0;
}
/**
* @brief Parse an identifier.
*
* ;; An identifier MUST NOT start with (('X'|'x') ('M'|'m') ('L'|'l'))
* identifier = (ALPHA / "_")
* *(ALPHA / DIGIT / "_" / "-" / ".")
*
* @param[in] id Identifier to use.
*
* @return Number of characters successfully parsed.
*/
unsigned int
parse_identifier(const char *id)
{
unsigned int parsed = 0;
assert(id);
if (!isalpha(id[0]) && (id[0] != '_')) {
return -parsed;
}
++parsed;
++id;
while (isalnum(id[0]) || (id[0] == '_') || (id[0] == '-') || (id[0] == '.')) {
++parsed;
++id;
}
return parsed;
}
/**
* @brief Parse a node-identifier.
*
* node-identifier = [module-name ":"] identifier
*
* @param[in] id Identifier to use.
* @param[out] mod_name Points to the module name, NULL if there is not any.
* @param[out] mod_name_len Length of the module name, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] all_desc Whether the path starts with '/', only supported in extended paths.
* @param[in] extended Whether to accept an extended path (support for [prefix:]*, /[prefix:]*, /[prefix:]., prefix:#identifier).
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_node_identifier(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len,
int *all_desc, int extended)
{
int parsed = 0, ret, all_desc_local = 0, first_id_len;
const char *first_id;
assert(id);
assert((mod_name && mod_name_len) || (!mod_name && !mod_name_len));
assert((name && nam_len) || (!name && !nam_len));
if (mod_name) {
*mod_name = NULL;
*mod_name_len = 0;
}
if (name) {
*name = NULL;
*nam_len = 0;
}
if (extended) {
/* try to parse only the extended expressions */
if (id[parsed] == '/') {
if (all_desc) {
*all_desc = 1;
}
all_desc_local = 1;
} else {
if (all_desc) {
*all_desc = 0;
}
}
/* is there a prefix? */
ret = parse_identifier(id + all_desc_local);
if (ret > 0) {
if (id[all_desc_local + ret] != ':') {
/* this is not a prefix, so not an extended id */
goto standard_id;
}
if (mod_name) {
*mod_name = id + all_desc_local;
*mod_name_len = ret;
}
/* "/" and ":" */
ret += all_desc_local + 1;
} else {
ret = all_desc_local;
}
/* parse either "*" or "." */
if (*(id + ret) == '*') {
if (name) {
*name = id + ret;
*nam_len = 1;
}
++ret;
return ret;
} else if (*(id + ret) == '.') {
if (!all_desc_local) {
/* /. is redundant expression, we do not accept it */
return -ret;
}
if (name) {
*name = id + ret;
*nam_len = 1;
}
++ret;
return ret;
} else if (*(id + ret) == '#') {
if (all_desc_local || !ret) {
/* no prefix */
return 0;
}
parsed = ret + 1;
if ((ret = parse_identifier(id + parsed)) < 1) {
return -parsed + ret;
}
*name = id + parsed - 1;
*nam_len = ret + 1;
return parsed + ret;
}
/* else a standard id, parse it all again */
}
standard_id:
if ((ret = parse_identifier(id)) < 1) {
return ret;
}
first_id = id;
first_id_len = ret;
parsed += ret;
id += ret;
/* there is prefix */
if (id[0] == ':') {
++parsed;
++id;
/* there isn't */
} else {
if (name) {
*name = first_id;
*nam_len = first_id_len;
}
return parsed;
}
/* identifier (node name) */
if ((ret = parse_identifier(id)) < 1) {
return -parsed + ret;
}
if (mod_name) {
*mod_name = first_id;
*mod_name_len = first_id_len;
}
if (name) {
*name = id;
*nam_len = ret;
}
return parsed + ret;
}
/**
* @brief Parse a path-predicate (leafref).
*
* path-predicate = "[" *WSP path-equality-expr *WSP "]"
* path-equality-expr = node-identifier *WSP "=" *WSP path-key-expr
*
* @param[in] id Identifier to use.
* @param[out] prefix Points to the prefix, NULL if there is not any.
* @param[out] pref_len Length of the prefix, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] path_key_expr Points to the path-key-expr.
* @param[out] pke_len Length of the path-key-expr.
* @param[out] has_predicate Flag to mark whether there is another predicate following.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_path_predicate(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len,
const char **path_key_expr, int *pke_len, int *has_predicate)
{
const char *ptr;
int parsed = 0, ret;
assert(id);
if (prefix) {
*prefix = NULL;
}
if (pref_len) {
*pref_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (path_key_expr) {
*path_key_expr = NULL;
}
if (pke_len) {
*pke_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '[') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) {
return -parsed+ret;
}
parsed += ret;
id += ret;
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '=') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
if ((ptr = strchr(id, ']')) == NULL) {
return -parsed;
}
--ptr;
while (isspace(ptr[0])) {
--ptr;
}
++ptr;
ret = ptr-id;
if (path_key_expr) {
*path_key_expr = id;
}
if (pke_len) {
*pke_len = ret;
}
parsed += ret;
id += ret;
while (isspace(id[0])) {
++parsed;
++id;
}
assert(id[0] == ']');
if (id[1] == '[') {
*has_predicate = 1;
}
return parsed+1;
}
/**
* @brief Parse a path-key-expr (leafref). First call parses "current()", all
* the ".." and the first node-identifier, other calls parse a single
* node-identifier each.
*
* path-key-expr = current-function-invocation *WSP "/" *WSP
* rel-path-keyexpr
* rel-path-keyexpr = 1*(".." *WSP "/" *WSP)
* *(node-identifier *WSP "/" *WSP)
* node-identifier
*
* @param[in] id Identifier to use.
* @param[out] prefix Points to the prefix, NULL if there is not any.
* @param[out] pref_len Length of the prefix, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] parent_times Number of ".." in the path. Must be 0 on the first call,
* must not be changed between consecutive calls.
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_path_key_expr(const char *id, const char **prefix, int *pref_len, const char **name, int *nam_len,
int *parent_times)
{
int parsed = 0, ret, par_times = 0;
assert(id);
assert(parent_times);
if (prefix) {
*prefix = NULL;
}
if (pref_len) {
*pref_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (!*parent_times) {
/* current-function-invocation *WSP "/" *WSP rel-path-keyexpr */
if (strncmp(id, "current()", 9)) {
return -parsed;
}
parsed += 9;
id += 9;
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* rel-path-keyexpr */
if (strncmp(id, "..", 2)) {
return -parsed;
}
++par_times;
parsed += 2;
id += 2;
while (isspace(id[0])) {
++parsed;
++id;
}
}
/* 1*(".." *WSP "/" *WSP) *(node-identifier *WSP "/" *WSP) node-identifier
*
* first parent reference with whitespaces already parsed
*/
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
while (!strncmp(id, "..", 2) && !*parent_times) {
++par_times;
parsed += 2;
id += 2;
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
}
if (!*parent_times) {
*parent_times = par_times;
}
/* all parent references must be parsed at this point */
if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
return parsed;
}
/**
* @brief Parse path-arg (leafref).
*
* path-arg = absolute-path / relative-path
* absolute-path = 1*("/" (node-identifier *path-predicate))
* relative-path = 1*(".." "/") descendant-path
*
* @param[in] mod Module of the context node to get correct prefix in case it is not explicitly specified
* @param[in] id Identifier to use.
* @param[out] prefix Points to the prefix, NULL if there is not any.
* @param[out] pref_len Length of the prefix, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] parent_times Number of ".." in the path. Must be 0 on the first call,
* must not be changed between consecutive calls. -1 if the
* path is relative.
* @param[out] has_predicate Flag to mark whether there is a predicate specified.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_path_arg(const struct lys_module *mod, const char *id, const char **prefix, int *pref_len,
const char **name, int *nam_len, int *parent_times, int *has_predicate)
{
int parsed = 0, ret, par_times = 0;
assert(id);
assert(parent_times);
if (prefix) {
*prefix = NULL;
}
if (pref_len) {
*pref_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (!*parent_times && !strncmp(id, "..", 2)) {
++par_times;
parsed += 2;
id += 2;
while (!strncmp(id, "/..", 3)) {
++par_times;
parsed += 3;
id += 3;
}
}
if (!*parent_times) {
if (par_times) {
*parent_times = par_times;
} else {
*parent_times = -1;
}
}
if (id[0] != '/') {
return -parsed;
}
/* skip '/' */
++parsed;
++id;
/* node-identifier ([prefix:]identifier) */
if ((ret = parse_node_identifier(id, prefix, pref_len, name, nam_len, NULL, 0)) < 1) {
return -parsed - ret;
}
if (prefix && !(*prefix)) {
/* actually we always need prefix even it is not specified */
*prefix = lys_main_module(mod)->name;
*pref_len = strlen(*prefix);
}
parsed += ret;
id += ret;
/* there is no predicate */
if ((id[0] == '/') || !id[0]) {
return parsed;
} else if (id[0] != '[') {
return -parsed;
}
if (has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse instance-identifier in JSON data format. That means that prefixes
* are actually model names.
*
* instance-identifier = 1*("/" (node-identifier *predicate))
*
* @param[in] id Identifier to use.
* @param[out] model Points to the model name.
* @param[out] mod_len Length of the model name.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] has_predicate Flag to mark whether there is a predicate specified.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_instance_identifier(const char *id, const char **model, int *mod_len, const char **name, int *nam_len,
int *has_predicate)
{
int parsed = 0, ret;
assert(id && model && mod_len && name && nam_len);
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '/') {
return -parsed;
}
++parsed;
++id;
if ((ret = parse_identifier(id)) < 1) {
return ret;
}
*name = id;
*nam_len = ret;
parsed += ret;
id += ret;
if (id[0] == ':') {
/* we have prefix */
*model = *name;
*mod_len = *nam_len;
++parsed;
++id;
if ((ret = parse_identifier(id)) < 1) {
return ret;
}
*name = id;
*nam_len = ret;
parsed += ret;
id += ret;
}
if (id[0] == '[' && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse predicate (instance-identifier) in JSON data format. That means that prefixes
* (which are mandatory) are actually model names.
*
* predicate = "[" *WSP (predicate-expr / pos) *WSP "]"
* predicate-expr = (node-identifier / ".") *WSP "=" *WSP
* ((DQUOTE string DQUOTE) /
* (SQUOTE string SQUOTE))
* pos = non-negative-integer-value
*
* @param[in] id Identifier to use.
* @param[out] model Points to the model name.
* @param[out] mod_len Length of the model name.
* @param[out] name Points to the node name. Can be identifier (from node-identifier), "." or pos.
* @param[out] nam_len Length of the node name.
* @param[out] value Value the node-identifier must have (string from the grammar),
* NULL if there is not any.
* @param[out] val_len Length of the value, 0 if there is not any.
* @param[out] has_predicate Flag to mark whether there is a predicate specified.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
parse_predicate(const char *id, const char **model, int *mod_len, const char **name, int *nam_len,
const char **value, int *val_len, int *has_predicate)
{
const char *ptr;
int parsed = 0, ret;
char quote;
assert(id);
if (model) {
assert(mod_len);
*model = NULL;
*mod_len = 0;
}
if (name) {
assert(nam_len);
*name = NULL;
*nam_len = 0;
}
if (value) {
assert(val_len);
*value = NULL;
*val_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '[') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* pos */
if (isdigit(id[0])) {
if (name) {
*name = id;
}
if (id[0] == '0') {
return -parsed;
}
while (isdigit(id[0])) {
++parsed;
++id;
}
if (nam_len) {
*nam_len = id-(*name);
}
/* "." or node-identifier */
} else {
if (id[0] == '.') {
if (name) {
*name = id;
}
if (nam_len) {
*nam_len = 1;
}
++parsed;
++id;
} else {
if ((ret = parse_node_identifier(id, model, mod_len, name, nam_len, NULL, 0)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
}
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != '=') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */
if ((id[0] == '\"') || (id[0] == '\'')) {
quote = id[0];
++parsed;
++id;
if ((ptr = strchr(id, quote)) == NULL) {
return -parsed;
}
ret = ptr - id;
if (value) {
*value = id;
}
if (val_len) {
*val_len = ret;
}
parsed += ret + 1;
id += ret + 1;
} else {
return -parsed;
}
}
while (isspace(id[0])) {
++parsed;
++id;
}
if (id[0] != ']') {
return -parsed;
}
++parsed;
++id;
if ((id[0] == '[') && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse schema-nodeid.
*
* schema-nodeid = absolute-schema-nodeid /
* descendant-schema-nodeid
* absolute-schema-nodeid = 1*("/" node-identifier)
* descendant-schema-nodeid = ["." "/"]
* node-identifier
* absolute-schema-nodeid
*
* @param[in] id Identifier to use.
* @param[out] mod_name Points to the module name, NULL if there is not any.
* @param[out] mod_name_len Length of the module name, 0 if there is not any.
* @param[out] name Points to the node name.
* @param[out] nam_len Length of the node name.
* @param[out] is_relative Flag to mark whether the nodeid is absolute or descendant. Must be -1
* on the first call, must not be changed between consecutive calls.
* @param[out] has_predicate Flag to mark whether there is a predicate specified. It cannot be
* based on the grammar, in those cases use NULL.
* @param[in] extended Whether to accept an extended path (support for /[prefix:]*, //[prefix:]*, //[prefix:].).
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
int
parse_schema_nodeid(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len,
int *is_relative, int *has_predicate, int *all_desc, int extended)
{
int parsed = 0, ret;
assert(id);
assert(is_relative);
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '/') {
if (*is_relative != -1) {
return -parsed;
} else {
*is_relative = 1;
}
if (!strncmp(id, "./", 2)) {
parsed += 2;
id += 2;
}
} else {
if (*is_relative == -1) {
*is_relative = 0;
}
++parsed;
++id;
}
if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, all_desc, extended)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
if ((id[0] == '[') && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
/**
* @brief Parse schema predicate (special format internally used).
*
* predicate = "[" *WSP predicate-expr *WSP "]"
* predicate-expr = "." / [prefix:]identifier / positive-integer / key-with-value
* key-with-value = identifier *WSP "=" *WSP
* ((DQUOTE string DQUOTE) /
* (SQUOTE string SQUOTE))
*
* @param[in] id Identifier to use.
* @param[out] mod_name Points to the list key module name.
* @param[out] mod_name_len Length of \p mod_name.
* @param[out] name Points to the list key name.
* @param[out] nam_len Length of \p name.
* @param[out] value Points to the key value. If specified, key-with-value is expected.
* @param[out] val_len Length of \p value.
* @param[out] has_predicate Flag to mark whether there is another predicate specified.
*/
int
parse_schema_json_predicate(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len,
const char **value, int *val_len, int *has_predicate)
{
const char *ptr;
int parsed = 0, ret;
char quote;
assert(id);
if (mod_name) {
*mod_name = NULL;
}
if (mod_name_len) {
*mod_name_len = 0;
}
if (name) {
*name = NULL;
}
if (nam_len) {
*nam_len = 0;
}
if (value) {
*value = NULL;
}
if (val_len) {
*val_len = 0;
}
if (has_predicate) {
*has_predicate = 0;
}
if (id[0] != '[') {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* identifier */
if (id[0] == '.') {
ret = 1;
if (name) {
*name = id;
}
if (nam_len) {
*nam_len = ret;
}
} else if (isdigit(id[0])) {
if (id[0] == '0') {
return -parsed;
}
ret = 1;
while (isdigit(id[ret])) {
++ret;
}
if (name) {
*name = id;
}
if (nam_len) {
*nam_len = ret;
}
} else if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, NULL, 0)) < 1) {
return -parsed + ret;
}
parsed += ret;
id += ret;
while (isspace(id[0])) {
++parsed;
++id;
}
/* there is value as well */
if (id[0] == '=') {
if (name && isdigit(**name)) {
return -parsed;
}
++parsed;
++id;
while (isspace(id[0])) {
++parsed;
++id;
}
/* ((DQUOTE string DQUOTE) / (SQUOTE string SQUOTE)) */
if ((id[0] == '\"') || (id[0] == '\'')) {
quote = id[0];
++parsed;
++id;
if ((ptr = strchr(id, quote)) == NULL) {
return -parsed;
}
ret = ptr - id;
if (value) {
*value = id;
}
if (val_len) {
*val_len = ret;
}
parsed += ret + 1;
id += ret + 1;
} else {
return -parsed;
}
while (isspace(id[0])) {
++parsed;
++id;
}
}
if (id[0] != ']') {
return -parsed;
}
++parsed;
++id;
if ((id[0] == '[') && has_predicate) {
*has_predicate = 1;
}
return parsed;
}
#ifdef LY_ENABLED_CACHE
static int
resolve_hash_table_find_equal(void *val1_p, void *val2_p, int mod, void *UNUSED(cb_data))
{
struct lyd_node *val2, *elem2;
struct parsed_pred pp;
const char *str;
int i;
assert(!mod);
(void)mod;
pp = *((struct parsed_pred *)val1_p);
val2 = *((struct lyd_node **)val2_p);
if (val2->schema != pp.schema) {
return 0;
}
switch (val2->schema->nodetype) {
case LYS_CONTAINER:
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
return 1;
case LYS_LEAFLIST:
str = ((struct lyd_node_leaf_list *)val2)->value_str;
if (!strncmp(str, pp.pred[0].value, pp.pred[0].val_len) && !str[pp.pred[0].val_len]) {
return 1;
}
return 0;
case LYS_LIST:
assert(((struct lys_node_list *)val2->schema)->keys_size);
assert(((struct lys_node_list *)val2->schema)->keys_size == pp.len);
/* lists with keys, their equivalence is based on their keys */
elem2 = val2->child;
/* the exact data order is guaranteed */
for (i = 0; elem2 && (i < pp.len); ++i) {
/* module check */
if (pp.pred[i].mod_name) {
if (strncmp(lyd_node_module(elem2)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len)
|| lyd_node_module(elem2)->name[pp.pred[i].mod_name_len]) {
break;
}
} else {
if (lyd_node_module(elem2) != lys_node_module(pp.schema)) {
break;
}
}
/* name check */
if (strncmp(elem2->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || elem2->schema->name[pp.pred[i].nam_len]) {
break;
}
/* value check */
str = ((struct lyd_node_leaf_list *)elem2)->value_str;
if (strncmp(str, pp.pred[i].value, pp.pred[i].val_len) || str[pp.pred[i].val_len]) {
break;
}
/* next key */
elem2 = elem2->next;
}
if (i == pp.len) {
return 1;
}
return 0;
default:
break;
}
LOGINT(val2->schema->module->ctx);
return 0;
}
static struct lyd_node *
resolve_json_data_node_hash(struct lyd_node *parent, struct parsed_pred pp)
{
values_equal_cb prev_cb;
struct lyd_node **ret = NULL;
uint32_t hash;
int i;
assert(parent && parent->hash);
/* set our value equivalence callback that does not require data nodes */
prev_cb = lyht_set_cb(parent->ht, resolve_hash_table_find_equal);
/* get the hash of the searched node */
hash = dict_hash_multi(0, lys_node_module(pp.schema)->name, strlen(lys_node_module(pp.schema)->name));
hash = dict_hash_multi(hash, pp.schema->name, strlen(pp.schema->name));
if (pp.schema->nodetype == LYS_LEAFLIST) {
assert((pp.len == 1) && (pp.pred[0].name[0] == '.') && (pp.pred[0].nam_len == 1));
/* leaf-list value in predicate */
hash = dict_hash_multi(hash, pp.pred[0].value, pp.pred[0].val_len);
} else if (pp.schema->nodetype == LYS_LIST) {
/* list keys in predicates */
for (i = 0; i < pp.len; ++i) {
hash = dict_hash_multi(hash, pp.pred[i].value, pp.pred[i].val_len);
}
}
hash = dict_hash_multi(hash, NULL, 0);
/* try to find the node */
i = lyht_find(parent->ht, &pp, hash, (void **)&ret);
assert(i || *ret);
/* restore the original callback */
lyht_set_cb(parent->ht, prev_cb);
return (i ? NULL : *ret);
}
#endif
/**
* @brief Resolve (find) a feature definition. Logs directly.
*
* @param[in] feat_name Feature name to resolve.
* @param[in] len Length of \p feat_name.
* @param[in] node Node with the if-feature expression.
* @param[out] feature Pointer to be set to point to the feature definition, if feature not found
* (return code 1), the pointer is untouched.
*
* @return 0 on success, 1 on forward reference, -1 on error.
*/
static int
resolve_feature(const char *feat_name, uint16_t len, const struct lys_node *node, struct lys_feature **feature)
{
char *str;
const char *mod_name, *name;
int mod_name_len, nam_len, i, j;
const struct lys_module *module;
assert(feature);
/* check prefix */
if ((i = parse_node_identifier(feat_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0)) < 1) {
LOGVAL(node->module->ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, feat_name[-i], &feat_name[-i]);
return -1;
}
module = lyp_get_module(lys_node_module(node), NULL, 0, mod_name, mod_name_len, 0);
if (!module) {
/* identity refers unknown data model */
LOGVAL(node->module->ctx, LYE_INMOD_LEN, LY_VLOG_NONE, NULL, mod_name_len, mod_name);
return -1;
}
if (module != node->module && module == lys_node_module(node)) {
/* first, try to search directly in submodule where the feature was mentioned */
for (j = 0; j < node->module->features_size; j++) {
if (!strncmp(name, node->module->features[j].name, nam_len) && !node->module->features[j].name[nam_len]) {
/* check status */
if (lyp_check_status(node->flags, lys_node_module(node), node->name, node->module->features[j].flags,
node->module->features[j].module, node->module->features[j].name, NULL)) {
return -1;
}
*feature = &node->module->features[j];
return 0;
}
}
}
/* search in the identified module ... */
for (j = 0; j < module->features_size; j++) {
if (!strncmp(name, module->features[j].name, nam_len) && !module->features[j].name[nam_len]) {
/* check status */
if (lyp_check_status(node->flags, lys_node_module(node), node->name, module->features[j].flags,
module->features[j].module, module->features[j].name, NULL)) {
return -1;
}
*feature = &module->features[j];
return 0;
}
}
/* ... and all its submodules */
for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) {
for (j = 0; j < module->inc[i].submodule->features_size; j++) {
if (!strncmp(name, module->inc[i].submodule->features[j].name, nam_len)
&& !module->inc[i].submodule->features[j].name[nam_len]) {
/* check status */
if (lyp_check_status(node->flags, lys_node_module(node), node->name,
module->inc[i].submodule->features[j].flags,
module->inc[i].submodule->features[j].module,
module->inc[i].submodule->features[j].name, NULL)) {
return -1;
}
*feature = &module->inc[i].submodule->features[j];
return 0;
}
}
}
/* not found */
str = strndup(feat_name, len);
LOGVAL(node->module->ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, "feature", str);
free(str);
return 1;
}
/*
* @return
* - 1 if enabled
* - 0 if disabled
*/
static int
resolve_feature_value(const struct lys_feature *feat)
{
int i;
for (i = 0; i < feat->iffeature_size; i++) {
if (!resolve_iffeature(&feat->iffeature[i])) {
return 0;
}
}
return feat->flags & LYS_FENABLED ? 1 : 0;
}
static int
resolve_iffeature_recursive(struct lys_iffeature *expr, int *index_e, int *index_f)
{
uint8_t op;
int a, b;
op = iff_getop(expr->expr, *index_e);
(*index_e)++;
switch (op) {
case LYS_IFF_F:
/* resolve feature */
return resolve_feature_value(expr->features[(*index_f)++]);
case LYS_IFF_NOT:
/* invert result */
return resolve_iffeature_recursive(expr, index_e, index_f) ? 0 : 1;
case LYS_IFF_AND:
case LYS_IFF_OR:
a = resolve_iffeature_recursive(expr, index_e, index_f);
b = resolve_iffeature_recursive(expr, index_e, index_f);
if (op == LYS_IFF_AND) {
return a && b;
} else { /* LYS_IFF_OR */
return a || b;
}
}
return 0;
}
int
resolve_iffeature(struct lys_iffeature *expr)
{
int index_e = 0, index_f = 0;
if (expr->expr) {
return resolve_iffeature_recursive(expr, &index_e, &index_f);
}
return 0;
}
struct iff_stack {
int size;
int index; /* first empty item */
uint8_t *stack;
};
static int
iff_stack_push(struct iff_stack *stack, uint8_t value)
{
if (stack->index == stack->size) {
stack->size += 4;
stack->stack = ly_realloc(stack->stack, stack->size * sizeof *stack->stack);
LY_CHECK_ERR_RETURN(!stack->stack, LOGMEM(NULL); stack->size = 0, EXIT_FAILURE);
}
stack->stack[stack->index++] = value;
return EXIT_SUCCESS;
}
static uint8_t
iff_stack_pop(struct iff_stack *stack)
{
stack->index--;
return stack->stack[stack->index];
}
static void
iff_stack_clean(struct iff_stack *stack)
{
stack->size = 0;
free(stack->stack);
}
static void
iff_setop(uint8_t *list, uint8_t op, int pos)
{
uint8_t *item;
uint8_t mask = 3;
assert(pos >= 0);
assert(op <= 3); /* max 2 bits */
item = &list[pos / 4];
mask = mask << 2 * (pos % 4);
*item = (*item) & ~mask;
*item = (*item) | (op << 2 * (pos % 4));
}
uint8_t
iff_getop(uint8_t *list, int pos)
{
uint8_t *item;
uint8_t mask = 3, result;
assert(pos >= 0);
item = &list[pos / 4];
result = (*item) & (mask << 2 * (pos % 4));
return result >> 2 * (pos % 4);
}
#define LYS_IFF_LP 0x04 /* ( */
#define LYS_IFF_RP 0x08 /* ) */
/* internal structure for passing data for UNRES_IFFEAT */
struct unres_iffeat_data {
struct lys_node *node;
const char *fname;
int infeature;
};
void
resolve_iffeature_getsizes(struct lys_iffeature *iffeat, unsigned int *expr_size, unsigned int *feat_size)
{
unsigned int e = 0, f = 0, r = 0;
uint8_t op;
assert(iffeat);
if (!iffeat->expr) {
goto result;
}
do {
op = iff_getop(iffeat->expr, e++);
switch (op) {
case LYS_IFF_NOT:
if (!r) {
r += 1;
}
break;
case LYS_IFF_AND:
case LYS_IFF_OR:
if (!r) {
r += 2;
} else {
r += 1;
}
break;
case LYS_IFF_F:
f++;
if (r) {
r--;
}
break;
}
} while(r);
result:
if (expr_size) {
*expr_size = e;
}
if (feat_size) {
*feat_size = f;
}
}
int
resolve_iffeature_compile(struct lys_iffeature *iffeat_expr, const char *value, struct lys_node *node,
int infeature, struct unres_schema *unres)
{
const char *c = value;
int r, rc = EXIT_FAILURE;
int i, j, last_not, checkversion = 0;
unsigned int f_size = 0, expr_size = 0, f_exp = 1;
uint8_t op;
struct iff_stack stack = {0, 0, NULL};
struct unres_iffeat_data *iff_data;
struct ly_ctx *ctx = node->module->ctx;
assert(c);
if (isspace(c[0])) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, c[0], c);
return EXIT_FAILURE;
}
/* pre-parse the expression to get sizes for arrays, also do some syntax checks of the expression */
for (i = j = last_not = 0; c[i]; i++) {
if (c[i] == '(') {
checkversion = 1;
j++;
continue;
} else if (c[i] == ')') {
j--;
continue;
} else if (isspace(c[i])) {
continue;
}
if (!strncmp(&c[i], "not", r = 3) || !strncmp(&c[i], "and", r = 3) || !strncmp(&c[i], "or", r = 2)) {
if (c[i + r] == '\0') {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
return EXIT_FAILURE;
} else if (!isspace(c[i + r])) {
/* feature name starting with the not/and/or */
last_not = 0;
f_size++;
} else if (c[i] == 'n') { /* not operation */
if (last_not) {
/* double not */
expr_size = expr_size - 2;
last_not = 0;
} else {
last_not = 1;
}
} else { /* and, or */
f_exp++;
/* not a not operation */
last_not = 0;
}
i += r;
} else {
f_size++;
last_not = 0;
}
expr_size++;
while (!isspace(c[i])) {
if (!c[i] || c[i] == ')') {
i--;
break;
}
i++;
}
}
if (j || f_exp != f_size) {
/* not matching count of ( and ) */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
return EXIT_FAILURE;
}
if (checkversion || expr_size > 1) {
/* check that we have 1.1 module */
if (node->module->version != LYS_VERSION_1_1) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "YANG 1.1 if-feature expression found in 1.0 module.");
return EXIT_FAILURE;
}
}
/* allocate the memory */
iffeat_expr->expr = calloc((j = (expr_size / 4) + ((expr_size % 4) ? 1 : 0)), sizeof *iffeat_expr->expr);
iffeat_expr->features = calloc(f_size, sizeof *iffeat_expr->features);
stack.stack = malloc(expr_size * sizeof *stack.stack);
LY_CHECK_ERR_GOTO(!stack.stack || !iffeat_expr->expr || !iffeat_expr->features, LOGMEM(ctx), error);
stack.size = expr_size;
f_size--; expr_size--; /* used as indexes from now */
for (i--; i >= 0; i--) {
if (c[i] == ')') {
/* push it on stack */
iff_stack_push(&stack, LYS_IFF_RP);
continue;
} else if (c[i] == '(') {
/* pop from the stack into result all operators until ) */
while((op = iff_stack_pop(&stack)) != LYS_IFF_RP) {
iff_setop(iffeat_expr->expr, op, expr_size--);
}
continue;
} else if (isspace(c[i])) {
continue;
}
/* end operator or operand -> find beginning and get what is it */
j = i + 1;
while (i >= 0 && !isspace(c[i]) && c[i] != '(') {
i--;
}
i++; /* get back by one step */
if (!strncmp(&c[i], "not", 3) && isspace(c[i + 3])) {
if (stack.index && stack.stack[stack.index - 1] == LYS_IFF_NOT) {
/* double not */
iff_stack_pop(&stack);
} else {
/* not has the highest priority, so do not pop from the stack
* as in case of AND and OR */
iff_stack_push(&stack, LYS_IFF_NOT);
}
} else if (!strncmp(&c[i], "and", 3) && isspace(c[i + 3])) {
/* as for OR - pop from the stack all operators with the same or higher
* priority and store them to the result, then push the AND to the stack */
while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_AND) {
op = iff_stack_pop(&stack);
iff_setop(iffeat_expr->expr, op, expr_size--);
}
iff_stack_push(&stack, LYS_IFF_AND);
} else if (!strncmp(&c[i], "or", 2) && isspace(c[i + 2])) {
while (stack.index && stack.stack[stack.index - 1] <= LYS_IFF_OR) {
op = iff_stack_pop(&stack);
iff_setop(iffeat_expr->expr, op, expr_size--);
}
iff_stack_push(&stack, LYS_IFF_OR);
} else {
/* feature name, length is j - i */
/* add it to the result */
iff_setop(iffeat_expr->expr, LYS_IFF_F, expr_size--);
/* now get the link to the feature definition. Since it can be
* forward referenced, we have to keep the feature name in auxiliary
* structure passed into unres */
iff_data = malloc(sizeof *iff_data);
LY_CHECK_ERR_GOTO(!iff_data, LOGMEM(ctx), error);
iff_data->node = node;
iff_data->fname = lydict_insert(node->module->ctx, &c[i], j - i);
iff_data->infeature = infeature;
r = unres_schema_add_node(node->module, unres, &iffeat_expr->features[f_size], UNRES_IFFEAT,
(struct lys_node *)iff_data);
f_size--;
if (r == -1) {
lydict_remove(node->module->ctx, iff_data->fname);
free(iff_data);
goto error;
}
}
}
while (stack.index) {
op = iff_stack_pop(&stack);
iff_setop(iffeat_expr->expr, op, expr_size--);
}
if (++expr_size || ++f_size) {
/* not all expected operators and operands found */
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature");
rc = EXIT_FAILURE;
} else {
rc = EXIT_SUCCESS;
}
error:
/* cleanup */
iff_stack_clean(&stack);
return rc;
}
/**
* @brief Resolve (find) a data node based on a schema-nodeid.
*
* Used for resolving unique statements - so id is expected to be relative and local (without reference to a different
* module).
*
*/
struct lyd_node *
resolve_data_descendant_schema_nodeid(const char *nodeid, struct lyd_node *start)
{
char *str, *token, *p;
struct lyd_node *result = NULL, *iter;
const struct lys_node *schema = NULL;
assert(nodeid && start);
if (nodeid[0] == '/') {
return NULL;
}
str = p = strdup(nodeid);
LY_CHECK_ERR_RETURN(!str, LOGMEM(start->schema->module->ctx), NULL);
while (p) {
token = p;
p = strchr(p, '/');
if (p) {
*p = '\0';
p++;
}
if (p) {
/* inner node */
if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema,
LYS_CONTAINER | LYS_CHOICE | LYS_CASE | LYS_LEAF, 0, &schema)
|| !schema) {
result = NULL;
break;
}
if (schema->nodetype & (LYS_CHOICE | LYS_CASE)) {
continue;
}
} else {
/* final node */
if (resolve_descendant_schema_nodeid(token, schema ? schema->child : start->schema, LYS_LEAF, 0, &schema)
|| !schema) {
result = NULL;
break;
}
}
LY_TREE_FOR(result ? result->child : start, iter) {
if (iter->schema == schema) {
/* move in data tree according to returned schema */
result = iter;
break;
}
}
if (!iter) {
/* instance not found */
result = NULL;
break;
}
}
free(str);
return result;
}
int
schema_nodeid_siblingcheck(const struct lys_node *sibling, const struct lys_module *cur_module, const char *mod_name,
int mod_name_len, const char *name, int nam_len)
{
const struct lys_module *prefix_mod;
/* handle special names */
if (name[0] == '*') {
return 2;
} else if (name[0] == '.') {
return 3;
}
/* name check */
if (strncmp(name, sibling->name, nam_len) || sibling->name[nam_len]) {
return 1;
}
/* module check */
if (mod_name) {
prefix_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0);
if (!prefix_mod) {
return -1;
}
} else {
prefix_mod = cur_module;
}
if (prefix_mod != lys_node_module(sibling)) {
return 1;
}
/* match */
return 0;
}
/* keys do not have to be ordered and do not have to be all of them */
static int
resolve_extended_schema_nodeid_predicate(const char *nodeid, const struct lys_node *node,
const struct lys_module *cur_module, int *nodeid_end)
{
int mod_len, nam_len, has_predicate, r, i;
const char *model, *name;
struct lys_node_list *list;
if (!(node->nodetype & (LYS_LIST | LYS_LEAFLIST))) {
return 1;
}
list = (struct lys_node_list *)node;
do {
r = parse_schema_json_predicate(nodeid, &model, &mod_len, &name, &nam_len, NULL, NULL, &has_predicate);
if (r < 1) {
LOGVAL(cur_module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, nodeid[r], &nodeid[r]);
return -1;
}
nodeid += r;
if (node->nodetype == LYS_LEAFLIST) {
/* just check syntax */
if (model || !name || (name[0] != '.') || has_predicate) {
return 1;
}
break;
} else {
/* check the key */
for (i = 0; i < list->keys_size; ++i) {
if (strncmp(list->keys[i]->name, name, nam_len) || list->keys[i]->name[nam_len]) {
continue;
}
if (model) {
if (strncmp(lys_node_module((struct lys_node *)list->keys[i])->name, model, mod_len)
|| lys_node_module((struct lys_node *)list->keys[i])->name[mod_len]) {
continue;
}
} else {
if (lys_node_module((struct lys_node *)list->keys[i]) != cur_module) {
continue;
}
}
/* match */
break;
}
if (i == list->keys_size) {
return 1;
}
}
} while (has_predicate);
if (!nodeid[0]) {
*nodeid_end = 1;
}
return 0;
}
/* start_parent - relative, module - absolute, -1 error (logged), EXIT_SUCCESS ok
*/
int
resolve_schema_nodeid(const char *nodeid, const struct lys_node *start_parent, const struct lys_module *cur_module,
struct ly_set **ret, int extended, int no_node_error)
{
const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL;
const struct lys_node *sibling, *next, *elem;
struct lys_node_augment *last_aug;
int r, nam_len, mod_name_len = 0, is_relative = -1, all_desc, has_predicate, nodeid_end = 0;
int yang_data_name_len, backup_mod_name_len = 0;
/* resolved import module from the start module, it must match the next node-name-match sibling */
const struct lys_module *start_mod, *aux_mod = NULL;
char *str;
struct ly_ctx *ctx;
assert(nodeid && (start_parent || cur_module) && ret);
*ret = NULL;
if (!cur_module) {
cur_module = lys_node_module(start_parent);
}
ctx = cur_module->ctx;
id = nodeid;
r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1);
if (r < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]);
return -1;
}
if (name[0] == '#') {
if (is_relative) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name);
return -1;
}
yang_data_name = name + 1;
yang_data_name_len = nam_len - 1;
backup_mod_name = mod_name;
backup_mod_name_len = mod_name_len;
id += r;
} else {
is_relative = -1;
}
r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate,
(extended ? &all_desc : NULL), extended);
if (r < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]);
return -1;
}
id += r;
if (backup_mod_name) {
mod_name = backup_mod_name;
mod_name_len = backup_mod_name_len;
}
if (is_relative && !start_parent) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_STR, nodeid, "Starting node must be provided for relative paths.");
return -1;
}
/* descendant-schema-nodeid */
if (is_relative) {
cur_module = start_mod = lys_node_module(start_parent);
/* absolute-schema-nodeid */
} else {
start_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0);
if (!start_mod) {
str = strndup(mod_name, mod_name_len);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return -1;
}
start_parent = NULL;
if (yang_data_name) {
start_parent = lyp_get_yang_data_template(start_mod, yang_data_name, yang_data_name_len);
if (!start_parent) {
str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return -1;
}
}
}
while (1) {
sibling = NULL;
last_aug = NULL;
if (start_parent) {
if (mod_name && (strncmp(mod_name, cur_module->name, mod_name_len)
|| (mod_name_len != (signed)strlen(cur_module->name)))) {
/* we are getting into another module (augment) */
aux_mod = lyp_get_module(cur_module, NULL, 0, mod_name, mod_name_len, 0);
if (!aux_mod) {
str = strndup(mod_name, mod_name_len);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return -1;
}
} else {
/* there is no mod_name, so why are we checking augments again?
* because this module may be not implemented and it augments something in another module and
* there is another augment augmenting that previous one */
aux_mod = cur_module;
}
/* look into augments */
if (!extended) {
get_next_augment:
last_aug = lys_getnext_target_aug(last_aug, aux_mod, start_parent);
}
}
while ((sibling = lys_getnext(sibling, (last_aug ? (struct lys_node *)last_aug : start_parent), start_mod,
LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) {
r = schema_nodeid_siblingcheck(sibling, cur_module, mod_name, mod_name_len, name, nam_len);
/* resolve predicate */
if (extended && ((r == 0) || (r == 2) || (r == 3)) && has_predicate) {
r = resolve_extended_schema_nodeid_predicate(id, sibling, cur_module, &nodeid_end);
if (r == 1) {
continue;
} else if (r == -1) {
return -1;
}
} else if (!id[0]) {
nodeid_end = 1;
}
if (r == 0) {
/* one matching result */
if (nodeid_end) {
*ret = ly_set_new();
LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1);
ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST);
} else {
if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
return -1;
}
start_parent = sibling;
}
break;
} else if (r == 1) {
continue;
} else if (r == 2) {
/* "*" */
if (!*ret) {
*ret = ly_set_new();
LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1);
}
ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST);
if (all_desc) {
LY_TREE_DFS_BEGIN(sibling, next, elem) {
if (elem != sibling) {
ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST);
}
LY_TREE_DFS_END(sibling, next, elem);
}
}
} else if (r == 3) {
/* "." */
if (!*ret) {
*ret = ly_set_new();
LY_CHECK_ERR_RETURN(!*ret, LOGMEM(ctx), -1);
ly_set_add(*ret, (void *)start_parent, LY_SET_OPT_USEASLIST);
}
ly_set_add(*ret, (void *)sibling, LY_SET_OPT_USEASLIST);
if (all_desc) {
LY_TREE_DFS_BEGIN(sibling, next, elem) {
if (elem != sibling) {
ly_set_add(*ret, (void *)elem, LY_SET_OPT_USEASLIST);
}
LY_TREE_DFS_END(sibling, next, elem);
}
}
} else {
LOGINT(ctx);
return -1;
}
}
/* skip predicate */
if (extended && has_predicate) {
while (id[0] == '[') {
id = strchr(id, ']');
if (!id) {
LOGINT(ctx);
return -1;
}
++id;
}
}
if (nodeid_end && ((r == 0) || (r == 2) || (r == 3))) {
return EXIT_SUCCESS;
}
/* no match */
if (!sibling) {
if (last_aug) {
/* it still could be in another augment */
goto get_next_augment;
}
if (no_node_error) {
str = strndup(nodeid, (name - nodeid) + nam_len);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return -1;
}
*ret = NULL;
return EXIT_SUCCESS;
}
r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate,
(extended ? &all_desc : NULL), extended);
if (r < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[r], &id[r]);
return -1;
}
id += r;
}
/* cannot get here */
LOGINT(ctx);
return -1;
}
/* unique, refine,
* >0 - unexpected char on position (ret - 1),
* 0 - ok (but ret can still be NULL),
* -1 - error,
* -2 - violated no_innerlist */
int
resolve_descendant_schema_nodeid(const char *nodeid, const struct lys_node *start, int ret_nodetype,
int no_innerlist, const struct lys_node **ret)
{
const char *name, *mod_name, *id;
const struct lys_node *sibling, *start_parent;
int r, nam_len, mod_name_len, is_relative = -1;
/* resolved import module from the start module, it must match the next node-name-match sibling */
const struct lys_module *module;
assert(nodeid && ret);
assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT | LYS_GROUPING)));
if (!start) {
/* leaf not found */
return 0;
}
id = nodeid;
module = lys_node_module(start);
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
if (!is_relative) {
return -1;
}
start_parent = lys_parent(start);
while ((start_parent->nodetype == LYS_USES) && lys_parent(start_parent)) {
start_parent = lys_parent(start_parent);
}
while (1) {
sibling = NULL;
while ((sibling = lys_getnext(sibling, start_parent, module,
LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_PARENTUSES | LYS_GETNEXT_NOSTATECHECK))) {
r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len);
if (r == 0) {
if (!id[0]) {
if (!(sibling->nodetype & ret_nodetype)) {
/* wrong node type, too bad */
continue;
}
*ret = sibling;
return EXIT_SUCCESS;
}
start_parent = sibling;
break;
} else if (r == 1) {
continue;
} else {
return -1;
}
}
/* no match */
if (!sibling) {
*ret = NULL;
return EXIT_SUCCESS;
} else if (no_innerlist && sibling->nodetype == LYS_LIST) {
*ret = NULL;
return -2;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
}
/* cannot get here */
LOGINT(module->ctx);
return -1;
}
/* choice default */
int
resolve_choice_default_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node **ret)
{
/* cannot actually be a path */
if (strchr(nodeid, '/')) {
return -1;
}
return resolve_descendant_schema_nodeid(nodeid, start, LYS_NO_RPC_NOTIF_NODE, 0, ret);
}
/* uses, -1 error, EXIT_SUCCESS ok (but ret can still be NULL), >0 unexpected char on ret - 1 */
static int
resolve_uses_schema_nodeid(const char *nodeid, const struct lys_node *start, const struct lys_node_grp **ret)
{
const struct lys_module *module;
const char *mod_prefix, *name;
int i, mod_prefix_len, nam_len;
/* parse the identifier, it must be parsed on one call */
if (((i = parse_node_identifier(nodeid, &mod_prefix, &mod_prefix_len, &name, &nam_len, NULL, 0)) < 1) || nodeid[i]) {
return -i + 1;
}
module = lyp_get_module(start->module, mod_prefix, mod_prefix_len, NULL, 0, 0);
if (!module) {
return -1;
}
if (module != lys_main_module(start->module)) {
start = module->data;
}
*ret = lys_find_grouping_up(name, (struct lys_node *)start);
return EXIT_SUCCESS;
}
int
resolve_absolute_schema_nodeid(const char *nodeid, const struct lys_module *module, int ret_nodetype,
const struct lys_node **ret)
{
const char *name, *mod_name, *id;
const struct lys_node *sibling, *start_parent;
int r, nam_len, mod_name_len, is_relative = -1;
const struct lys_module *abs_start_mod;
assert(nodeid && module && ret);
assert(!(ret_nodetype & (LYS_USES | LYS_AUGMENT)) && ((ret_nodetype == LYS_GROUPING) || !(ret_nodetype & LYS_GROUPING)));
id = nodeid;
start_parent = NULL;
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
if (is_relative) {
return -1;
}
abs_start_mod = lyp_get_module(module, NULL, 0, mod_name, mod_name_len, 0);
if (!abs_start_mod) {
return -1;
}
while (1) {
sibling = NULL;
while ((sibling = lys_getnext(sibling, start_parent, abs_start_mod, LYS_GETNEXT_WITHCHOICE
| LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT | LYS_GETNEXT_WITHGROUPING | LYS_GETNEXT_NOSTATECHECK))) {
r = schema_nodeid_siblingcheck(sibling, module, mod_name, mod_name_len, name, nam_len);
if (r == 0) {
if (!id[0]) {
if (!(sibling->nodetype & ret_nodetype)) {
/* wrong node type, too bad */
continue;
}
*ret = sibling;
return EXIT_SUCCESS;
}
start_parent = sibling;
break;
} else if (r == 1) {
continue;
} else {
return -1;
}
}
/* no match */
if (!sibling) {
*ret = NULL;
return EXIT_SUCCESS;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 0)) < 1) {
return ((id - nodeid) - r) + 1;
}
id += r;
}
/* cannot get here */
LOGINT(module->ctx);
return -1;
}
static int
resolve_json_schema_list_predicate(const char *predicate, const struct lys_node_list *list, int *parsed)
{
const char *mod_name, *name;
int mod_name_len, nam_len, has_predicate, i;
struct lys_node *key;
if (((i = parse_schema_json_predicate(predicate, &mod_name, &mod_name_len, &name, &nam_len, NULL, NULL, &has_predicate)) < 1)
|| !strncmp(name, ".", nam_len)) {
LOGVAL(list->module->ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, predicate[-i], &predicate[-i]);
return -1;
}
predicate += i;
*parsed += i;
if (!isdigit(name[0])) {
for (i = 0; i < list->keys_size; ++i) {
key = (struct lys_node *)list->keys[i];
if (!strncmp(key->name, name, nam_len) && !key->name[nam_len]) {
break;
}
}
if (i == list->keys_size) {
LOGVAL(list->module->ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, name);
return -1;
}
}
/* more predicates? */
if (has_predicate) {
return resolve_json_schema_list_predicate(predicate, list, parsed);
}
return 0;
}
/* cannot return LYS_GROUPING, LYS_AUGMENT, LYS_USES, logs directly */
const struct lys_node *
resolve_json_nodeid(const char *nodeid, struct ly_ctx *ctx, const struct lys_node *start, int output)
{
char *str;
const char *name, *mod_name, *id, *backup_mod_name = NULL, *yang_data_name = NULL;
const struct lys_node *sibling, *start_parent, *parent;
int r, nam_len, mod_name_len, is_relative = -1, has_predicate;
int yang_data_name_len, backup_mod_name_len;
/* resolved import module from the start module, it must match the next node-name-match sibling */
const struct lys_module *prefix_mod, *module, *prev_mod;
assert(nodeid && (ctx || start));
if (!ctx) {
ctx = start->module->ctx;
}
id = nodeid;
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
if (name[0] == '#') {
if (is_relative) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name);
return NULL;
}
yang_data_name = name + 1;
yang_data_name_len = nam_len - 1;
backup_mod_name = mod_name;
backup_mod_name_len = mod_name_len;
id += r;
} else {
is_relative = -1;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
id += r;
if (backup_mod_name) {
mod_name = backup_mod_name;
mod_name_len = backup_mod_name_len;
}
if (is_relative) {
assert(start);
start_parent = start;
while (start_parent && (start_parent->nodetype == LYS_USES)) {
start_parent = lys_parent(start_parent);
}
module = start->module;
} else {
if (!mod_name) {
str = strndup(nodeid, (name + nam_len) - nodeid);
LOGVAL(ctx, LYE_PATH_MISSMOD, LY_VLOG_STR, nodeid);
free(str);
return NULL;
}
str = strndup(mod_name, mod_name_len);
module = ly_ctx_get_module(ctx, str, NULL, 1);
free(str);
if (!module) {
str = strndup(nodeid, (mod_name + mod_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return NULL;
}
start_parent = NULL;
if (yang_data_name) {
start_parent = lyp_get_yang_data_template(module, yang_data_name, yang_data_name_len);
if (!start_parent) {
str = strndup(nodeid, (yang_data_name + yang_data_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return NULL;
}
}
/* now it's as if there was no module name */
mod_name = NULL;
mod_name_len = 0;
}
prev_mod = module;
while (1) {
sibling = NULL;
while ((sibling = lys_getnext(sibling, start_parent, module, 0))) {
/* name match */
if (sibling->name && !strncmp(name, sibling->name, nam_len) && !sibling->name[nam_len]) {
/* output check */
for (parent = lys_parent(sibling); parent && !(parent->nodetype & (LYS_INPUT | LYS_OUTPUT)); parent = lys_parent(parent));
if (parent) {
if (output && (parent->nodetype == LYS_INPUT)) {
continue;
} else if (!output && (parent->nodetype == LYS_OUTPUT)) {
continue;
}
}
/* module check */
if (mod_name) {
/* will also find an augment module */
prefix_mod = ly_ctx_nget_module(ctx, mod_name, mod_name_len, NULL, 1);
if (!prefix_mod) {
str = strndup(nodeid, (mod_name + mod_name_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INMOD, LY_VLOG_STR, str);
free(str);
return NULL;
}
} else {
prefix_mod = prev_mod;
}
if (prefix_mod != lys_node_module(sibling)) {
continue;
}
/* do we have some predicates on it? */
if (has_predicate) {
r = 0;
if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
if ((r = parse_schema_json_predicate(id, NULL, NULL, NULL, NULL, NULL, NULL, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
} else if (sibling->nodetype == LYS_LIST) {
if (resolve_json_schema_list_predicate(id, (const struct lys_node_list *)sibling, &r)) {
return NULL;
}
} else {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
return NULL;
}
id += r;
}
/* the result node? */
if (!id[0]) {
return sibling;
}
/* move down the tree, if possible */
if (sibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
return NULL;
}
start_parent = sibling;
/* update prev mod */
prev_mod = (start_parent->child ? lys_node_module(start_parent->child) : module);
break;
}
}
/* no match */
if (!sibling) {
str = strndup(nodeid, (name + nam_len) - nodeid);
LOGVAL(ctx, LYE_PATH_INNODE, LY_VLOG_STR, str);
free(str);
return NULL;
}
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
return NULL;
}
id += r;
}
/* cannot get here */
LOGINT(ctx);
return NULL;
}
static int
resolve_partial_json_data_list_predicate(struct parsed_pred pp, struct lyd_node *node, int position)
{
uint16_t i;
struct lyd_node_leaf_list *key;
struct lys_node_list *slist;
struct ly_ctx *ctx;
assert(node);
assert(node->schema->nodetype == LYS_LIST);
assert(pp.len);
ctx = node->schema->module->ctx;
slist = (struct lys_node_list *)node->schema;
/* is the predicate a number? */
if (isdigit(pp.pred[0].name[0])) {
if (position == atoi(pp.pred[0].name)) {
/* match */
return 0;
} else {
/* not a match */
return 1;
}
}
key = (struct lyd_node_leaf_list *)node->child;
if (!key) {
/* it is not a position, so we need a key for it to be a match */
return 1;
}
/* go through all the keys */
for (i = 0; i < slist->keys_size; ++i) {
if (strncmp(key->schema->name, pp.pred[i].name, pp.pred[i].nam_len) || key->schema->name[pp.pred[i].nam_len]) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
if (pp.pred[i].mod_name) {
/* specific module, check that the found key is from that module */
if (strncmp(lyd_node_module((struct lyd_node *)key)->name, pp.pred[i].mod_name, pp.pred[i].mod_name_len)
|| lyd_node_module((struct lyd_node *)key)->name[pp.pred[i].mod_name_len]) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
/* but if the module is the same as the parent, it should have been omitted */
if (lyd_node_module((struct lyd_node *)key) == lyd_node_module(node)) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
} else {
/* no module, so it must be the same as the list (parent) */
if (lyd_node_module((struct lyd_node *)key) != lyd_node_module(node)) {
LOGVAL(ctx, LYE_PATH_INKEY, LY_VLOG_NONE, NULL, pp.pred[i].name);
return -1;
}
}
/* value does not match */
if (strncmp(key->value_str, pp.pred[i].value, pp.pred[i].val_len) || key->value_str[pp.pred[i].val_len]) {
return 1;
}
key = (struct lyd_node_leaf_list *)key->next;
}
return 0;
}
/**
* @brief get the closest parent of the node (or the node itself) identified by the nodeid (path)
*
* @param[in] nodeid Node data path to find
* @param[in] llist_value If the \p nodeid identifies leaf-list, this is expected value of the leaf-list instance.
* @param[in] options Bitmask of options flags, see @ref pathoptions.
* @param[out] parsed Number of characters processed in \p id
* @return The closes parent (or the node itself) from the path
*/
struct lyd_node *
resolve_partial_json_data_nodeid(const char *nodeid, const char *llist_value, struct lyd_node *start, int options,
int *parsed)
{
const char *id, *mod_name, *name, *data_val, *llval;
int r, ret, mod_name_len, nam_len, is_relative = -1, list_instance_position;
int has_predicate, last_parsed = 0, llval_len;
struct lyd_node *sibling, *last_match = NULL;
struct lyd_node_leaf_list *llist;
const struct lys_module *prev_mod;
struct ly_ctx *ctx;
const struct lys_node *ssibling, *sparent;
struct lys_node_list *slist;
struct parsed_pred pp;
assert(nodeid && start && parsed);
memset(&pp, 0, sizeof pp);
ctx = start->schema->module->ctx;
id = nodeid;
/* parse first nodeid in case it is yang-data extension */
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, NULL, NULL, 1)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
goto error;
}
if (name[0] == '#') {
if (is_relative) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, '#', name);
goto error;
}
id += r;
last_parsed = r;
} else {
is_relative = -1;
}
/* parse first nodeid */
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
goto error;
}
id += r;
/* add it to parsed only after the data node was actually found */
last_parsed += r;
if (is_relative) {
prev_mod = lyd_node_module(start);
start = (start->schema->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_RPC | LYS_ACTION | LYS_NOTIF)) ? start->child : NULL;
} else {
for (; start->parent; start = start->parent);
prev_mod = lyd_node_module(start);
}
if (!start) {
/* there are no siblings to search */
return NULL;
}
/* do not duplicate code, use predicate parsing from the loop */
goto parse_predicates;
while (1) {
/* find the correct schema node first */
ssibling = NULL;
sparent = (start && start->parent) ? start->parent->schema : NULL;
while ((ssibling = lys_getnext(ssibling, sparent, prev_mod, 0))) {
/* skip invalid input/output nodes */
if (sparent && (sparent->nodetype & (LYS_RPC | LYS_ACTION))) {
if (options & LYD_PATH_OPT_OUTPUT) {
if (lys_parent(ssibling)->nodetype == LYS_INPUT) {
continue;
}
} else {
if (lys_parent(ssibling)->nodetype == LYS_OUTPUT) {
continue;
}
}
}
if (!schema_nodeid_siblingcheck(ssibling, prev_mod, mod_name, mod_name_len, name, nam_len)) {
break;
}
}
if (!ssibling) {
/* there is not even such a schema node */
free(pp.pred);
return last_match;
}
pp.schema = ssibling;
/* unify leaf-list value - it is possible to specify last-node value as both a predicate or parameter if
* is a leaf-list, unify both cases and the value will in both cases be in the predicate structure */
if (!id[0] && !pp.len && (ssibling->nodetype == LYS_LEAFLIST)) {
pp.len = 1;
pp.pred = calloc(1, sizeof *pp.pred);
LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error);
pp.pred[0].name = ".";
pp.pred[0].nam_len = 1;
pp.pred[0].value = (llist_value ? llist_value : "");
pp.pred[0].val_len = strlen(pp.pred[0].value);
}
if (ssibling->nodetype & (LYS_LEAFLIST | LYS_LEAF)) {
/* check leaf/leaf-list predicate */
if (pp.len > 1) {
LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL);
goto error;
} else if (pp.len) {
if ((pp.pred[0].name[0] != '.') || (pp.pred[0].nam_len != 1)) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, pp.pred[0].name[0], pp.pred[0].name);
goto error;
}
if ((((struct lys_node_leaf *)ssibling)->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[0].value, ':', pp.pred[0].val_len)) {
LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, ssibling, pp.pred[0].val_len, pp.pred[0].value);
goto error;
}
}
} else if (ssibling->nodetype == LYS_LIST) {
/* list should have predicates for all the keys or position */
slist = (struct lys_node_list *)ssibling;
if (!pp.len) {
/* none match */
return last_match;
} else if (!isdigit(pp.pred[0].name[0])) {
/* list predicate is not a position, so there must be all the keys */
if (pp.len > slist->keys_size) {
LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL);
goto error;
} else if (pp.len < slist->keys_size) {
LOGVAL(ctx, LYE_PATH_MISSKEY, LY_VLOG_NONE, NULL, slist->keys[pp.len]->name);
goto error;
}
/* check that all identityrefs have module name, otherwise the hash of the list instance will never match!! */
for (r = 0; r < pp.len; ++r) {
if ((slist->keys[r]->type.base == LY_TYPE_IDENT) && !strnchr(pp.pred[r].value, ':', pp.pred[r].val_len)) {
LOGVAL(ctx, LYE_PATH_INIDENTREF, LY_VLOG_LYS, slist->keys[r], pp.pred[r].val_len, pp.pred[r].value);
goto error;
}
}
}
} else if (pp.pred) {
/* no other nodes allow predicates */
LOGVAL(ctx, LYE_PATH_PREDTOOMANY, LY_VLOG_NONE, NULL);
goto error;
}
#ifdef LY_ENABLED_CACHE
/* we will not be matching keyless lists or state leaf-lists this way */
if (start->parent && start->parent->ht && ((pp.schema->nodetype != LYS_LIST) || ((struct lys_node_list *)pp.schema)->keys_size)
&& ((pp.schema->nodetype != LYS_LEAFLIST) || (pp.schema->flags & LYS_CONFIG_W))) {
sibling = resolve_json_data_node_hash(start->parent, pp);
} else
#endif
{
list_instance_position = 0;
LY_TREE_FOR(start, sibling) {
/* RPC/action data check, return simply invalid argument, because the data tree is invalid */
if (lys_parent(sibling->schema)) {
if (options & LYD_PATH_OPT_OUTPUT) {
if (lys_parent(sibling->schema)->nodetype == LYS_INPUT) {
LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC input nodes (%s).", sibling->schema->name);
goto error;
}
} else {
if (lys_parent(sibling->schema)->nodetype == LYS_OUTPUT) {
LOGERR(ctx, LY_EINVAL, "Provided data tree includes some RPC output nodes (%s).", sibling->schema->name);
goto error;
}
}
}
if (sibling->schema != ssibling) {
/* wrong schema node */
continue;
}
/* leaf-list, did we find it with the correct value or not? */
if (ssibling->nodetype == LYS_LEAFLIST) {
if (ssibling->flags & LYS_CONFIG_R) {
/* state leaf-lists will never match */
continue;
}
llist = (struct lyd_node_leaf_list *)sibling;
/* get the expected leaf-list value */
llval = NULL;
llval_len = 0;
if (pp.pred) {
/* it was already checked that it is correct */
llval = pp.pred[0].value;
llval_len = pp.pred[0].val_len;
}
/* make value canonical (remove module name prefix) unless it was specified with it */
if (llval && !strchr(llval, ':') && (llist->value_type & LY_TYPE_IDENT)
&& !strncmp(llist->value_str, lyd_node_module(sibling)->name, strlen(lyd_node_module(sibling)->name))
&& (llist->value_str[strlen(lyd_node_module(sibling)->name)] == ':')) {
data_val = llist->value_str + strlen(lyd_node_module(sibling)->name) + 1;
} else {
data_val = llist->value_str;
}
if ((!llval && data_val && data_val[0]) || (llval && (strncmp(llval, data_val, llval_len)
|| data_val[llval_len]))) {
continue;
}
} else if (ssibling->nodetype == LYS_LIST) {
/* list, we likely need predicates'n'stuff then, but if without a predicate, we are always creating it */
++list_instance_position;
ret = resolve_partial_json_data_list_predicate(pp, sibling, list_instance_position);
if (ret == -1) {
goto error;
} else if (ret == 1) {
/* this list instance does not match */
continue;
}
}
break;
}
}
/* no match, return last match */
if (!sibling) {
free(pp.pred);
return last_match;
}
/* we found a next matching node */
*parsed += last_parsed;
last_match = sibling;
prev_mod = lyd_node_module(sibling);
/* the result node? */
if (!id[0]) {
free(pp.pred);
return last_match;
}
/* move down the tree, if possible, and continue */
if (ssibling->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
/* there can be no children even through expected, error */
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
goto error;
} else if (!sibling->child) {
/* there could be some children, but are not, return what we found so far */
free(pp.pred);
return last_match;
}
start = sibling->child;
/* parse nodeid */
if ((r = parse_schema_nodeid(id, &mod_name, &mod_name_len, &name, &nam_len, &is_relative, &has_predicate, NULL, 0)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[-r], &id[-r]);
goto error;
}
id += r;
last_parsed = r;
parse_predicates:
/* parse all the predicates */
free(pp.pred);
pp.schema = NULL;
pp.len = 0;
pp.pred = NULL;
while (has_predicate) {
++pp.len;
pp.pred = ly_realloc(pp.pred, pp.len * sizeof *pp.pred);
LY_CHECK_ERR_GOTO(!pp.pred, LOGMEM(ctx), error);
if ((r = parse_schema_json_predicate(id, &pp.pred[pp.len - 1].mod_name, &pp.pred[pp.len - 1].mod_name_len,
&pp.pred[pp.len - 1].name, &pp.pred[pp.len - 1].nam_len, &pp.pred[pp.len - 1].value,
&pp.pred[pp.len - 1].val_len, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_PATH_INCHAR, LY_VLOG_NONE, NULL, id[0], id);
goto error;
}
id += r;
last_parsed += r;
}
}
error:
*parsed = -1;
free(pp.pred);
return NULL;
}
/**
* @brief Resolves length or range intervals. Does not log.
* Syntax is assumed to be correct, *ret MUST be NULL.
*
* @param[in] ctx Context for errors.
* @param[in] str_restr Restriction as a string.
* @param[in] type Type of the restriction.
* @param[out] ret Final interval structure that starts with
* the interval of the initial type, continues with intervals
* of any superior types derived from the initial one, and
* finishes with intervals from our \p type.
*
* @return EXIT_SUCCESS on succes, -1 on error.
*/
int
resolve_len_ran_interval(struct ly_ctx *ctx, const char *str_restr, struct lys_type *type, struct len_ran_intv **ret)
{
/* 0 - unsigned, 1 - signed, 2 - floating point */
int kind;
int64_t local_smin = 0, local_smax = 0, local_fmin, local_fmax;
uint64_t local_umin, local_umax = 0;
uint8_t local_fdig = 0;
const char *seg_ptr, *ptr;
struct len_ran_intv *local_intv = NULL, *tmp_local_intv = NULL, *tmp_intv, *intv = NULL;
switch (type->base) {
case LY_TYPE_BINARY:
kind = 0;
local_umin = 0;
local_umax = 18446744073709551615UL;
if (!str_restr && type->info.binary.length) {
str_restr = type->info.binary.length->expr;
}
break;
case LY_TYPE_DEC64:
kind = 2;
local_fmin = __INT64_C(-9223372036854775807) - __INT64_C(1);
local_fmax = __INT64_C(9223372036854775807);
local_fdig = type->info.dec64.dig;
if (!str_restr && type->info.dec64.range) {
str_restr = type->info.dec64.range->expr;
}
break;
case LY_TYPE_INT8:
kind = 1;
local_smin = __INT64_C(-128);
local_smax = __INT64_C(127);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_INT16:
kind = 1;
local_smin = __INT64_C(-32768);
local_smax = __INT64_C(32767);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_INT32:
kind = 1;
local_smin = __INT64_C(-2147483648);
local_smax = __INT64_C(2147483647);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_INT64:
kind = 1;
local_smin = __INT64_C(-9223372036854775807) - __INT64_C(1);
local_smax = __INT64_C(9223372036854775807);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT8:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(255);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT16:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(65535);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT32:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(4294967295);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_UINT64:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(18446744073709551615);
if (!str_restr && type->info.num.range) {
str_restr = type->info.num.range->expr;
}
break;
case LY_TYPE_STRING:
kind = 0;
local_umin = __UINT64_C(0);
local_umax = __UINT64_C(18446744073709551615);
if (!str_restr && type->info.str.length) {
str_restr = type->info.str.length->expr;
}
break;
default:
return -1;
}
/* process superior types */
if (type->der) {
if (resolve_len_ran_interval(ctx, NULL, &type->der->type, &intv)) {
return -1;
}
assert(!intv || (intv->kind == kind));
}
if (!str_restr) {
/* we do not have any restriction, return superior ones */
*ret = intv;
return EXIT_SUCCESS;
}
/* adjust local min and max */
if (intv) {
tmp_intv = intv;
if (kind == 0) {
local_umin = tmp_intv->value.uval.min;
} else if (kind == 1) {
local_smin = tmp_intv->value.sval.min;
} else if (kind == 2) {
local_fmin = tmp_intv->value.fval.min;
}
while (tmp_intv->next) {
tmp_intv = tmp_intv->next;
}
if (kind == 0) {
local_umax = tmp_intv->value.uval.max;
} else if (kind == 1) {
local_smax = tmp_intv->value.sval.max;
} else if (kind == 2) {
local_fmax = tmp_intv->value.fval.max;
}
}
/* finally parse our restriction */
seg_ptr = str_restr;
tmp_intv = NULL;
while (1) {
if (!tmp_local_intv) {
assert(!local_intv);
local_intv = malloc(sizeof *local_intv);
tmp_local_intv = local_intv;
} else {
tmp_local_intv->next = malloc(sizeof *tmp_local_intv);
tmp_local_intv = tmp_local_intv->next;
}
LY_CHECK_ERR_GOTO(!tmp_local_intv, LOGMEM(ctx), error);
tmp_local_intv->kind = kind;
tmp_local_intv->type = type;
tmp_local_intv->next = NULL;
/* min */
ptr = seg_ptr;
while (isspace(ptr[0])) {
++ptr;
}
if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) {
if (kind == 0) {
tmp_local_intv->value.uval.min = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 1) {
tmp_local_intv->value.sval.min = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 2) {
if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.min)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range");
goto error;
}
}
} else if (!strncmp(ptr, "min", 3)) {
if (kind == 0) {
tmp_local_intv->value.uval.min = local_umin;
} else if (kind == 1) {
tmp_local_intv->value.sval.min = local_smin;
} else if (kind == 2) {
tmp_local_intv->value.fval.min = local_fmin;
}
ptr += 3;
} else if (!strncmp(ptr, "max", 3)) {
if (kind == 0) {
tmp_local_intv->value.uval.min = local_umax;
} else if (kind == 1) {
tmp_local_intv->value.sval.min = local_smax;
} else if (kind == 2) {
tmp_local_intv->value.fval.min = local_fmax;
}
ptr += 3;
} else {
goto error;
}
while (isspace(ptr[0])) {
ptr++;
}
/* no interval or interval */
if ((ptr[0] == '|') || !ptr[0]) {
if (kind == 0) {
tmp_local_intv->value.uval.max = tmp_local_intv->value.uval.min;
} else if (kind == 1) {
tmp_local_intv->value.sval.max = tmp_local_intv->value.sval.min;
} else if (kind == 2) {
tmp_local_intv->value.fval.max = tmp_local_intv->value.fval.min;
}
} else if (!strncmp(ptr, "..", 2)) {
/* skip ".." */
ptr += 2;
while (isspace(ptr[0])) {
++ptr;
}
/* max */
if (isdigit(ptr[0]) || (ptr[0] == '+') || (ptr[0] == '-')) {
if (kind == 0) {
tmp_local_intv->value.uval.max = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 1) {
tmp_local_intv->value.sval.max = strtoll(ptr, (char **)&ptr, 10);
} else if (kind == 2) {
if (parse_range_dec64(&ptr, local_fdig, &tmp_local_intv->value.fval.max)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, ptr, "range");
goto error;
}
}
} else if (!strncmp(ptr, "max", 3)) {
if (kind == 0) {
tmp_local_intv->value.uval.max = local_umax;
} else if (kind == 1) {
tmp_local_intv->value.sval.max = local_smax;
} else if (kind == 2) {
tmp_local_intv->value.fval.max = local_fmax;
}
} else {
goto error;
}
} else {
goto error;
}
/* check min and max in correct order*/
if (kind == 0) {
/* current segment */
if (tmp_local_intv->value.uval.min > tmp_local_intv->value.uval.max) {
goto error;
}
if (tmp_local_intv->value.uval.min < local_umin || tmp_local_intv->value.uval.max > local_umax) {
goto error;
}
/* segments sholud be ascending order */
if (tmp_intv && (tmp_intv->value.uval.max >= tmp_local_intv->value.uval.min)) {
goto error;
}
} else if (kind == 1) {
if (tmp_local_intv->value.sval.min > tmp_local_intv->value.sval.max) {
goto error;
}
if (tmp_local_intv->value.sval.min < local_smin || tmp_local_intv->value.sval.max > local_smax) {
goto error;
}
if (tmp_intv && (tmp_intv->value.sval.max >= tmp_local_intv->value.sval.min)) {
goto error;
}
} else if (kind == 2) {
if (tmp_local_intv->value.fval.min > tmp_local_intv->value.fval.max) {
goto error;
}
if (tmp_local_intv->value.fval.min < local_fmin || tmp_local_intv->value.fval.max > local_fmax) {
goto error;
}
if (tmp_intv && (tmp_intv->value.fval.max >= tmp_local_intv->value.fval.min)) {
/* fraction-digits value is always the same (it cannot be changed in derived types) */
goto error;
}
}
/* next segment (next OR) */
seg_ptr = strchr(seg_ptr, '|');
if (!seg_ptr) {
break;
}
seg_ptr++;
tmp_intv = tmp_local_intv;
}
/* check local restrictions against superior ones */
if (intv) {
tmp_intv = intv;
tmp_local_intv = local_intv;
while (tmp_local_intv && tmp_intv) {
/* reuse local variables */
if (kind == 0) {
local_umin = tmp_local_intv->value.uval.min;
local_umax = tmp_local_intv->value.uval.max;
/* it must be in this interval */
if ((local_umin >= tmp_intv->value.uval.min) && (local_umin <= tmp_intv->value.uval.max)) {
/* this interval is covered, next one */
if (local_umax <= tmp_intv->value.uval.max) {
tmp_local_intv = tmp_local_intv->next;
continue;
/* ascending order of restrictions -> fail */
} else {
goto error;
}
}
} else if (kind == 1) {
local_smin = tmp_local_intv->value.sval.min;
local_smax = tmp_local_intv->value.sval.max;
if ((local_smin >= tmp_intv->value.sval.min) && (local_smin <= tmp_intv->value.sval.max)) {
if (local_smax <= tmp_intv->value.sval.max) {
tmp_local_intv = tmp_local_intv->next;
continue;
} else {
goto error;
}
}
} else if (kind == 2) {
local_fmin = tmp_local_intv->value.fval.min;
local_fmax = tmp_local_intv->value.fval.max;
if ((dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.min, local_fdig) > -1)
&& (dec64cmp(local_fmin, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1)) {
if (dec64cmp(local_fmax, local_fdig, tmp_intv->value.fval.max, local_fdig) < 1) {
tmp_local_intv = tmp_local_intv->next;
continue;
} else {
goto error;
}
}
}
tmp_intv = tmp_intv->next;
}
/* some interval left uncovered -> fail */
if (tmp_local_intv) {
goto error;
}
}
/* append the local intervals to all the intervals of the superior types, return it all */
if (intv) {
for (tmp_intv = intv; tmp_intv->next; tmp_intv = tmp_intv->next);
tmp_intv->next = local_intv;
} else {
intv = local_intv;
}
*ret = intv;
return EXIT_SUCCESS;
error:
while (intv) {
tmp_intv = intv->next;
free(intv);
intv = tmp_intv;
}
while (local_intv) {
tmp_local_intv = local_intv->next;
free(local_intv);
local_intv = tmp_local_intv;
}
return -1;
}
static int
resolve_superior_type_check(struct lys_type *type)
{
uint32_t i;
if (type->base == LY_TYPE_DER) {
/* check that the referenced typedef is resolved */
return EXIT_FAILURE;
} else if (type->base == LY_TYPE_UNION) {
/* check that all union types are resolved */
for (i = 0; i < type->info.uni.count; ++i) {
if (resolve_superior_type_check(&type->info.uni.types[i])) {
return EXIT_FAILURE;
}
}
} else if (type->base == LY_TYPE_LEAFREF) {
/* check there is path in some derived type */
while (!type->info.lref.path) {
assert(type->der);
type = &type->der->type;
}
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve a typedef, return only resolved typedefs if derived. If leafref, it must be
* resolved for this function to return it. Does not log.
*
* @param[in] name Typedef name.
* @param[in] mod_name Typedef name module name.
* @param[in] module Main module.
* @param[in] parent Parent of the resolved type definition.
* @param[out] ret Pointer to the resolved typedef. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
int
resolve_superior_type(const char *name, const char *mod_name, const struct lys_module *module,
const struct lys_node *parent, struct lys_tpdf **ret)
{
int i, j;
struct lys_tpdf *tpdf, *match;
int tpdf_size;
if (!mod_name) {
/* no prefix, try built-in types */
for (i = 1; i < LY_DATA_TYPE_COUNT; i++) {
if (!strcmp(ly_types[i]->name, name)) {
if (ret) {
*ret = ly_types[i];
}
return EXIT_SUCCESS;
}
}
} else {
if (!strcmp(mod_name, module->name)) {
/* prefix refers to the current module, ignore it */
mod_name = NULL;
}
}
if (!mod_name && parent) {
/* search in local typedefs */
while (parent) {
switch (parent->nodetype) {
case LYS_CONTAINER:
tpdf_size = ((struct lys_node_container *)parent)->tpdf_size;
tpdf = ((struct lys_node_container *)parent)->tpdf;
break;
case LYS_LIST:
tpdf_size = ((struct lys_node_list *)parent)->tpdf_size;
tpdf = ((struct lys_node_list *)parent)->tpdf;
break;
case LYS_GROUPING:
tpdf_size = ((struct lys_node_grp *)parent)->tpdf_size;
tpdf = ((struct lys_node_grp *)parent)->tpdf;
break;
case LYS_RPC:
case LYS_ACTION:
tpdf_size = ((struct lys_node_rpc_action *)parent)->tpdf_size;
tpdf = ((struct lys_node_rpc_action *)parent)->tpdf;
break;
case LYS_NOTIF:
tpdf_size = ((struct lys_node_notif *)parent)->tpdf_size;
tpdf = ((struct lys_node_notif *)parent)->tpdf;
break;
case LYS_INPUT:
case LYS_OUTPUT:
tpdf_size = ((struct lys_node_inout *)parent)->tpdf_size;
tpdf = ((struct lys_node_inout *)parent)->tpdf;
break;
default:
parent = lys_parent(parent);
continue;
}
for (i = 0; i < tpdf_size; i++) {
if (!strcmp(tpdf[i].name, name)) {
match = &tpdf[i];
goto check_typedef;
}
}
parent = lys_parent(parent);
}
} else {
/* get module where to search */
module = lyp_get_module(module, NULL, 0, mod_name, 0, 0);
if (!module) {
return -1;
}
}
/* search in top level typedefs */
for (i = 0; i < module->tpdf_size; i++) {
if (!strcmp(module->tpdf[i].name, name)) {
match = &module->tpdf[i];
goto check_typedef;
}
}
/* search in submodules */
for (i = 0; i < module->inc_size && module->inc[i].submodule; i++) {
for (j = 0; j < module->inc[i].submodule->tpdf_size; j++) {
if (!strcmp(module->inc[i].submodule->tpdf[j].name, name)) {
match = &module->inc[i].submodule->tpdf[j];
goto check_typedef;
}
}
}
return EXIT_FAILURE;
check_typedef:
if (resolve_superior_type_check(&match->type)) {
return EXIT_FAILURE;
}
if (ret) {
*ret = match;
}
return EXIT_SUCCESS;
}
/**
* @brief Check the default \p value of the \p type. Logs directly.
*
* @param[in] type Type definition to use.
* @param[in] value Default value to check.
* @param[in] module Type module.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
check_default(struct lys_type *type, const char **value, struct lys_module *module, int tpdf)
{
struct lys_tpdf *base_tpdf = NULL;
struct lyd_node_leaf_list node;
const char *dflt = NULL;
char *s;
int ret = EXIT_SUCCESS, r;
struct ly_ctx *ctx = module->ctx;
assert(value);
memset(&node, 0, sizeof node);
if (type->base <= LY_TYPE_DER) {
/* the type was not resolved yet, nothing to do for now */
ret = EXIT_FAILURE;
goto cleanup;
} else if (!tpdf && !module->implemented) {
/* do not check defaults in not implemented module's data */
goto cleanup;
} else if (tpdf && !module->implemented && type->base == LY_TYPE_IDENT) {
/* identityrefs are checked when instantiated in data instead of typedef,
* but in typedef the value has to be modified to include the prefix */
if (*value) {
if (strchr(*value, ':')) {
dflt = transform_schema2json(module, *value);
} else {
/* default prefix of the module where the typedef is defined */
if (asprintf(&s, "%s:%s", lys_main_module(module)->name, *value) == -1) {
LOGMEM(ctx);
ret = -1;
goto cleanup;
}
dflt = lydict_insert_zc(ctx, s);
}
lydict_remove(ctx, *value);
*value = dflt;
dflt = NULL;
}
goto cleanup;
} else if (type->base == LY_TYPE_LEAFREF && tpdf) {
/* leafref in typedef cannot be checked */
goto cleanup;
}
dflt = lydict_insert(ctx, *value, 0);
if (!dflt) {
/* we do not have a new default value, so is there any to check even, in some base type? */
for (base_tpdf = type->der; base_tpdf->type.der; base_tpdf = base_tpdf->type.der) {
if (base_tpdf->dflt) {
dflt = lydict_insert(ctx, base_tpdf->dflt, 0);
break;
}
}
if (!dflt) {
/* no default value, nothing to check, all is well */
goto cleanup;
}
/* so there is a default value in a base type, but can the default value be no longer valid (did we define some new restrictions)? */
switch (type->base) {
case LY_TYPE_IDENT:
if (lys_main_module(base_tpdf->type.parent->module)->implemented) {
goto cleanup;
} else {
/* check the default value from typedef, but use also the typedef's module
* due to possible searching in imported modules which is expected in
* typedef's module instead of module where the typedef is used */
module = base_tpdf->module;
}
break;
case LY_TYPE_INST:
case LY_TYPE_LEAFREF:
case LY_TYPE_BOOL:
case LY_TYPE_EMPTY:
/* these have no restrictions, so we would do the exact same work as the unres in the base typedef */
goto cleanup;
case LY_TYPE_BITS:
/* the default value must match the restricted list of values, if the type was restricted */
if (type->info.bits.count) {
break;
}
goto cleanup;
case LY_TYPE_ENUM:
/* the default value must match the restricted list of values, if the type was restricted */
if (type->info.enums.count) {
break;
}
goto cleanup;
case LY_TYPE_DEC64:
if (type->info.dec64.range) {
break;
}
goto cleanup;
case LY_TYPE_BINARY:
if (type->info.binary.length) {
break;
}
goto cleanup;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
if (type->info.num.range) {
break;
}
goto cleanup;
case LY_TYPE_STRING:
if (type->info.str.length || type->info.str.patterns) {
break;
}
goto cleanup;
case LY_TYPE_UNION:
/* way too much trouble learning whether we need to check the default again, so just do it */
break;
default:
LOGINT(ctx);
ret = -1;
goto cleanup;
}
} else if (type->base == LY_TYPE_EMPTY) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "default", type->parent->name);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The \"empty\" data type cannot have a default value.");
ret = -1;
goto cleanup;
}
/* dummy leaf */
memset(&node, 0, sizeof node);
node.value_str = lydict_insert(ctx, dflt, 0);
node.value_type = type->base;
if (tpdf) {
node.schema = calloc(1, sizeof (struct lys_node_leaf));
if (!node.schema) {
LOGMEM(ctx);
ret = -1;
goto cleanup;
}
r = asprintf((char **)&node.schema->name, "typedef-%s-default", ((struct lys_tpdf *)type->parent)->name);
if (r == -1) {
LOGMEM(ctx);
ret = -1;
goto cleanup;
}
node.schema->module = module;
memcpy(&((struct lys_node_leaf *)node.schema)->type, type, sizeof *type);
} else {
node.schema = (struct lys_node *)type->parent;
}
if (type->base == LY_TYPE_LEAFREF) {
if (!type->info.lref.target) {
ret = EXIT_FAILURE;
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Default value \"%s\" cannot be checked in an unresolved leafref.",
dflt);
goto cleanup;
}
ret = check_default(&type->info.lref.target->type, &dflt, module, 0);
if (!ret) {
/* adopt possibly changed default value to its canonical form */
if (*value) {
lydict_remove(ctx, *value);
*value = dflt;
dflt = NULL;
}
}
} else {
if (!lyp_parse_value(type, &node.value_str, NULL, &node, NULL, module, 1, 1, 0)) {
/* possible forward reference */
ret = EXIT_FAILURE;
if (base_tpdf) {
/* default value is defined in some base typedef */
if ((type->base == LY_TYPE_BITS && type->der->type.der) ||
(type->base == LY_TYPE_ENUM && type->der->type.der)) {
/* we have refined bits/enums */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL,
"Invalid value \"%s\" of the default statement inherited to \"%s\" from \"%s\" base type.",
dflt, type->parent->name, base_tpdf->name);
}
}
} else {
/* success - adopt canonical form from the node into the default value */
if (!ly_strequal(dflt, node.value_str, 1)) {
/* this can happen only if we have non-inherited default value,
* inherited default values are already in canonical form */
assert(ly_strequal(dflt, *value, 1));
lydict_remove(ctx, *value);
*value = node.value_str;
node.value_str = NULL;
}
}
}
cleanup:
lyd_free_value(node.value, node.value_type, node.value_flags, type, NULL, NULL, NULL);
lydict_remove(ctx, node.value_str);
if (tpdf && node.schema) {
free((char *)node.schema->name);
free(node.schema);
}
lydict_remove(ctx, dflt);
return ret;
}
/**
* @brief Check a key for mandatory attributes. Logs directly.
*
* @param[in] key The key to check.
* @param[in] flags What flags to check.
* @param[in] list The list of all the keys.
* @param[in] index Index of the key in the key list.
* @param[in] name The name of the keys.
* @param[in] len The name length.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
check_key(struct lys_node_list *list, int index, const char *name, int len)
{
struct lys_node_leaf *key = list->keys[index];
char *dup = NULL;
int j;
struct ly_ctx *ctx = list->module->ctx;
/* existence */
if (!key) {
if (name[len] != '\0') {
dup = strdup(name);
LY_CHECK_ERR_RETURN(!dup, LOGMEM(ctx), -1);
dup[len] = '\0';
name = dup;
}
LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, list, name);
free(dup);
return -1;
}
/* uniqueness */
for (j = index - 1; j >= 0; j--) {
if (key == list->keys[j]) {
LOGVAL(ctx, LYE_KEY_DUP, LY_VLOG_LYS, list, key->name);
return -1;
}
}
/* key is a leaf */
if (key->nodetype != LYS_LEAF) {
LOGVAL(ctx, LYE_KEY_NLEAF, LY_VLOG_LYS, list, key->name);
return -1;
}
/* type of the leaf is not built-in empty */
if (key->type.base == LY_TYPE_EMPTY && key->module->version < LYS_VERSION_1_1) {
LOGVAL(ctx, LYE_KEY_TYPE, LY_VLOG_LYS, list, key->name);
return -1;
}
/* config attribute is the same as of the list */
if ((key->flags & LYS_CONFIG_MASK) && (list->flags & LYS_CONFIG_MASK)
&& ((list->flags & LYS_CONFIG_MASK) != (key->flags & LYS_CONFIG_MASK))) {
LOGVAL(ctx, LYE_KEY_CONFIG, LY_VLOG_LYS, list, key->name);
return -1;
}
/* key is not placed from augment */
if (key->parent->nodetype == LYS_AUGMENT) {
LOGVAL(ctx, LYE_KEY_MISS, LY_VLOG_LYS, key, key->name);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key inserted from augment.");
return -1;
}
/* key is not when/if-feature -conditional */
j = 0;
if (key->when || (key->iffeature_size && (j = 1))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, key, j ? "if-feature" : "when", "leaf");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Key definition cannot depend on a \"%s\" condition.",
j ? "if-feature" : "when");
return -1;
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve (test the target exists) unique. Logs directly.
*
* @param[in] parent The parent node of the unique structure.
* @param[in] uniq_str_path One path from the unique string.
*
* @return EXIT_SUCCESS on succes, EXIT_FAILURE on forward reference, -1 on error.
*/
int
resolve_unique(struct lys_node *parent, const char *uniq_str_path, uint8_t *trg_type)
{
int rc;
const struct lys_node *leaf = NULL;
struct ly_ctx *ctx = parent->module->ctx;
rc = resolve_descendant_schema_nodeid(uniq_str_path, *lys_child(parent, LYS_LEAF), LYS_LEAF, 1, &leaf);
if (rc || !leaf) {
if (rc) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
if (rc > 0) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_PREV, NULL, uniq_str_path[rc - 1], &uniq_str_path[rc - 1]);
} else if (rc == -2) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Unique argument references list.");
}
rc = -1;
} else {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target leaf not found.");
rc = EXIT_FAILURE;
}
goto error;
}
if (leaf->nodetype != LYS_LEAF) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Target is not a leaf.");
return -1;
}
/* check status */
if (parent->nodetype != LYS_EXT && lyp_check_status(parent->flags, parent->module, parent->name,
leaf->flags, leaf->module, leaf->name, leaf)) {
return -1;
}
/* check that all unique's targets are of the same config type */
if (*trg_type) {
if (((*trg_type == 1) && (leaf->flags & LYS_CONFIG_R)) || ((*trg_type == 2) && (leaf->flags & LYS_CONFIG_W))) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, parent, uniq_str_path, "unique");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"Leaf \"%s\" referenced in unique statement is config %s, but previous referenced leaf is config %s.",
uniq_str_path, *trg_type == 1 ? "false" : "true", *trg_type == 1 ? "true" : "false");
return -1;
}
} else {
/* first unique */
if (leaf->flags & LYS_CONFIG_W) {
*trg_type = 1;
} else {
*trg_type = 2;
}
}
/* set leaf's unique flag */
((struct lys_node_leaf *)leaf)->flags |= LYS_UNIQUE;
return EXIT_SUCCESS;
error:
return rc;
}
void
unres_data_del(struct unres_data *unres, uint32_t i)
{
/* there are items after the one deleted */
if (i+1 < unres->count) {
/* we only move the data, memory is left allocated, why bother */
memmove(&unres->node[i], &unres->node[i+1], (unres->count-(i+1)) * sizeof *unres->node);
/* deleting the last item */
} else if (i == 0) {
free(unres->node);
unres->node = NULL;
}
/* if there are no items after and it is not the last one, just move the counter */
--unres->count;
}
/**
* @brief Resolve (find) a data node from a specific module. Does not log.
*
* @param[in] mod Module to search in.
* @param[in] name Name of the data node.
* @param[in] nam_len Length of the name.
* @param[in] start Data node to start the search from.
* @param[in,out] parents Resolved nodes. If there are some parents,
* they are replaced (!!) with the resolvents.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_data(const struct lys_module *mod, const char *name, int nam_len, struct lyd_node *start, struct unres_data *parents)
{
struct lyd_node *node;
int flag;
uint32_t i;
if (!parents->count) {
parents->count = 1;
parents->node = malloc(sizeof *parents->node);
LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), -1);
parents->node[0] = NULL;
}
for (i = 0; i < parents->count;) {
if (parents->node[i] && (parents->node[i]->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
/* skip */
++i;
continue;
}
flag = 0;
LY_TREE_FOR(parents->node[i] ? parents->node[i]->child : start, node) {
if (lyd_node_module(node) == mod && !strncmp(node->schema->name, name, nam_len)
&& node->schema->name[nam_len] == '\0') {
/* matching target */
if (!flag) {
/* put node instead of the current parent */
parents->node[i] = node;
flag = 1;
} else {
/* multiple matching, so create a new node */
++parents->count;
parents->node = ly_realloc(parents->node, parents->count * sizeof *parents->node);
LY_CHECK_ERR_RETURN(!parents->node, LOGMEM(mod->ctx), EXIT_FAILURE);
parents->node[parents->count-1] = node;
++i;
}
}
}
if (!flag) {
/* remove item from the parents list */
unres_data_del(parents, i);
} else {
++i;
}
}
return parents->count ? EXIT_SUCCESS : EXIT_FAILURE;
}
static int
resolve_schema_leafref_valid_dep_flag(const struct lys_node *op_node, const struct lys_module *local_mod,
const struct lys_node *first_node, int abs_path)
{
int dep1, dep2;
const struct lys_node *node;
if (!op_node) {
/* leafref pointing to a different module */
if (local_mod != lys_node_module(first_node)) {
return 1;
}
} else if (lys_parent(op_node)) {
/* inner operation (notif/action) */
if (abs_path) {
return 1;
} else {
/* compare depth of both nodes */
for (dep1 = 0, node = op_node; lys_parent(node); node = lys_parent(node));
for (dep2 = 0, node = first_node; lys_parent(node); node = lys_parent(node));
if ((dep2 > dep1) || ((dep2 == dep1) && (op_node != first_node))) {
return 1;
}
}
} else {
/* top-level operation (notif/rpc) */
if (op_node != first_node) {
return 1;
}
}
return 0;
}
/**
* @brief Resolve a path (leafref) predicate in JSON schema context. Logs directly.
*
* @param[in] path Path to use.
* @param[in] context_node Predicate context node (where the predicate is placed).
* @param[in] parent Path context node (where the path begins/is placed).
* @param[in] op_node Optional node if the leafref is in an operation (action/rpc/notif).
*
* @return 0 on forward reference, otherwise the number
* of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
resolve_schema_leafref_predicate(const char *path, const struct lys_node *context_node, struct lys_node *parent)
{
const struct lys_module *trg_mod;
const struct lys_node *src_node, *dst_node;
const char *path_key_expr, *source, *sour_pref, *dest, *dest_pref;
int pke_len, sour_len, sour_pref_len, dest_len, dest_pref_len, pke_parsed, parsed = 0;
int has_predicate, dest_parent_times, i, rc;
struct ly_ctx *ctx = context_node->module->ctx;
do {
if ((i = parse_path_predicate(path, &sour_pref, &sour_pref_len, &source, &sour_len, &path_key_expr,
&pke_len, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path[-i], path-i);
return -parsed+i;
}
parsed += i;
path += i;
/* source (must be leaf) */
if (sour_pref) {
trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, sour_pref, sour_pref_len, 0);
} else {
trg_mod = lys_node_module(parent);
}
rc = lys_getnext_data(trg_mod, context_node, source, sour_len, LYS_LEAF | LYS_LEAFLIST, LYS_GETNEXT_NOSTATECHECK,
&src_node);
if (rc) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path-parsed);
return 0;
}
/* destination */
dest_parent_times = 0;
pke_parsed = 0;
if ((i = parse_path_key_expr(path_key_expr, &dest_pref, &dest_pref_len, &dest, &dest_len,
&dest_parent_times)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, path_key_expr[-i], path_key_expr-i);
return -parsed;
}
pke_parsed += i;
for (i = 0, dst_node = parent; i < dest_parent_times; ++i) {
if (!dst_node) {
/* we went too much into parents, there is no parent anymore */
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr);
return 0;
}
if (dst_node->parent && (dst_node->parent->nodetype == LYS_AUGMENT)
&& !((struct lys_node_augment *)dst_node->parent)->target) {
/* we are in an unresolved augment, cannot evaluate */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, dst_node->parent,
"Cannot resolve leafref predicate \"%s\" because it is in an unresolved augment.", path_key_expr);
return 0;
}
/* path is supposed to be evaluated in data tree, so we have to skip
* all schema nodes that cannot be instantiated in data tree */
for (dst_node = lys_parent(dst_node);
dst_node && !(dst_node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC));
dst_node = lys_parent(dst_node));
}
while (1) {
if (dest_pref) {
trg_mod = lyp_get_module(lys_node_module(parent), NULL, 0, dest_pref, dest_pref_len, 0);
} else {
trg_mod = lys_node_module(parent);
}
rc = lys_getnext_data(trg_mod, dst_node, dest, dest_len, LYS_CONTAINER | LYS_LIST | LYS_LEAF,
LYS_GETNEXT_NOSTATECHECK, &dst_node);
if (rc) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path_key_expr);
return 0;
}
if (pke_len == pke_parsed) {
break;
}
if ((i = parse_path_key_expr(path_key_expr + pke_parsed, &dest_pref, &dest_pref_len, &dest, &dest_len,
&dest_parent_times)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent,
(path_key_expr + pke_parsed)[-i], (path_key_expr + pke_parsed)-i);
return -parsed;
}
pke_parsed += i;
}
/* check source - dest match */
if (dst_node->nodetype != src_node->nodetype) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref predicate", path - parsed);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Destination node is not a %s, but a %s.",
strnodetype(src_node->nodetype), strnodetype(dst_node->nodetype));
return -parsed;
}
} while (has_predicate);
return parsed;
}
static int
check_leafref_features(struct lys_type *type)
{
struct lys_node *iter;
struct ly_set *src_parents, *trg_parents, *features;
struct lys_node_augment *aug;
struct ly_ctx *ctx = ((struct lys_tpdf *)type->parent)->module->ctx;
unsigned int i, j, size, x;
int ret = EXIT_SUCCESS;
assert(type->parent);
src_parents = ly_set_new();
trg_parents = ly_set_new();
features = ly_set_new();
/* get parents chain of source (leafref) */
for (iter = (struct lys_node *)type->parent; iter; iter = lys_parent(iter)) {
if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) {
continue;
}
if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) {
aug = (struct lys_node_augment *)iter->parent;
if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) {
/* unresolved augment, wait until it's resolved */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug,
"Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path);
ret = EXIT_FAILURE;
goto cleanup;
}
/* also add this augment */
ly_set_add(src_parents, aug, LY_SET_OPT_USEASLIST);
}
ly_set_add(src_parents, iter, LY_SET_OPT_USEASLIST);
}
/* get parents chain of target */
for (iter = (struct lys_node *)type->info.lref.target; iter; iter = lys_parent(iter)) {
if (iter->nodetype & (LYS_INPUT | LYS_OUTPUT)) {
continue;
}
if (iter->parent && (iter->parent->nodetype == LYS_AUGMENT)) {
aug = (struct lys_node_augment *)iter->parent;
if ((aug->module->implemented && (aug->flags & LYS_NOTAPPLIED)) || !aug->target) {
/* unresolved augment, wait until it's resolved */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, aug,
"Cannot check leafref \"%s\" if-feature consistency because of an unresolved augment.", type->info.lref.path);
ret = EXIT_FAILURE;
goto cleanup;
}
}
ly_set_add(trg_parents, iter, LY_SET_OPT_USEASLIST);
}
/* compare the features used in if-feature statements in the rest of both
* chains of parents. The set of features used for target must be a subset
* of features used for the leafref. This is not a perfect, we should compare
* the truth tables but it could require too much resources, so we simplify that */
for (i = 0; i < src_parents->number; i++) {
iter = src_parents->set.s[i]; /* shortcut */
if (!iter->iffeature_size) {
continue;
}
for (j = 0; j < iter->iffeature_size; j++) {
resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size);
for (; size; size--) {
if (!iter->iffeature[j].features[size - 1]) {
/* not yet resolved feature, postpone this check */
ret = EXIT_FAILURE;
goto cleanup;
}
ly_set_add(features, iter->iffeature[j].features[size - 1], 0);
}
}
}
x = features->number;
for (i = 0; i < trg_parents->number; i++) {
iter = trg_parents->set.s[i]; /* shortcut */
if (!iter->iffeature_size) {
continue;
}
for (j = 0; j < iter->iffeature_size; j++) {
resolve_iffeature_getsizes(&iter->iffeature[j], NULL, &size);
for (; size; size--) {
if (!iter->iffeature[j].features[size - 1]) {
/* not yet resolved feature, postpone this check */
ret = EXIT_FAILURE;
goto cleanup;
}
if ((unsigned)ly_set_add(features, iter->iffeature[j].features[size - 1], 0) >= x) {
/* the feature is not present in features set of target's parents chain */
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, type->parent, "leafref", type->info.lref.path);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"Leafref is not conditional based on \"%s\" feature as its target.",
iter->iffeature[j].features[size - 1]->name);
ret = -1;
goto cleanup;
}
}
}
}
cleanup:
ly_set_free(features);
ly_set_free(src_parents);
ly_set_free(trg_parents);
return ret;
}
/**
* @brief Resolve a path (leafref) in JSON schema context. Logs directly.
*
* @param[in] path Path to use.
* @param[in] parent_node Parent of the leafref.
* @param[out] ret Pointer to the resolved schema node. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_schema_leafref(struct lys_type *type, struct lys_node *parent, struct unres_schema *unres)
{
const struct lys_node *node, *op_node = NULL, *tmp_parent;
struct lys_node_augment *last_aug;
const struct lys_module *tmp_mod, *cur_module;
const char *id, *prefix, *name;
int pref_len, nam_len, parent_times, has_predicate;
int i, first_iter;
struct ly_ctx *ctx = parent->module->ctx;
if (!type->info.lref.target) {
first_iter = 1;
parent_times = 0;
id = type->info.lref.path;
/* find operation schema we are in */
for (op_node = lys_parent(parent);
op_node && !(op_node->nodetype & (LYS_ACTION | LYS_NOTIF | LYS_RPC));
op_node = lys_parent(op_node));
cur_module = lys_node_module(parent);
do {
if ((i = parse_path_arg(cur_module, id, &prefix, &pref_len, &name, &nam_len, &parent_times, &has_predicate)) < 1) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, parent, id[-i], &id[-i]);
return -1;
}
id += i;
/* get the current module */
tmp_mod = prefix ? lyp_get_module(cur_module, NULL, 0, prefix, pref_len, 0) : cur_module;
if (!tmp_mod) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return EXIT_FAILURE;
}
last_aug = NULL;
if (first_iter) {
if (parent_times == -1) {
/* use module data */
node = NULL;
} else if (parent_times > 0) {
/* we are looking for the right parent */
for (i = 0, node = parent; i < parent_times; i++) {
if (node->parent && (node->parent->nodetype == LYS_AUGMENT)
&& !((struct lys_node_augment *)node->parent)->target) {
/* we are in an unresolved augment, cannot evaluate */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, node->parent,
"Cannot resolve leafref \"%s\" because it is in an unresolved augment.", type->info.lref.path);
return EXIT_FAILURE;
}
/* path is supposed to be evaluated in data tree, so we have to skip
* all schema nodes that cannot be instantiated in data tree */
for (node = lys_parent(node);
node && !(node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_ACTION | LYS_NOTIF | LYS_RPC));
node = lys_parent(node));
if (!node) {
if (i == parent_times - 1) {
/* top-level */
break;
}
/* higher than top-level */
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return EXIT_FAILURE;
}
}
} else {
LOGINT(ctx);
return -1;
}
}
/* find the next node (either in unconnected augment or as a schema sibling, node is NULL for top-level node -
* - useless to search for that in augments) */
if (!tmp_mod->implemented && node) {
get_next_augment:
last_aug = lys_getnext_target_aug(last_aug, tmp_mod, node);
}
tmp_parent = (last_aug ? (struct lys_node *)last_aug : node);
node = NULL;
while ((node = lys_getnext(node, tmp_parent, tmp_mod, LYS_GETNEXT_NOSTATECHECK))) {
if (lys_node_module(node) != lys_main_module(tmp_mod)) {
continue;
}
if (strncmp(node->name, name, nam_len) || node->name[nam_len]) {
continue;
}
/* match */
break;
}
if (!node) {
if (last_aug) {
/* restore the correct augment target */
node = last_aug->target;
goto get_next_augment;
}
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return EXIT_FAILURE;
}
if (first_iter) {
/* set external dependency flag, we can decide based on the first found node */
if (resolve_schema_leafref_valid_dep_flag(op_node, cur_module, node, (parent_times == -1 ? 1 : 0))) {
parent->flags |= LYS_LEAFREF_DEP;
}
first_iter = 0;
}
if (has_predicate) {
/* we have predicate, so the current result must be list */
if (node->nodetype != LYS_LIST) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
return -1;
}
i = resolve_schema_leafref_predicate(id, node, parent);
if (!i) {
return EXIT_FAILURE;
} else if (i < 0) {
return -1;
}
id += i;
has_predicate = 0;
}
} while (id[0]);
/* the target must be leaf or leaf-list (in YANG 1.1 only) */
if ((node->nodetype != LYS_LEAF) && (node->nodetype != LYS_LEAFLIST)) {
LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_LYS, parent, "leafref", type->info.lref.path);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Leafref target \"%s\" is not a leaf nor a leaf-list.", type->info.lref.path);
return -1;
}
/* check status */
if (lyp_check_status(parent->flags, parent->module, parent->name,
node->flags, node->module, node->name, node)) {
return -1;
}
/* assign */
type->info.lref.target = (struct lys_node_leaf *)node;
}
/* as the last thing traverse this leafref and make targets on the path implemented */
if (lys_node_module(parent)->implemented) {
/* make all the modules in the path implemented */
for (node = (struct lys_node *)type->info.lref.target; node; node = lys_parent(node)) {
if (!lys_node_module(node)->implemented) {
lys_node_module(node)->implemented = 1;
if (unres_schema_add_node(lys_node_module(node), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
}
/* store the backlink from leafref target */
if (lys_leaf_add_leafref_target(type->info.lref.target, (struct lys_node *)type->parent)) {
return -1;
}
}
/* check if leafref and its target are under common if-features */
return check_leafref_features(type);
}
/**
* @brief Compare 2 data node values.
*
* Comparison performed on canonical forms, the first value
* is first transformed into canonical form.
*
* @param[in] node Leaf/leaf-list with these values.
* @param[in] noncan_val Non-canonical value.
* @param[in] noncan_val_len Length of \p noncal_val.
* @param[in] can_val Canonical value.
* @return 1 if equal, 0 if not, -1 on error (logged).
*/
static int
valequal(struct lys_node *node, const char *noncan_val, int noncan_val_len, const char *can_val)
{
int ret;
struct lyd_node_leaf_list leaf;
struct lys_node_leaf *sleaf = (struct lys_node_leaf*)node;
/* dummy leaf */
memset(&leaf, 0, sizeof leaf);
leaf.value_str = lydict_insert(node->module->ctx, noncan_val, noncan_val_len);
repeat:
leaf.value_type = sleaf->type.base;
leaf.schema = node;
if (leaf.value_type == LY_TYPE_LEAFREF) {
if (!sleaf->type.info.lref.target) {
/* it should either be unresolved leafref (leaf.value_type are ORed flags) or it will be resolved */
LOGINT(node->module->ctx);
ret = -1;
goto finish;
}
sleaf = sleaf->type.info.lref.target;
goto repeat;
} else {
if (!lyp_parse_value(&sleaf->type, &leaf.value_str, NULL, &leaf, NULL, NULL, 0, 0, 0)) {
ret = -1;
goto finish;
}
}
if (!strcmp(leaf.value_str, can_val)) {
ret = 1;
} else {
ret = 0;
}
finish:
lydict_remove(node->module->ctx, leaf.value_str);
return ret;
}
/**
* @brief Resolve instance-identifier predicate in JSON data format.
* Does not log.
*
* @param[in] prev_mod Previous module to use in case there is no prefix.
* @param[in] pred Predicate to use.
* @param[in,out] node Node matching the restriction without
* the predicate. If it does not satisfy the predicate,
* it is set to NULL.
*
* @return Number of characters successfully parsed,
* positive on success, negative on failure.
*/
static int
resolve_instid_predicate(const struct lys_module *prev_mod, const char *pred, struct lyd_node **node, int cur_idx)
{
/* ... /node[key=value] ... */
struct lyd_node_leaf_list *key;
struct lys_node_leaf **list_keys = NULL;
struct lys_node_list *slist = NULL;
const char *model, *name, *value;
int mod_len, nam_len, val_len, i, has_predicate, parsed;
struct ly_ctx *ctx = prev_mod->ctx;
assert(pred && node && *node);
parsed = 0;
do {
if ((i = parse_predicate(pred + parsed, &model, &mod_len, &name, &nam_len, &value, &val_len, &has_predicate)) < 1) {
return -parsed + i;
}
parsed += i;
if (!(*node)) {
/* just parse it all */
continue;
}
/* target */
if (name[0] == '.') {
/* leaf-list value */
if ((*node)->schema->nodetype != LYS_LEAFLIST) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects leaf-list, but have %s \"%s\".",
strnodetype((*node)->schema->nodetype), (*node)->schema->name);
parsed = -1;
goto cleanup;
}
/* check the value */
if (!valequal((*node)->schema, value, val_len, ((struct lyd_node_leaf_list *)*node)->value_str)) {
*node = NULL;
goto cleanup;
}
} else if (isdigit(name[0])) {
assert(!value);
/* keyless list position */
if ((*node)->schema->nodetype != LYS_LIST) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".",
strnodetype((*node)->schema->nodetype), (*node)->schema->name);
parsed = -1;
goto cleanup;
}
if (((struct lys_node_list *)(*node)->schema)->keys) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list without keys, but have list \"%s\".",
(*node)->schema->name);
parsed = -1;
goto cleanup;
}
/* check the index */
if (atoi(name) != cur_idx) {
*node = NULL;
goto cleanup;
}
} else {
/* list key value */
if ((*node)->schema->nodetype != LYS_LIST) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list, but have %s \"%s\".",
strnodetype((*node)->schema->nodetype), (*node)->schema->name);
parsed = -1;
goto cleanup;
}
slist = (struct lys_node_list *)(*node)->schema;
/* prepare key array */
if (!list_keys) {
list_keys = malloc(slist->keys_size * sizeof *list_keys);
LY_CHECK_ERR_RETURN(!list_keys, LOGMEM(ctx), -1);
for (i = 0; i < slist->keys_size; ++i) {
list_keys[i] = slist->keys[i];
}
}
/* find the schema key leaf */
for (i = 0; i < slist->keys_size; ++i) {
if (list_keys[i] && !strncmp(list_keys[i]->name, name, nam_len) && !list_keys[i]->name[nam_len]) {
break;
}
}
if (i == slist->keys_size) {
/* this list has no such key */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects list with the key \"%.*s\","
" but list \"%s\" does not define it.", nam_len, name, slist->name);
parsed = -1;
goto cleanup;
}
/* check module */
if (model) {
if (strncmp(list_keys[i]->module->name, model, mod_len) || list_keys[i]->module->name[mod_len]) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%.*s\", not \"%s\".",
list_keys[i]->name, model, mod_len, list_keys[i]->module->name);
parsed = -1;
goto cleanup;
}
} else {
if (list_keys[i]->module != prev_mod) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier expects key \"%s\" from module \"%s\", not \"%s\".",
list_keys[i]->name, prev_mod->name, list_keys[i]->module->name);
parsed = -1;
goto cleanup;
}
}
/* find the actual data key */
for (key = (struct lyd_node_leaf_list *)(*node)->child; key; key = (struct lyd_node_leaf_list *)key->next) {
if (key->schema == (struct lys_node *)list_keys[i]) {
break;
}
}
if (!key) {
/* list instance is missing a key? definitely should not happen */
LOGINT(ctx);
parsed = -1;
goto cleanup;
}
/* check the value */
if (!valequal(key->schema, value, val_len, key->value_str)) {
*node = NULL;
/* we still want to parse the whole predicate */
continue;
}
/* everything is fine, mark this key as resolved */
list_keys[i] = NULL;
}
} while (has_predicate);
/* check that all list keys were specified */
if (*node && list_keys) {
for (i = 0; i < slist->keys_size; ++i) {
if (list_keys[i]) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Instance identifier is missing list key \"%s\".", list_keys[i]->name);
parsed = -1;
goto cleanup;
}
}
}
cleanup:
free(list_keys);
return parsed;
}
static int
check_xpath(struct lys_node *node, int check_place)
{
struct lys_node *parent;
struct lyxp_set set;
enum int_log_opts prev_ilo;
if (check_place) {
parent = node;
while (parent) {
if (parent->nodetype == LYS_GROUPING) {
/* unresolved grouping, skip for now (will be checked later) */
return EXIT_SUCCESS;
}
if (parent->nodetype == LYS_AUGMENT) {
if (!((struct lys_node_augment *)parent)->target) {
/* unresolved augment, skip for now (will be checked later) */
return EXIT_FAILURE;
} else {
parent = ((struct lys_node_augment *)parent)->target;
continue;
}
}
parent = parent->parent;
}
}
memset(&set, 0, sizeof set);
/* produce just warnings */
ly_ilo_change(NULL, ILO_ERR2WRN, &prev_ilo, NULL);
lyxp_node_atomize(node, &set, 1);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (set.val.snodes) {
free(set.val.snodes);
}
return EXIT_SUCCESS;
}
static int
check_leafref_config(struct lys_node_leaf *leaf, struct lys_type *type)
{
unsigned int i;
if (type->base == LY_TYPE_LEAFREF) {
if ((leaf->flags & LYS_CONFIG_W) && type->info.lref.target && type->info.lref.req != -1 &&
(type->info.lref.target->flags & LYS_CONFIG_R)) {
LOGVAL(leaf->module->ctx, LYE_SPEC, LY_VLOG_LYS, leaf, "The leafref %s is config but refers to a non-config %s.",
strnodetype(leaf->nodetype), strnodetype(type->info.lref.target->nodetype));
return -1;
}
/* we can skip the test in case the leafref is not yet resolved. In that case the test is done in the time
* of leafref resolving (lys_leaf_add_leafref_target()) */
} else if (type->base == LY_TYPE_UNION) {
for (i = 0; i < type->info.uni.count; i++) {
if (check_leafref_config(leaf, &type->info.uni.types[i])) {
return -1;
}
}
}
return 0;
}
/**
* @brief Passes config flag down to children, skips nodes without config flags.
* Logs.
*
* @param[in] node Siblings and their children to have flags changed.
* @param[in] clear Flag to clear all config flags if parent is LYS_NOTIF, LYS_INPUT, LYS_OUTPUT, LYS_RPC.
* @param[in] flags Flags to assign to all the nodes.
* @param[in,out] unres List of unresolved items.
*
* @return 0 on success, -1 on error.
*/
int
inherit_config_flag(struct lys_node *node, int flags, int clear)
{
struct lys_node_leaf *leaf;
struct ly_ctx *ctx;
if (!node) {
return 0;
}
assert(!(flags ^ (flags & LYS_CONFIG_MASK)));
ctx = node->module->ctx;
LY_TREE_FOR(node, node) {
if (clear) {
node->flags &= ~LYS_CONFIG_MASK;
node->flags &= ~LYS_CONFIG_SET;
} else {
if (node->flags & LYS_CONFIG_SET) {
/* skip nodes with an explicit config value */
if ((flags & LYS_CONFIG_R) && (node->flags & LYS_CONFIG_W)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, node, "true", "config");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children.");
return -1;
}
continue;
}
if (!(node->nodetype & (LYS_USES | LYS_GROUPING))) {
node->flags = (node->flags & ~LYS_CONFIG_MASK) | flags;
/* check that configuration lists have keys */
if ((node->nodetype == LYS_LIST) && (node->flags & LYS_CONFIG_W)
&& !((struct lys_node_list *)node)->keys_size) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, node, "key", "list");
return -1;
}
}
}
if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
if (inherit_config_flag(node->child, flags, clear)) {
return -1;
}
} else if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
leaf = (struct lys_node_leaf *)node;
if (check_leafref_config(leaf, &leaf->type)) {
return -1;
}
}
}
return 0;
}
/**
* @brief Resolve augment target. Logs directly.
*
* @param[in] aug Augment to use.
* @param[in] uses Parent where to start the search in. If set, uses augment, if not, standalone augment.
* @param[in,out] unres List of unresolved items.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_augment(struct lys_node_augment *aug, struct lys_node *uses, struct unres_schema *unres)
{
int rc;
struct lys_node *sub;
struct lys_module *mod;
struct ly_set *set;
struct ly_ctx *ctx;
assert(aug);
mod = lys_main_module(aug->module);
ctx = mod->ctx;
/* set it as not applied for now */
aug->flags |= LYS_NOTAPPLIED;
/* it can already be resolved in case we returned EXIT_FAILURE from if block below */
if (!aug->target) {
/* resolve target node */
rc = resolve_schema_nodeid(aug->target_name, uses, (uses ? NULL : lys_node_module((struct lys_node *)aug)), &set, 0, 0);
if (rc == -1) {
LOGVAL(ctx, LYE_PATH, LY_VLOG_LYS, aug);
return -1;
}
if (!set) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, aug, "augment", aug->target_name);
return EXIT_FAILURE;
}
aug->target = set->set.s[0];
ly_set_free(set);
}
/* make this module implemented if the target module is (if the target is in an unimplemented module,
* it is fine because when we will be making that module implemented, its augment will be applied
* and that augment target module made implemented, recursively) */
if (mod->implemented && !lys_node_module(aug->target)->implemented) {
lys_node_module(aug->target)->implemented = 1;
if (unres_schema_add_node(lys_node_module(aug->target), unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
/* check for mandatory nodes - if the target node is in another module
* the added nodes cannot be mandatory
*/
if (!aug->parent && (lys_node_module((struct lys_node *)aug) != lys_node_module(aug->target))
&& (rc = lyp_check_mandatory_augment(aug, aug->target))) {
return rc;
}
/* check augment target type and then augment nodes type */
if (aug->target->nodetype & (LYS_CONTAINER | LYS_LIST)) {
LY_TREE_FOR(aug->child, sub) {
if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES
| LYS_CHOICE | LYS_ACTION | LYS_NOTIF))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".",
strnodetype(aug->target->nodetype), strnodetype(sub->nodetype));
return -1;
}
}
} else if (aug->target->nodetype & (LYS_CASE | LYS_INPUT | LYS_OUTPUT | LYS_NOTIF)) {
LY_TREE_FOR(aug->child, sub) {
if (!(sub->nodetype & (LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_USES | LYS_CHOICE))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".",
strnodetype(aug->target->nodetype), strnodetype(sub->nodetype));
return -1;
}
}
} else if (aug->target->nodetype == LYS_CHOICE) {
LY_TREE_FOR(aug->child, sub) {
if (!(sub->nodetype & (LYS_CASE | LYS_ANYDATA | LYS_CONTAINER | LYS_LEAF | LYS_LIST | LYS_LEAFLIST))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, aug, strnodetype(sub->nodetype), "augment");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Cannot augment \"%s\" with a \"%s\".",
strnodetype(aug->target->nodetype), strnodetype(sub->nodetype));
return -1;
}
}
} else {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, aug, aug->target_name, "target-node");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid augment target node type \"%s\".", strnodetype(aug->target->nodetype));
return -1;
}
/* check identifier uniqueness as in lys_node_addchild() */
LY_TREE_FOR(aug->child, sub) {
if (lys_check_id(sub, aug->target, NULL)) {
return -1;
}
}
if (!aug->child) {
/* empty augment, nothing to connect, but it is techincally applied */
LOGWRN(ctx, "Augment \"%s\" without children.", aug->target_name);
aug->flags &= ~LYS_NOTAPPLIED;
} else if ((aug->parent || mod->implemented) && apply_aug(aug, unres)) {
/* we try to connect the augment only in case the module is implemented or
* the augment applies on the used grouping, anyway we failed here */
return -1;
}
return EXIT_SUCCESS;
}
static int
resolve_extension(struct unres_ext *info, struct lys_ext_instance **ext, struct unres_schema *unres)
{
enum LY_VLOG_ELEM vlog_type;
void *vlog_node;
unsigned int i, j;
struct lys_ext *e;
char *ext_name, *ext_prefix, *tmp;
struct lyxml_elem *next_yin, *yin;
const struct lys_module *mod;
struct lys_ext_instance *tmp_ext;
struct ly_ctx *ctx = NULL;
LYEXT_TYPE etype;
switch (info->parent_type) {
case LYEXT_PAR_NODE:
vlog_node = info->parent;
vlog_type = LY_VLOG_LYS;
break;
case LYEXT_PAR_MODULE:
case LYEXT_PAR_IMPORT:
case LYEXT_PAR_INCLUDE:
vlog_node = NULL;
vlog_type = LY_VLOG_LYS;
break;
default:
vlog_node = NULL;
vlog_type = LY_VLOG_NONE;
break;
}
if (info->datatype == LYS_IN_YIN) {
/* YIN */
/* get the module where the extension is supposed to be defined */
mod = lyp_get_import_module_ns(info->mod, info->data.yin->ns->value);
if (!mod) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name);
return EXIT_FAILURE;
}
ctx = mod->ctx;
/* find the extension definition */
e = NULL;
for (i = 0; i < mod->extensions_size; i++) {
if (ly_strequal(mod->extensions[i].name, info->data.yin->name, 1)) {
e = &mod->extensions[i];
break;
}
}
/* try submodules */
for (j = 0; !e && j < mod->inc_size; j++) {
for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) {
if (ly_strequal(mod->inc[j].submodule->extensions[i].name, info->data.yin->name, 1)) {
e = &mod->inc[j].submodule->extensions[i];
break;
}
}
}
if (!e) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, info->data.yin->name);
return EXIT_FAILURE;
}
/* we have the extension definition, so now it cannot be forward referenced and error is always fatal */
if (e->plugin && e->plugin->check_position) {
/* common part - we have plugin with position checking function, use it first */
if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) {
/* extension is not allowed here */
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name);
return -1;
}
}
/* extension type-specific part - allocation */
if (e->plugin) {
etype = e->plugin->type;
} else {
/* default type */
etype = LYEXT_FLAG;
}
switch (etype) {
case LYEXT_FLAG:
(*ext) = calloc(1, sizeof(struct lys_ext_instance));
break;
case LYEXT_COMPLEX:
(*ext) = calloc(1, ((struct lyext_plugin_complex*)e->plugin)->instance_size);
break;
case LYEXT_ERR:
/* we never should be here */
LOGINT(ctx);
return -1;
}
LY_CHECK_ERR_RETURN(!*ext, LOGMEM(ctx), -1);
/* common part for all extension types */
(*ext)->def = e;
(*ext)->parent = info->parent;
(*ext)->parent_type = info->parent_type;
(*ext)->insubstmt = info->substmt;
(*ext)->insubstmt_index = info->substmt_index;
(*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG;
(*ext)->flags |= e->plugin ? e->plugin->flags : 0;
if (e->argument) {
if (!(e->flags & LYS_YINELEM)) {
(*ext)->arg_value = lyxml_get_attr(info->data.yin, e->argument, NULL);
if (!(*ext)->arg_value) {
LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, info->data.yin->name);
return -1;
}
(*ext)->arg_value = lydict_insert(mod->ctx, (*ext)->arg_value, 0);
} else {
LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) {
if (ly_strequal(yin->name, e->argument, 1)) {
(*ext)->arg_value = lydict_insert(mod->ctx, yin->content, 0);
lyxml_free(mod->ctx, yin);
break;
}
}
}
}
if ((*ext)->flags & LYEXT_OPT_VALID &&
(info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) {
((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT;
}
(*ext)->nodetype = LYS_EXT;
(*ext)->module = info->mod;
/* extension type-specific part - parsing content */
switch (etype) {
case LYEXT_FLAG:
LY_TREE_FOR_SAFE(info->data.yin->child, next_yin, yin) {
if (!yin->ns) {
/* garbage */
lyxml_free(mod->ctx, yin);
continue;
} else if (!strcmp(yin->ns->value, LY_NSYIN)) {
/* standard YANG statements are not expected here */
LOGVAL(ctx, LYE_INCHILDSTMT, vlog_type, vlog_node, yin->name, info->data.yin->name);
return -1;
} else if (yin->ns == info->data.yin->ns &&
(e->flags & LYS_YINELEM) && ly_strequal(yin->name, e->argument, 1)) {
/* we have the extension's argument */
if ((*ext)->arg_value) {
LOGVAL(ctx, LYE_TOOMANY, vlog_type, vlog_node, yin->name, info->data.yin->name);
return -1;
}
(*ext)->arg_value = yin->content;
yin->content = NULL;
lyxml_free(mod->ctx, yin);
} else {
/* extension instance */
if (lyp_yin_parse_subnode_ext(info->mod, *ext, LYEXT_PAR_EXTINST, yin,
LYEXT_SUBSTMT_SELF, 0, unres)) {
return -1;
}
continue;
}
}
break;
case LYEXT_COMPLEX:
((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt;
if (lyp_yin_parse_complex_ext(info->mod, (struct lys_ext_instance_complex*)(*ext), info->data.yin, unres)) {
/* TODO memory cleanup */
return -1;
}
break;
default:
break;
}
/* TODO - lyext_check_result_clb, other than LYEXT_FLAG plugins */
} else {
/* YANG */
ext_prefix = (char *)(*ext)->def;
tmp = strchr(ext_prefix, ':');
if (!tmp) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix);
goto error;
}
ext_name = tmp + 1;
/* get the module where the extension is supposed to be defined */
mod = lyp_get_module(info->mod, ext_prefix, tmp - ext_prefix, NULL, 0, 0);
if (!mod) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix);
return EXIT_FAILURE;
}
ctx = mod->ctx;
/* find the extension definition */
e = NULL;
for (i = 0; i < mod->extensions_size; i++) {
if (ly_strequal(mod->extensions[i].name, ext_name, 0)) {
e = &mod->extensions[i];
break;
}
}
/* try submodules */
for (j = 0; !e && j < mod->inc_size; j++) {
for (i = 0; i < mod->inc[j].submodule->extensions_size; i++) {
if (ly_strequal(mod->inc[j].submodule->extensions[i].name, ext_name, 0)) {
e = &mod->inc[j].submodule->extensions[i];
break;
}
}
}
if (!e) {
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, ext_prefix);
return EXIT_FAILURE;
}
(*ext)->flags &= ~LYEXT_OPT_YANG;
(*ext)->def = NULL;
/* we have the extension definition, so now it cannot be forward referenced and error is always fatal */
if (e->plugin && e->plugin->check_position) {
/* common part - we have plugin with position checking function, use it first */
if ((*e->plugin->check_position)(info->parent, info->parent_type, info->substmt)) {
/* extension is not allowed here */
LOGVAL(ctx, LYE_INSTMT, vlog_type, vlog_node, e->name);
goto error;
}
}
/* extension common part */
(*ext)->def = e;
(*ext)->parent = info->parent;
(*ext)->ext_type = e->plugin ? e->plugin->type : LYEXT_FLAG;
(*ext)->flags |= e->plugin ? e->plugin->flags : 0;
if (e->argument && !(*ext)->arg_value) {
LOGVAL(ctx, LYE_MISSARG, LY_VLOG_NONE, NULL, e->argument, ext_name);
goto error;
}
if ((*ext)->flags & LYEXT_OPT_VALID &&
(info->parent_type == LYEXT_PAR_NODE || info->parent_type == LYEXT_PAR_TPDF)) {
((struct lys_node *)info->parent)->flags |= LYS_VALID_EXT;
}
(*ext)->module = info->mod;
(*ext)->nodetype = LYS_EXT;
/* extension type-specific part */
if (e->plugin) {
etype = e->plugin->type;
} else {
/* default type */
etype = LYEXT_FLAG;
}
switch (etype) {
case LYEXT_FLAG:
/* nothing change */
break;
case LYEXT_COMPLEX:
tmp_ext = realloc(*ext, ((struct lyext_plugin_complex*)e->plugin)->instance_size);
LY_CHECK_ERR_GOTO(!tmp_ext, LOGMEM(ctx), error);
memset((char *)tmp_ext + offsetof(struct lys_ext_instance_complex, content), 0,
((struct lyext_plugin_complex*)e->plugin)->instance_size - offsetof(struct lys_ext_instance_complex, content));
(*ext) = tmp_ext;
((struct lys_ext_instance_complex*)(*ext))->substmt = ((struct lyext_plugin_complex*)e->plugin)->substmt;
if (info->data.yang) {
*tmp = ':';
if (yang_parse_ext_substatement(info->mod, unres, info->data.yang->ext_substmt, ext_prefix,
(struct lys_ext_instance_complex*)(*ext))) {
goto error;
}
if (yang_fill_extcomplex_module(info->mod->ctx, (struct lys_ext_instance_complex*)(*ext), ext_prefix,
info->data.yang->ext_modules, info->mod->implemented)) {
goto error;
}
}
if (lyp_mand_check_ext((struct lys_ext_instance_complex*)(*ext), ext_prefix)) {
goto error;
}
break;
case LYEXT_ERR:
/* we never should be here */
LOGINT(ctx);
goto error;
}
if (yang_check_ext_instance(info->mod, &(*ext)->ext, (*ext)->ext_size, *ext, unres)) {
goto error;
}
free(ext_prefix);
}
return EXIT_SUCCESS;
error:
free(ext_prefix);
return -1;
}
/**
* @brief Resolve (find) choice default case. Does not log.
*
* @param[in] choic Choice to use.
* @param[in] dflt Name of the default case.
*
* @return Pointer to the default node or NULL.
*/
static struct lys_node *
resolve_choice_dflt(struct lys_node_choice *choic, const char *dflt)
{
struct lys_node *child, *ret;
LY_TREE_FOR(choic->child, child) {
if (child->nodetype == LYS_USES) {
ret = resolve_choice_dflt((struct lys_node_choice *)child, dflt);
if (ret) {
return ret;
}
}
if (ly_strequal(child->name, dflt, 1) && (child->nodetype & (LYS_ANYDATA | LYS_CASE
| LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CHOICE))) {
return child;
}
}
return NULL;
}
/**
* @brief Resolve uses, apply augments, refines. Logs directly.
*
* @param[in] uses Uses to use.
* @param[in,out] unres List of unresolved items.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_uses(struct lys_node_uses *uses, struct unres_schema *unres)
{
struct ly_ctx *ctx = uses->module->ctx; /* shortcut */
struct lys_node *node = NULL, *next, *iter, **refine_nodes = NULL;
struct lys_node *node_aux, *parent, *tmp;
struct lys_node_leaflist *llist;
struct lys_node_leaf *leaf;
struct lys_refine *rfn;
struct lys_restr *must, **old_must;
struct lys_iffeature *iff, **old_iff;
int i, j, k, rc;
uint8_t size, *old_size;
unsigned int usize, usize1, usize2;
assert(uses->grp);
/* check that the grouping is resolved (no unresolved uses inside) */
assert(!uses->grp->unres_count);
/* copy the data nodes from grouping into the uses context */
LY_TREE_FOR(uses->grp->child, node_aux) {
if (node_aux->nodetype & LYS_GROUPING) {
/* do not instantiate groupings from groupings */
continue;
}
node = lys_node_dup(uses->module, (struct lys_node *)uses, node_aux, unres, 0);
if (!node) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, uses->grp->name, "uses");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Copying data from grouping failed.");
goto fail;
}
/* test the name of siblings */
LY_TREE_FOR((uses->parent) ? *lys_child(uses->parent, LYS_USES) : lys_main_module(uses->module)->data, tmp) {
if (!(tmp->nodetype & (LYS_USES | LYS_GROUPING | LYS_CASE)) && ly_strequal(tmp->name, node_aux->name, 1)) {
goto fail;
}
}
}
/* we managed to copy the grouping, the rest must be possible to resolve */
if (uses->refine_size) {
refine_nodes = malloc(uses->refine_size * sizeof *refine_nodes);
LY_CHECK_ERR_GOTO(!refine_nodes, LOGMEM(ctx), fail);
}
/* apply refines */
for (i = 0; i < uses->refine_size; i++) {
rfn = &uses->refine[i];
rc = resolve_descendant_schema_nodeid(rfn->target_name, uses->child,
LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF,
0, (const struct lys_node **)&node);
if (rc || !node) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine");
goto fail;
}
if (rfn->target_type && !(node->nodetype & rfn->target_type)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->target_name, "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Refine substatements not applicable to the target-node.");
goto fail;
}
refine_nodes[i] = node;
/* description on any nodetype */
if (rfn->dsc) {
lydict_remove(ctx, node->dsc);
node->dsc = lydict_insert(ctx, rfn->dsc, 0);
}
/* reference on any nodetype */
if (rfn->ref) {
lydict_remove(ctx, node->ref);
node->ref = lydict_insert(ctx, rfn->ref, 0);
}
/* config on any nodetype,
* in case of notification or rpc/action, the config is not applicable (there is no config status) */
if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) {
node->flags &= ~LYS_CONFIG_MASK;
node->flags |= (rfn->flags & LYS_CONFIG_MASK);
}
/* default value ... */
if (rfn->dflt_size) {
if (node->nodetype == LYS_LEAF) {
/* leaf */
leaf = (struct lys_node_leaf *)node;
/* replace default value */
lydict_remove(ctx, leaf->dflt);
leaf->dflt = lydict_insert(ctx, rfn->dflt[0], 0);
/* check the default value */
if (unres_schema_add_node(leaf->module, unres, &leaf->type, UNRES_TYPE_DFLT,
(struct lys_node *)(&leaf->dflt)) == -1) {
goto fail;
}
} else if (node->nodetype == LYS_LEAFLIST) {
/* leaf-list */
llist = (struct lys_node_leaflist *)node;
/* remove complete set of defaults in target */
for (j = 0; j < llist->dflt_size; j++) {
lydict_remove(ctx, llist->dflt[j]);
}
free(llist->dflt);
/* copy the default set from refine */
llist->dflt = malloc(rfn->dflt_size * sizeof *llist->dflt);
LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), fail);
llist->dflt_size = rfn->dflt_size;
for (j = 0; j < llist->dflt_size; j++) {
llist->dflt[j] = lydict_insert(ctx, rfn->dflt[j], 0);
}
/* check default value */
for (j = 0; j < llist->dflt_size; j++) {
if (unres_schema_add_node(llist->module, unres, &llist->type, UNRES_TYPE_DFLT,
(struct lys_node *)(&llist->dflt[j])) == -1) {
goto fail;
}
}
}
}
/* mandatory on leaf, anyxml or choice */
if (rfn->flags & LYS_MAND_MASK) {
/* remove current value */
node->flags &= ~LYS_MAND_MASK;
/* set new value */
node->flags |= (rfn->flags & LYS_MAND_MASK);
if (rfn->flags & LYS_MAND_TRUE) {
/* check if node has default value */
if ((node->nodetype & LYS_LEAF) && ((struct lys_node_leaf *)node)->dflt) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses,
"The \"mandatory\" statement is forbidden on leaf with \"default\".");
goto fail;
}
if ((node->nodetype & LYS_CHOICE) && ((struct lys_node_choice *)node)->dflt) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses,
"The \"mandatory\" statement is forbidden on choices with \"default\".");
goto fail;
}
}
}
/* presence on container */
if ((node->nodetype & LYS_CONTAINER) && rfn->mod.presence) {
lydict_remove(ctx, ((struct lys_node_container *)node)->presence);
((struct lys_node_container *)node)->presence = lydict_insert(ctx, rfn->mod.presence, 0);
}
/* min/max-elements on list or leaf-list */
if (node->nodetype == LYS_LIST) {
if (rfn->flags & LYS_RFN_MINSET) {
((struct lys_node_list *)node)->min = rfn->mod.list.min;
}
if (rfn->flags & LYS_RFN_MAXSET) {
((struct lys_node_list *)node)->max = rfn->mod.list.max;
}
} else if (node->nodetype == LYS_LEAFLIST) {
if (rfn->flags & LYS_RFN_MINSET) {
((struct lys_node_leaflist *)node)->min = rfn->mod.list.min;
}
if (rfn->flags & LYS_RFN_MAXSET) {
((struct lys_node_leaflist *)node)->max = rfn->mod.list.max;
}
}
/* must in leaf, leaf-list, list, container or anyxml */
if (rfn->must_size) {
switch (node->nodetype) {
case LYS_LEAF:
old_size = &((struct lys_node_leaf *)node)->must_size;
old_must = &((struct lys_node_leaf *)node)->must;
break;
case LYS_LEAFLIST:
old_size = &((struct lys_node_leaflist *)node)->must_size;
old_must = &((struct lys_node_leaflist *)node)->must;
break;
case LYS_LIST:
old_size = &((struct lys_node_list *)node)->must_size;
old_must = &((struct lys_node_list *)node)->must;
break;
case LYS_CONTAINER:
old_size = &((struct lys_node_container *)node)->must_size;
old_must = &((struct lys_node_container *)node)->must;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
old_size = &((struct lys_node_anydata *)node)->must_size;
old_must = &((struct lys_node_anydata *)node)->must;
break;
default:
LOGINT(ctx);
goto fail;
}
size = *old_size + rfn->must_size;
must = realloc(*old_must, size * sizeof *rfn->must);
LY_CHECK_ERR_GOTO(!must, LOGMEM(ctx), fail);
for (k = 0, j = *old_size; k < rfn->must_size; k++, j++) {
must[j].ext_size = rfn->must[k].ext_size;
lys_ext_dup(ctx, rfn->module, rfn->must[k].ext, rfn->must[k].ext_size, &rfn->must[k], LYEXT_PAR_RESTR,
&must[j].ext, 0, unres);
must[j].expr = lydict_insert(ctx, rfn->must[k].expr, 0);
must[j].dsc = lydict_insert(ctx, rfn->must[k].dsc, 0);
must[j].ref = lydict_insert(ctx, rfn->must[k].ref, 0);
must[j].eapptag = lydict_insert(ctx, rfn->must[k].eapptag, 0);
must[j].emsg = lydict_insert(ctx, rfn->must[k].emsg, 0);
must[j].flags = rfn->must[k].flags;
}
*old_must = must;
*old_size = size;
/* check XPath dependencies again */
if (unres_schema_add_node(node->module, unres, node, UNRES_XPATH, NULL) == -1) {
goto fail;
}
}
/* if-feature in leaf, leaf-list, list, container or anyxml */
if (rfn->iffeature_size) {
old_size = &node->iffeature_size;
old_iff = &node->iffeature;
size = *old_size + rfn->iffeature_size;
iff = realloc(*old_iff, size * sizeof *rfn->iffeature);
LY_CHECK_ERR_GOTO(!iff, LOGMEM(ctx), fail);
*old_iff = iff;
for (k = 0, j = *old_size; k < rfn->iffeature_size; k++, j++) {
resolve_iffeature_getsizes(&rfn->iffeature[k], &usize1, &usize2);
if (usize1) {
/* there is something to duplicate */
/* duplicate compiled expression */
usize = (usize1 / 4) + (usize1 % 4) ? 1 : 0;
iff[j].expr = malloc(usize * sizeof *iff[j].expr);
LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail);
memcpy(iff[j].expr, rfn->iffeature[k].expr, usize * sizeof *iff[j].expr);
/* duplicate list of feature pointers */
iff[j].features = malloc(usize2 * sizeof *iff[k].features);
LY_CHECK_ERR_GOTO(!iff[j].expr, LOGMEM(ctx), fail);
memcpy(iff[j].features, rfn->iffeature[k].features, usize2 * sizeof *iff[j].features);
/* duplicate extensions */
iff[j].ext_size = rfn->iffeature[k].ext_size;
lys_ext_dup(ctx, rfn->module, rfn->iffeature[k].ext, rfn->iffeature[k].ext_size,
&rfn->iffeature[k], LYEXT_PAR_IFFEATURE, &iff[j].ext, 0, unres);
}
(*old_size)++;
}
assert(*old_size == size);
}
}
/* apply augments */
for (i = 0; i < uses->augment_size; i++) {
rc = resolve_augment(&uses->augment[i], (struct lys_node *)uses, unres);
if (rc) {
goto fail;
}
}
/* check refines */
for (i = 0; i < uses->refine_size; i++) {
node = refine_nodes[i];
rfn = &uses->refine[i];
/* config on any nodetype */
if ((rfn->flags & LYS_CONFIG_MASK) && (node->flags & LYS_CONFIG_MASK)) {
for (parent = lys_parent(node); parent && parent->nodetype == LYS_USES; parent = lys_parent(parent));
if (parent && parent->nodetype != LYS_GROUPING && (parent->flags & LYS_CONFIG_MASK) &&
((parent->flags & LYS_CONFIG_MASK) != (rfn->flags & LYS_CONFIG_MASK)) &&
(rfn->flags & LYS_CONFIG_W)) {
/* setting config true under config false is prohibited */
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"changing config from 'false' to 'true' is prohibited while "
"the target's parent is still config 'false'.");
goto fail;
}
/* inherit config change to the target children */
LY_TREE_DFS_BEGIN(node->child, next, iter) {
if (rfn->flags & LYS_CONFIG_W) {
if (iter->flags & LYS_CONFIG_SET) {
/* config is set explicitely, go to next sibling */
next = NULL;
goto nextsibling;
}
} else { /* LYS_CONFIG_R */
if ((iter->flags & LYS_CONFIG_SET) && (iter->flags & LYS_CONFIG_W)) {
/* error - we would have config data under status data */
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, "config", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"changing config from 'true' to 'false' is prohibited while the target "
"has still a children with explicit config 'true'.");
goto fail;
}
}
/* change config */
iter->flags &= ~LYS_CONFIG_MASK;
iter->flags |= (rfn->flags & LYS_CONFIG_MASK);
/* select next iter - modified LY_TREE_DFS_END */
if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next = NULL;
} else {
next = iter->child;
}
nextsibling:
if (!next) {
/* try siblings */
next = iter->next;
}
while (!next) {
/* parent is already processed, go to its sibling */
iter = lys_parent(iter);
/* no siblings, go back through parents */
if (iter == node) {
/* we are done, no next element to process */
break;
}
next = iter->next;
}
}
}
/* default value */
if (rfn->dflt_size) {
if (node->nodetype == LYS_CHOICE) {
/* choice */
((struct lys_node_choice *)node)->dflt = resolve_choice_dflt((struct lys_node_choice *)node,
rfn->dflt[0]);
if (!((struct lys_node_choice *)node)->dflt) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, uses, rfn->dflt[0], "default");
goto fail;
}
if (lyp_check_mandatory_choice(node)) {
goto fail;
}
}
}
/* min/max-elements on list or leaf-list */
if (node->nodetype == LYS_LIST && ((struct lys_node_list *)node)->max) {
if (((struct lys_node_list *)node)->min > ((struct lys_node_list *)node)->max) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\".");
goto fail;
}
} else if (node->nodetype == LYS_LEAFLIST && ((struct lys_node_leaflist *)node)->max) {
if (((struct lys_node_leaflist *)node)->min > ((struct lys_node_leaflist *)node)->max) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, uses, "Invalid value \"%d\" of \"%s\".", rfn->mod.list.min, "min-elements");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\".");
goto fail;
}
}
/* additional checks */
/* default value with mandatory/min-elements */
if (node->nodetype == LYS_LEAFLIST) {
llist = (struct lys_node_leaflist *)node;
if (llist->dflt_size && llist->min) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "min-elements", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement.");
goto fail;
}
} else if (node->nodetype == LYS_LEAF) {
leaf = (struct lys_node_leaf *)node;
if (leaf->dflt && (leaf->flags & LYS_MAND_TRUE)) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, uses, rfn->dflt_size ? "default" : "mandatory", "refine");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
"The \"mandatory\" statement is forbidden on leafs with the \"default\" statement.");
goto fail;
}
}
/* check for mandatory node in default case, first find the closest parent choice to the changed node */
if ((rfn->flags & LYS_MAND_TRUE) || rfn->mod.list.min) {
for (parent = node->parent;
parent && !(parent->nodetype & (LYS_CHOICE | LYS_GROUPING | LYS_ACTION | LYS_USES));
parent = parent->parent) {
if (parent->nodetype == LYS_CONTAINER && ((struct lys_node_container *)parent)->presence) {
/* stop also on presence containers */
break;
}
}
/* and if it is a choice with the default case, check it for presence of a mandatory node in it */
if (parent && parent->nodetype == LYS_CHOICE && ((struct lys_node_choice *)parent)->dflt) {
if (lyp_check_mandatory_choice(parent)) {
goto fail;
}
}
}
}
free(refine_nodes);
return EXIT_SUCCESS;
fail:
LY_TREE_FOR_SAFE(uses->child, next, iter) {
lys_node_free(iter, NULL, 0);
}
free(refine_nodes);
return -1;
}
void
resolve_identity_backlink_update(struct lys_ident *der, struct lys_ident *base)
{
int i;
assert(der && base);
if (!base->der) {
/* create a set for backlinks if it does not exist */
base->der = ly_set_new();
}
/* store backlink */
ly_set_add(base->der, der, LY_SET_OPT_USEASLIST);
/* do it recursively */
for (i = 0; i < base->base_size; i++) {
resolve_identity_backlink_update(der, base->base[i]);
}
}
/**
* @brief Resolve base identity recursively. Does not log.
*
* @param[in] module Main module.
* @param[in] ident Identity to use.
* @param[in] basename Base name of the identity.
* @param[out] ret Pointer to the resolved identity. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on crucial error.
*/
static int
resolve_base_ident_sub(const struct lys_module *module, struct lys_ident *ident, const char *basename,
struct unres_schema *unres, struct lys_ident **ret)
{
uint32_t i, j;
struct lys_ident *base = NULL;
struct ly_ctx *ctx = module->ctx;
assert(ret);
/* search module */
for (i = 0; i < module->ident_size; i++) {
if (!strcmp(basename, module->ident[i].name)) {
if (!ident) {
/* just search for type, so do not modify anything, just return
* the base identity pointer */
*ret = &module->ident[i];
return EXIT_SUCCESS;
}
base = &module->ident[i];
goto matchfound;
}
}
/* search submodules */
for (j = 0; j < module->inc_size && module->inc[j].submodule; j++) {
for (i = 0; i < module->inc[j].submodule->ident_size; i++) {
if (!strcmp(basename, module->inc[j].submodule->ident[i].name)) {
if (!ident) {
*ret = &module->inc[j].submodule->ident[i];
return EXIT_SUCCESS;
}
base = &module->inc[j].submodule->ident[i];
goto matchfound;
}
}
}
matchfound:
/* we found it somewhere */
if (base) {
/* is it already completely resolved? */
for (i = 0; i < unres->count; i++) {
if ((unres->item[i] == base) && (unres->type[i] == UNRES_IDENT)) {
/* identity found, but not yet resolved, so do not return it in *res and try it again later */
/* simple check for circular reference,
* the complete check is done as a side effect of using only completely
* resolved identities (previous check of unres content) */
if (ly_strequal((const char *)unres->str_snode[i], ident->name, 1)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, basename, "base");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Circular reference of \"%s\" identity.", basename);
return -1;
}
return EXIT_FAILURE;
}
}
/* checks done, store the result */
*ret = base;
return EXIT_SUCCESS;
}
/* base not found (maybe a forward reference) */
return EXIT_FAILURE;
}
/**
* @brief Resolve base identity. Logs directly.
*
* @param[in] module Main module.
* @param[in] ident Identity to use.
* @param[in] basename Base name of the identity.
* @param[in] parent Either "type" or "identity".
* @param[in,out] type Type structure where we want to resolve identity. Can be NULL.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_base_ident(const struct lys_module *module, struct lys_ident *ident, const char *basename, const char *parent,
struct lys_type *type, struct unres_schema *unres)
{
const char *name;
int mod_name_len = 0, rc;
struct lys_ident *target, **ret;
uint16_t flags;
struct lys_module *mod;
struct ly_ctx *ctx = module->ctx;
assert((ident && !type) || (!ident && type));
if (!type) {
/* have ident to resolve */
ret = ⌖
flags = ident->flags;
mod = ident->module;
} else {
/* have type to fill */
++type->info.ident.count;
type->info.ident.ref = ly_realloc(type->info.ident.ref, type->info.ident.count * sizeof *type->info.ident.ref);
LY_CHECK_ERR_RETURN(!type->info.ident.ref, LOGMEM(ctx), -1);
ret = &type->info.ident.ref[type->info.ident.count - 1];
flags = type->parent->flags;
mod = type->parent->module;
}
*ret = NULL;
/* search for the base identity */
name = strchr(basename, ':');
if (name) {
/* set name to correct position after colon */
mod_name_len = name - basename;
name++;
if (!strncmp(basename, module->name, mod_name_len) && !module->name[mod_name_len]) {
/* prefix refers to the current module, ignore it */
mod_name_len = 0;
}
} else {
name = basename;
}
/* get module where to search */
module = lyp_get_module(module, NULL, 0, mod_name_len ? basename : NULL, mod_name_len, 0);
if (!module) {
/* identity refers unknown data model */
LOGVAL(ctx, LYE_INMOD, LY_VLOG_NONE, NULL, basename);
return -1;
}
/* search in the identified module ... */
rc = resolve_base_ident_sub(module, ident, name, unres, ret);
if (!rc) {
assert(*ret);
/* check status */
if (lyp_check_status(flags, mod, ident ? ident->name : "of type",
(*ret)->flags, (*ret)->module, (*ret)->name, NULL)) {
rc = -1;
} else if (ident) {
ident->base[ident->base_size++] = *ret;
if (lys_main_module(mod)->implemented) {
/* in case of the implemented identity, maintain backlinks to it
* from the base identities to make it available when resolving
* data with the identity values (not implemented identity is not
* allowed as an identityref value). */
resolve_identity_backlink_update(ident, *ret);
}
}
} else if (rc == EXIT_FAILURE) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_NONE, NULL, parent, basename);
if (type) {
--type->info.ident.count;
}
}
return rc;
}
/*
* 1 - true (der is derived from base)
* 0 - false (der is not derived from base)
*/
static int
search_base_identity(struct lys_ident *der, struct lys_ident *base)
{
int i;
if (der == base) {
return 1;
} else {
for(i = 0; i < der->base_size; i++) {
if (search_base_identity(der->base[i], base) == 1) {
return 1;
}
}
}
return 0;
}
/**
* @brief Resolve JSON data format identityref. Logs directly.
*
* @param[in] type Identityref type.
* @param[in] ident_name Identityref name.
* @param[in] node Node where the identityref is being resolved
* @param[in] dflt flag if we are resolving default value in the schema
*
* @return Pointer to the identity resolvent, NULL on error.
*/
struct lys_ident *
resolve_identref(struct lys_type *type, const char *ident_name, struct lyd_node *node, struct lys_module *mod, int dflt)
{
const char *mod_name, *name;
char *str;
int mod_name_len, nam_len, rc;
int need_implemented = 0;
unsigned int i, j;
struct lys_ident *der, *cur;
struct lys_module *imod = NULL, *m, *tmod;
struct ly_ctx *ctx;
assert(type && ident_name && mod);
ctx = mod->ctx;
if (!type || (!type->info.ident.count && !type->der) || !ident_name) {
return NULL;
}
rc = parse_node_identifier(ident_name, &mod_name, &mod_name_len, &name, &nam_len, NULL, 0);
if (rc < 1) {
LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[-rc], &ident_name[-rc]);
return NULL;
} else if (rc < (signed)strlen(ident_name)) {
LOGVAL(ctx, LYE_INCHAR, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, ident_name[rc], &ident_name[rc]);
return NULL;
}
m = lys_main_module(mod); /* shortcut */
if (!mod_name || (!strncmp(mod_name, m->name, mod_name_len) && !m->name[mod_name_len])) {
/* identity is defined in the same module as node */
imod = m;
} else if (dflt) {
/* solving identityref in default definition in schema -
* find the identity's module in the imported modules list to have a correct revision */
for (i = 0; i < mod->imp_size; i++) {
if (!strncmp(mod_name, mod->imp[i].module->name, mod_name_len) && !mod->imp[i].module->name[mod_name_len]) {
imod = mod->imp[i].module;
break;
}
}
/* We may need to pull it from the module that the typedef came from */
if (!imod && type && type->der) {
tmod = type->der->module;
for (i = 0; i < tmod->imp_size; i++) {
if (!strncmp(mod_name, tmod->imp[i].module->name, mod_name_len) && !tmod->imp[i].module->name[mod_name_len]) {
imod = tmod->imp[i].module;
break;
}
}
}
} else {
/* solving identityref in data - get the module from the context */
for (i = 0; i < (unsigned)mod->ctx->models.used; ++i) {
imod = mod->ctx->models.list[i];
if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) {
break;
}
imod = NULL;
}
if (!imod && mod->ctx->models.parsing_sub_modules_count) {
/* we are currently parsing some module and checking XPath or a default value,
* so take this module into account */
for (i = 0; i < mod->ctx->models.parsing_sub_modules_count; i++) {
imod = mod->ctx->models.parsing_sub_modules[i];
if (imod->type) {
/* skip submodules */
continue;
}
if (!strncmp(mod_name, imod->name, mod_name_len) && !imod->name[mod_name_len]) {
break;
}
imod = NULL;
}
}
}
if (!dflt && (!imod || !imod->implemented) && ctx->data_clb) {
/* the needed module was not found, but it may have been expected so call the data callback */
if (imod) {
ctx->data_clb(ctx, imod->name, imod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data);
} else if (mod_name) {
str = strndup(mod_name, mod_name_len);
imod = (struct lys_module *)ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data);
free(str);
}
}
if (!imod) {
goto fail;
}
if (m != imod || lys_main_module(type->parent->module) != mod) {
/* the type is not referencing the same schema,
* THEN, we may need to make the module with the identity implemented, but only if it really
* contains the identity */
if (!imod->implemented) {
cur = NULL;
/* get the identity in the module */
for (i = 0; i < imod->ident_size; i++) {
if (!strcmp(name, imod->ident[i].name)) {
cur = &imod->ident[i];
break;
}
}
if (!cur) {
/* go through includes */
for (j = 0; j < imod->inc_size; j++) {
for (i = 0; i < imod->inc[j].submodule->ident_size; i++) {
if (!strcmp(name, imod->inc[j].submodule->ident[i].name)) {
cur = &imod->inc[j].submodule->ident[i];
break;
}
}
}
if (!cur) {
goto fail;
}
}
/* check that identity is derived from one of the type's base */
while (type->der) {
for (i = 0; i < type->info.ident.count; i++) {
if (search_base_identity(cur, type->info.ident.ref[i])) {
/* cur's base matches the type's base */
need_implemented = 1;
goto match;
}
}
type = &type->der->type;
}
/* matching base not found */
LOGVAL(ctx, LYE_SPEC, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "Identity used as identityref value is not implemented.");
goto fail;
}
}
/* go through all the derived types of all the bases */
while (type->der) {
for (i = 0; i < type->info.ident.count; ++i) {
cur = type->info.ident.ref[i];
if (cur->der) {
/* there are some derived identities */
for (j = 0; j < cur->der->number; j++) {
der = (struct lys_ident *)cur->der->set.g[j]; /* shortcut */
if (!strcmp(der->name, name) && lys_main_module(der->module) == imod) {
/* we have match */
cur = der;
goto match;
}
}
}
}
type = &type->der->type;
}
fail:
LOGVAL(ctx, LYE_INRESOLV, node ? LY_VLOG_LYD : LY_VLOG_NONE, node, "identityref", ident_name);
return NULL;
match:
for (i = 0; i < cur->iffeature_size; i++) {
if (!resolve_iffeature(&cur->iffeature[i])) {
if (node) {
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, node, cur->name, node->schema->name);
}
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Identity \"%s\" is disabled by its if-feature condition.", cur->name);
return NULL;
}
}
if (need_implemented) {
if (dflt) {
/* later try to make the module implemented */
LOGVRB("Making \"%s\" module implemented because of identityref default value \"%s\" used in the implemented \"%s\" module",
imod->name, cur->name, mod->name);
/* to be more effective we should use UNRES_MOD_IMPLEMENT but that would require changing prototype of
* several functions with little gain */
if (lys_set_implemented(imod)) {
LOGERR(ctx, ly_errno, "Setting the module \"%s\" implemented because of used default identity \"%s\" failed.",
imod->name, cur->name);
goto fail;
}
} else {
/* just say that it was found, but in a non-implemented module */
LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Identity found, but in a non-implemented module \"%s\".",
lys_main_module(cur->module)->name);
goto fail;
}
}
return cur;
}
/**
* @brief Resolve unresolved uses. Logs directly.
*
* @param[in] uses Uses to use.
* @param[in] unres Specific unres item.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_unres_schema_uses(struct lys_node_uses *uses, struct unres_schema *unres)
{
int rc;
struct lys_node *par_grp;
struct ly_ctx *ctx = uses->module->ctx;
/* HACK: when a grouping has uses inside, all such uses have to be resolved before the grouping itself is used
* in some uses. When we see such a uses, the grouping's unres counter is used to store number of so far
* unresolved uses. The grouping cannot be used unless this counter is decreased back to 0. To remember
* that the uses already increased grouping's counter, the LYS_USESGRP flag is used. */
for (par_grp = lys_parent((struct lys_node *)uses); par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp));
if (par_grp && ly_strequal(par_grp->name, uses->name, 1)) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return -1;
}
if (!uses->grp) {
rc = resolve_uses_schema_nodeid(uses->name, (const struct lys_node *)uses, (const struct lys_node_grp **)&uses->grp);
if (rc == -1) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return -1;
} else if (rc > 0) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYS, uses, uses->name[rc - 1], &uses->name[rc - 1]);
return -1;
} else if (!uses->grp) {
if (par_grp && !(uses->flags & LYS_USESGRP)) {
if (++((struct lys_node_grp *)par_grp)->unres_count == 0) {
LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping.");
return -1;
}
uses->flags |= LYS_USESGRP;
}
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return EXIT_FAILURE;
}
}
if (uses->grp->unres_count) {
if (par_grp && !(uses->flags & LYS_USESGRP)) {
if (++((struct lys_node_grp *)par_grp)->unres_count == 0) {
LOGERR(ctx, LY_EINT, "Too many unresolved items (uses) inside a grouping.");
return -1;
}
uses->flags |= LYS_USESGRP;
} else {
/* instantiate grouping only when it is completely resolved */
uses->grp = NULL;
}
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, uses, "uses", uses->name);
return EXIT_FAILURE;
}
rc = resolve_uses(uses, unres);
if (!rc) {
/* decrease unres count only if not first try */
if (par_grp && (uses->flags & LYS_USESGRP)) {
assert(((struct lys_node_grp *)par_grp)->unres_count);
((struct lys_node_grp *)par_grp)->unres_count--;
uses->flags &= ~LYS_USESGRP;
}
/* check status */
if (lyp_check_status(uses->flags, uses->module, "of uses",
uses->grp->flags, uses->grp->module, uses->grp->name,
(struct lys_node *)uses)) {
return -1;
}
return EXIT_SUCCESS;
}
return rc;
}
/**
* @brief Resolve list keys. Logs directly.
*
* @param[in] list List to use.
* @param[in] keys_str Keys node value.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_list_keys(struct lys_node_list *list, const char *keys_str)
{
int i, len, rc;
const char *value;
char *s = NULL;
struct ly_ctx *ctx = list->module->ctx;
for (i = 0; i < list->keys_size; ++i) {
assert(keys_str);
if (!list->child) {
/* no child, possible forward reference */
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list keys", keys_str);
return EXIT_FAILURE;
}
/* get the key name */
if ((value = strpbrk(keys_str, " \t\n"))) {
len = value - keys_str;
while (isspace(value[0])) {
value++;
}
} else {
len = strlen(keys_str);
}
rc = lys_getnext_data(lys_node_module((struct lys_node *)list), (struct lys_node *)list, keys_str, len, LYS_LEAF,
LYS_GETNEXT_NOSTATECHECK, (const struct lys_node **)&list->keys[i]);
if (rc) {
LOGVAL(ctx, LYE_INRESOLV, LY_VLOG_LYS, list, "list key", keys_str);
return EXIT_FAILURE;
}
if (check_key(list, i, keys_str, len)) {
/* check_key logs */
return -1;
}
/* check status */
if (lyp_check_status(list->flags, list->module, list->name,
list->keys[i]->flags, list->keys[i]->module, list->keys[i]->name,
(struct lys_node *)list->keys[i])) {
return -1;
}
/* default value - is ignored, keep it but print a warning */
if (list->keys[i]->dflt) {
/* log is not hidden only in case this resolving fails and in such a case
* we cannot get here
*/
assert(log_opt == ILO_STORE);
log_opt = ILO_LOG;
LOGWRN(ctx, "Default value \"%s\" in the list key \"%s\" is ignored. (%s)", list->keys[i]->dflt,
list->keys[i]->name, s = lys_path((struct lys_node*)list, LYS_PATH_FIRST_PREFIX));
log_opt = ILO_STORE;
free(s);
}
/* prepare for next iteration */
while (value && isspace(value[0])) {
value++;
}
keys_str = value;
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve (check) all must conditions of \p node.
* Logs directly.
*
* @param[in] node Data node with optional must statements.
* @param[in] inout_parent If set, must in input or output parent of node->schema will be resolved.
*
* @return EXIT_SUCCESS on pass, EXIT_FAILURE on fail, -1 on error.
*/
static int
resolve_must(struct lyd_node *node, int inout_parent, int ignore_fail)
{
uint8_t i, must_size;
struct lys_node *schema;
struct lys_restr *must;
struct lyxp_set set;
struct ly_ctx *ctx = node->schema->module->ctx;
assert(node);
memset(&set, 0, sizeof set);
if (inout_parent) {
for (schema = lys_parent(node->schema);
schema && (schema->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES));
schema = lys_parent(schema));
if (!schema || !(schema->nodetype & (LYS_INPUT | LYS_OUTPUT))) {
LOGINT(ctx);
return -1;
}
must_size = ((struct lys_node_inout *)schema)->must_size;
must = ((struct lys_node_inout *)schema)->must;
/* context node is the RPC/action */
node = node->parent;
if (!(node->schema->nodetype & (LYS_RPC | LYS_ACTION))) {
LOGINT(ctx);
return -1;
}
} else {
switch (node->schema->nodetype) {
case LYS_CONTAINER:
must_size = ((struct lys_node_container *)node->schema)->must_size;
must = ((struct lys_node_container *)node->schema)->must;
break;
case LYS_LEAF:
must_size = ((struct lys_node_leaf *)node->schema)->must_size;
must = ((struct lys_node_leaf *)node->schema)->must;
break;
case LYS_LEAFLIST:
must_size = ((struct lys_node_leaflist *)node->schema)->must_size;
must = ((struct lys_node_leaflist *)node->schema)->must;
break;
case LYS_LIST:
must_size = ((struct lys_node_list *)node->schema)->must_size;
must = ((struct lys_node_list *)node->schema)->must;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
must_size = ((struct lys_node_anydata *)node->schema)->must_size;
must = ((struct lys_node_anydata *)node->schema)->must;
break;
case LYS_NOTIF:
must_size = ((struct lys_node_notif *)node->schema)->must_size;
must = ((struct lys_node_notif *)node->schema)->must;
break;
default:
must_size = 0;
break;
}
}
for (i = 0; i < must_size; ++i) {
if (lyxp_eval(must[i].expr, node, LYXP_NODE_ELEM, lyd_node_module(node), &set, LYXP_MUST)) {
return -1;
}
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_MUST);
if (!set.val.bool) {
if ((ignore_fail == 1) || ((must[i].flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) && (ignore_fail == 2))) {
LOGVRB("Must condition \"%s\" not satisfied, but it is not required.", must[i].expr);
} else {
LOGVAL(ctx, LYE_NOMUST, LY_VLOG_LYD, node, must[i].expr);
if (must[i].emsg) {
ly_vlog_str(ctx, LY_VLOG_PREV, must[i].emsg);
}
if (must[i].eapptag) {
ly_err_last_set_apptag(ctx, must[i].eapptag);
}
return 1;
}
}
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve (find) when condition schema context node. Does not log.
*
* @param[in] schema Schema node with the when condition.
* @param[out] ctx_snode When schema context node.
* @param[out] ctx_snode_type Schema context node type.
*/
void
resolve_when_ctx_snode(const struct lys_node *schema, struct lys_node **ctx_snode, enum lyxp_node_type *ctx_snode_type)
{
const struct lys_node *sparent;
/* find a not schema-only node */
*ctx_snode_type = LYXP_NODE_ELEM;
while (schema->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_AUGMENT | LYS_INPUT | LYS_OUTPUT)) {
if (schema->nodetype == LYS_AUGMENT) {
sparent = ((struct lys_node_augment *)schema)->target;
} else {
sparent = schema->parent;
}
if (!sparent) {
/* context node is the document root (fake root in our case) */
if (schema->flags & LYS_CONFIG_W) {
*ctx_snode_type = LYXP_NODE_ROOT_CONFIG;
} else {
*ctx_snode_type = LYXP_NODE_ROOT;
}
/* we need the first top-level sibling, but no uses or groupings */
schema = lys_getnext(NULL, NULL, lys_node_module(schema), LYS_GETNEXT_NOSTATECHECK);
break;
}
schema = sparent;
}
*ctx_snode = (struct lys_node *)schema;
}
/**
* @brief Resolve (find) when condition context node. Does not log.
*
* @param[in] node Data node, whose conditional definition is being decided.
* @param[in] schema Schema node with the when condition.
* @param[out] ctx_node Context node.
* @param[out] ctx_node_type Context node type.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_when_ctx_node(struct lyd_node *node, struct lys_node *schema, struct lyd_node **ctx_node,
enum lyxp_node_type *ctx_node_type)
{
struct lyd_node *parent;
struct lys_node *sparent;
enum lyxp_node_type node_type;
uint16_t i, data_depth, schema_depth;
resolve_when_ctx_snode(schema, &schema, &node_type);
if (node_type == LYXP_NODE_ELEM) {
/* standard element context node */
for (parent = node, data_depth = 0; parent; parent = parent->parent, ++data_depth);
for (sparent = schema, schema_depth = 0;
sparent;
sparent = (sparent->nodetype == LYS_AUGMENT ? ((struct lys_node_augment *)sparent)->target : sparent->parent)) {
if (sparent->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA | LYS_NOTIF | LYS_RPC)) {
++schema_depth;
}
}
if (data_depth < schema_depth) {
return -1;
}
/* find the corresponding data node */
for (i = 0; i < data_depth - schema_depth; ++i) {
node = node->parent;
}
if (node->schema != schema) {
return -1;
}
} else {
/* root context node */
while (node->parent) {
node = node->parent;
}
while (node->prev->next) {
node = node->prev;
}
}
*ctx_node = node;
*ctx_node_type = node_type;
return EXIT_SUCCESS;
}
/**
* @brief Temporarily unlink nodes as per YANG 1.1 RFC section 7.21.5 for when XPath evaluation.
* The context node is adjusted if needed.
*
* @param[in] snode Schema node, whose children instances need to be unlinked.
* @param[in,out] node Data siblings where to look for the children of \p snode. If it is unlinked,
* it is moved to point to another sibling still in the original tree.
* @param[in,out] ctx_node When context node, adjusted if needed.
* @param[in] ctx_node_type Context node type, just for information to detect invalid situations.
* @param[out] unlinked_nodes Unlinked siblings. Can be safely appended to \p node afterwards.
* Ordering may change, but there will be no semantic change.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_when_unlink_nodes(struct lys_node *snode, struct lyd_node **node, struct lyd_node **ctx_node,
enum lyxp_node_type ctx_node_type, struct lyd_node **unlinked_nodes)
{
struct lyd_node *next, *elem;
const struct lys_node *slast;
struct ly_ctx *ctx = snode->module->ctx;
switch (snode->nodetype) {
case LYS_AUGMENT:
case LYS_USES:
case LYS_CHOICE:
case LYS_CASE:
slast = NULL;
while ((slast = lys_getnext(slast, snode, NULL, LYS_GETNEXT_PARENTUSES))) {
if (slast->nodetype & (LYS_ACTION | LYS_NOTIF)) {
continue;
}
if (resolve_when_unlink_nodes((struct lys_node *)slast, node, ctx_node, ctx_node_type, unlinked_nodes)) {
return -1;
}
}
break;
case LYS_CONTAINER:
case LYS_LIST:
case LYS_LEAF:
case LYS_LEAFLIST:
case LYS_ANYXML:
case LYS_ANYDATA:
LY_TREE_FOR_SAFE(lyd_first_sibling(*node), next, elem) {
if (elem->schema == snode) {
if (elem == *ctx_node) {
/* We are going to unlink our context node! This normally cannot happen,
* but we use normal top-level data nodes for faking a document root node,
* so if this is the context node, we just use the next top-level node.
* Additionally, it can even happen that there are no top-level data nodes left,
* all were unlinked, so in this case we pass NULL as the context node/data tree,
* lyxp_eval() can handle this special situation.
*/
if (ctx_node_type == LYXP_NODE_ELEM) {
LOGINT(ctx);
return -1;
}
if (elem->prev == elem) {
/* unlinking last top-level element, use an empty data tree */
*ctx_node = NULL;
} else {
/* in this case just use the previous/last top-level data node */
*ctx_node = elem->prev;
}
} else if (elem == *node) {
/* We are going to unlink the currently processed node. This does not matter that
* much, but we would lose access to the original data tree, so just move our
* pointer somewhere still inside it.
*/
if ((*node)->prev != *node) {
*node = (*node)->prev;
} else {
/* the processed node with sibings were all unlinked, oh well */
*node = NULL;
}
}
/* temporarily unlink the node */
lyd_unlink_internal(elem, 0);
if (*unlinked_nodes) {
if (lyd_insert_after((*unlinked_nodes)->prev, elem)) {
LOGINT(ctx);
return -1;
}
} else {
*unlinked_nodes = elem;
}
if (snode->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_ANYDATA)) {
/* there can be only one instance */
break;
}
}
}
break;
default:
LOGINT(ctx);
return -1;
}
return EXIT_SUCCESS;
}
/**
* @brief Relink the unlinked nodes back.
*
* @param[in] node Data node to link the nodes back to. It can actually be the adjusted context node,
* we simply need a sibling from the original data tree.
* @param[in] unlinked_nodes Unlinked nodes to relink to \p node.
* @param[in] ctx_node_type Context node type to distinguish between \p node being the parent
* or the sibling of \p unlinked_nodes.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
static int
resolve_when_relink_nodes(struct lyd_node *node, struct lyd_node *unlinked_nodes, enum lyxp_node_type ctx_node_type)
{
struct lyd_node *elem;
LY_TREE_FOR_SAFE(unlinked_nodes, unlinked_nodes, elem) {
lyd_unlink_internal(elem, 0);
if (ctx_node_type == LYXP_NODE_ELEM) {
if (lyd_insert_common(node, NULL, elem, 0)) {
return -1;
}
} else {
if (lyd_insert_nextto(node, elem, 0, 0)) {
return -1;
}
}
}
return EXIT_SUCCESS;
}
int
resolve_applies_must(const struct lyd_node *node)
{
int ret = 0;
uint8_t must_size;
struct lys_node *schema, *iter;
assert(node);
schema = node->schema;
/* their own must */
switch (schema->nodetype) {
case LYS_CONTAINER:
must_size = ((struct lys_node_container *)schema)->must_size;
break;
case LYS_LEAF:
must_size = ((struct lys_node_leaf *)schema)->must_size;
break;
case LYS_LEAFLIST:
must_size = ((struct lys_node_leaflist *)schema)->must_size;
break;
case LYS_LIST:
must_size = ((struct lys_node_list *)schema)->must_size;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
must_size = ((struct lys_node_anydata *)schema)->must_size;
break;
case LYS_NOTIF:
must_size = ((struct lys_node_notif *)schema)->must_size;
break;
default:
must_size = 0;
break;
}
if (must_size) {
++ret;
}
/* schema may be a direct data child of input/output with must (but it must be first, it needs to be evaluated only once) */
if (!node->prev->next) {
for (iter = lys_parent(schema); iter && (iter->nodetype & (LYS_CHOICE | LYS_CASE | LYS_USES)); iter = lys_parent(iter));
if (iter && (iter->nodetype & (LYS_INPUT | LYS_OUTPUT))) {
ret += 0x2;
}
}
return ret;
}
static struct lys_when *
snode_get_when(const struct lys_node *schema)
{
switch (schema->nodetype) {
case LYS_CONTAINER:
return ((struct lys_node_container *)schema)->when;
case LYS_CHOICE:
return ((struct lys_node_choice *)schema)->when;
case LYS_LEAF:
return ((struct lys_node_leaf *)schema)->when;
case LYS_LEAFLIST:
return ((struct lys_node_leaflist *)schema)->when;
case LYS_LIST:
return ((struct lys_node_list *)schema)->when;
case LYS_ANYDATA:
case LYS_ANYXML:
return ((struct lys_node_anydata *)schema)->when;
case LYS_CASE:
return ((struct lys_node_case *)schema)->when;
case LYS_USES:
return ((struct lys_node_uses *)schema)->when;
case LYS_AUGMENT:
return ((struct lys_node_augment *)schema)->when;
default:
return NULL;
}
}
int
resolve_applies_when(const struct lys_node *schema, int mode, const struct lys_node *stop)
{
const struct lys_node *parent;
assert(schema);
if (!(schema->nodetype & (LYS_NOTIF | LYS_RPC)) && snode_get_when(schema)) {
return 1;
}
parent = schema;
goto check_augment;
while (parent) {
/* stop conditions */
if (!mode) {
/* stop on node that can be instantiated in data tree */
if (!(parent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) {
break;
}
} else {
/* stop on the specified node */
if (parent == stop) {
break;
}
}
if (snode_get_when(parent)) {
return 1;
}
check_augment:
if (parent->parent && (parent->parent->nodetype == LYS_AUGMENT) && snode_get_when(parent->parent)) {
return 1;
}
parent = lys_parent(parent);
}
return 0;
}
/**
* @brief Resolve (check) all when conditions relevant for \p node.
* Logs directly.
*
* @param[in] node Data node, whose conditional reference, if such, is being decided.
* @param[in] ignore_fail 1 if when does not have to be satisfied, 2 if it does not have to be satisfied
* only when requiring external dependencies.
*
* @return
* -1 - error, ly_errno is set
* 0 - all "when" statements true
* 0, ly_vecode = LYVE_NOWHEN - some "when" statement false, returned in failed_when
* 1, ly_vecode = LYVE_INWHEN - nodes needed to resolve are conditional and not yet resolved (under another "when")
*/
int
resolve_when(struct lyd_node *node, int ignore_fail, struct lys_when **failed_when)
{
struct lyd_node *ctx_node = NULL, *unlinked_nodes, *tmp_node;
struct lys_node *sparent;
struct lyxp_set set;
enum lyxp_node_type ctx_node_type;
struct ly_ctx *ctx = node->schema->module->ctx;
int rc = 0;
assert(node);
memset(&set, 0, sizeof set);
if (!(node->schema->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION)) && snode_get_when(node->schema)) {
/* make the node dummy for the evaluation */
node->validity |= LYD_VAL_INUSE;
rc = lyxp_eval(snode_get_when(node->schema)->cond, node, LYXP_NODE_ELEM, lyd_node_module(node),
&set, LYXP_WHEN);
node->validity &= ~LYD_VAL_INUSE;
if (rc) {
if (rc == 1) {
LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond);
}
goto cleanup;
}
/* set boolean result of the condition */
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, node, lyd_node_module(node), LYXP_WHEN);
if (!set.val.bool) {
node->when_status |= LYD_WHEN_FALSE;
if ((ignore_fail == 1) || ((snode_get_when(node->schema)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))
&& (ignore_fail == 2))) {
LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(node->schema)->cond);
} else {
LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(node->schema)->cond);
if (failed_when) {
*failed_when = snode_get_when(node->schema);
}
goto cleanup;
}
}
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, node, lyd_node_module(node), 0);
}
sparent = node->schema;
goto check_augment;
/* check when in every schema node that affects node */
while (sparent && (sparent->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE))) {
if (snode_get_when(sparent)) {
if (!ctx_node) {
rc = resolve_when_ctx_node(node, sparent, &ctx_node, &ctx_node_type);
if (rc) {
LOGINT(ctx);
goto cleanup;
}
}
unlinked_nodes = NULL;
/* we do not want our node pointer to change */
tmp_node = node;
rc = resolve_when_unlink_nodes(sparent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes);
if (rc) {
goto cleanup;
}
rc = lyxp_eval(snode_get_when(sparent)->cond, ctx_node, ctx_node_type, lys_node_module(sparent),
&set, LYXP_WHEN);
if (unlinked_nodes && ctx_node) {
if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) {
rc = -1;
goto cleanup;
}
}
if (rc) {
if (rc == 1) {
LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond);
}
goto cleanup;
}
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent), LYXP_WHEN);
if (!set.val.bool) {
if ((ignore_fail == 1) || ((snode_get_when(sparent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))
&& (ignore_fail == 2))) {
LOGVRB("When condition \"%s\" is not satisfied, but it is not required.", snode_get_when(sparent)->cond);
} else {
node->when_status |= LYD_WHEN_FALSE;
LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent)->cond);
if (failed_when) {
*failed_when = snode_get_when(sparent);
}
goto cleanup;
}
}
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent), 0);
}
check_augment:
if ((sparent->parent && (sparent->parent->nodetype == LYS_AUGMENT) && snode_get_when(sparent->parent))) {
if (!ctx_node) {
rc = resolve_when_ctx_node(node, sparent->parent, &ctx_node, &ctx_node_type);
if (rc) {
LOGINT(ctx);
goto cleanup;
}
}
unlinked_nodes = NULL;
tmp_node = node;
rc = resolve_when_unlink_nodes(sparent->parent, &tmp_node, &ctx_node, ctx_node_type, &unlinked_nodes);
if (rc) {
goto cleanup;
}
rc = lyxp_eval(snode_get_when(sparent->parent)->cond, ctx_node, ctx_node_type,
lys_node_module(sparent->parent), &set, LYXP_WHEN);
/* reconnect nodes, if ctx_node is NULL then all the nodes were unlinked, but linked together,
* so the tree did not actually change and there is nothing for us to do
*/
if (unlinked_nodes && ctx_node) {
if (resolve_when_relink_nodes(ctx_node, unlinked_nodes, ctx_node_type)) {
rc = -1;
goto cleanup;
}
}
if (rc) {
if (rc == 1) {
LOGVAL(ctx, LYE_INWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond);
}
goto cleanup;
}
lyxp_set_cast(&set, LYXP_SET_BOOLEAN, ctx_node, lys_node_module(sparent->parent), LYXP_WHEN);
if (!set.val.bool) {
node->when_status |= LYD_WHEN_FALSE;
if ((ignore_fail == 1) || ((snode_get_when(sparent->parent)->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))
&& (ignore_fail == 2))) {
LOGVRB("When condition \"%s\" is not satisfied, but it is not required.",
snode_get_when(sparent->parent)->cond);
} else {
LOGVAL(ctx, LYE_NOWHEN, LY_VLOG_LYD, node, snode_get_when(sparent->parent)->cond);
if (failed_when) {
*failed_when = snode_get_when(sparent->parent);
}
goto cleanup;
}
}
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node, lys_node_module(sparent->parent), 0);
}
sparent = lys_parent(sparent);
}
node->when_status |= LYD_WHEN_TRUE;
cleanup:
/* free xpath set content */
lyxp_set_cast(&set, LYXP_SET_EMPTY, ctx_node ? ctx_node : node, NULL, 0);
return rc;
}
static int
check_type_union_leafref(struct lys_type *type)
{
uint8_t i;
if ((type->base == LY_TYPE_UNION) && type->info.uni.count) {
/* go through unions and look for leafref */
for (i = 0; i < type->info.uni.count; ++i) {
switch (type->info.uni.types[i].base) {
case LY_TYPE_LEAFREF:
return 1;
case LY_TYPE_UNION:
if (check_type_union_leafref(&type->info.uni.types[i])) {
return 1;
}
break;
default:
break;
}
}
return 0;
}
/* just inherit the flag value */
return type->der->has_union_leafref;
}
/**
* @brief Resolve a single unres schema item. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] item Item to resolve. Type determined by \p type.
* @param[in] type Type of the unresolved item.
* @param[in] str_snode String, a schema node, or NULL.
* @param[in] unres Unres schema structure to use.
* @param[in] final_fail Whether we are just printing errors of the failed unres items.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
static int
resolve_unres_schema_item(struct lys_module *mod, void *item, enum UNRES_ITEM type, void *str_snode,
struct unres_schema *unres)
{
/* has_str - whether the str_snode is a string in a dictionary that needs to be freed */
int rc = -1, has_str = 0, parent_type = 0, i, k;
unsigned int j;
struct ly_ctx * ctx = mod->ctx;
struct lys_node *root, *next, *node, *par_grp;
const char *expr;
uint8_t *u;
struct ly_set *refs, *procs;
struct lys_feature *ref, *feat;
struct lys_ident *ident;
struct lys_type *stype;
struct lys_node_choice *choic;
struct lyxml_elem *yin;
struct yang_type *yang;
struct unres_list_uniq *unique_info;
struct unres_iffeat_data *iff_data;
struct unres_ext *ext_data;
struct lys_ext_instance *ext, **extlist;
struct lyext_plugin *eplugin;
switch (type) {
case UNRES_IDENT:
expr = str_snode;
has_str = 1;
ident = item;
rc = resolve_base_ident(mod, ident, expr, "identity", NULL, unres);
break;
case UNRES_TYPE_IDENTREF:
expr = str_snode;
has_str = 1;
stype = item;
rc = resolve_base_ident(mod, NULL, expr, "type", stype, unres);
break;
case UNRES_TYPE_LEAFREF:
node = str_snode;
stype = item;
rc = resolve_schema_leafref(stype, node, unres);
break;
case UNRES_TYPE_DER_EXT:
parent_type++;
/* falls through */
case UNRES_TYPE_DER_TPDF:
parent_type++;
/* falls through */
case UNRES_TYPE_DER:
/* parent */
node = str_snode;
stype = item;
/* HACK type->der is temporarily unparsed type statement */
yin = (struct lyxml_elem *)stype->der;
stype->der = NULL;
if (yin->flags & LY_YANG_STRUCTURE_FLAG) {
yang = (struct yang_type *)yin;
rc = yang_check_type(mod, node, yang, stype, parent_type, unres);
if (rc) {
/* may try again later */
stype->der = (struct lys_tpdf *)yang;
} else {
/* we need to always be able to free this, it's safe only in this case */
lydict_remove(ctx, yang->name);
free(yang);
}
} else {
rc = fill_yin_type(mod, node, yin, stype, parent_type, unres);
if (!rc || rc == -1) {
/* we need to always be able to free this, it's safe only in this case */
lyxml_free(ctx, yin);
} else {
/* may try again later, put all back how it was */
stype->der = (struct lys_tpdf *)yin;
}
}
if (rc == EXIT_SUCCESS) {
/* it does not make sense to have leaf-list of empty type */
if (!parent_type && node->nodetype == LYS_LEAFLIST && stype->base == LY_TYPE_EMPTY) {
LOGWRN(ctx, "The leaf-list \"%s\" is of \"empty\" type, which does not make sense.", node->name);
}
if ((type == UNRES_TYPE_DER_TPDF) && (stype->base == LY_TYPE_UNION)) {
/* fill typedef union leafref flag */
((struct lys_tpdf *)stype->parent)->has_union_leafref = check_type_union_leafref(stype);
} else if ((type == UNRES_TYPE_DER) && stype->der->has_union_leafref) {
/* copy the type in case it has union leafref flag */
if (lys_copy_union_leafrefs(mod, node, stype, NULL, unres)) {
LOGERR(ctx, LY_EINT, "Failed to duplicate type.");
return -1;
}
}
} else if (rc == EXIT_FAILURE && !(stype->value_flags & LY_VALUE_UNRESGRP)) {
/* forward reference - in case the type is in grouping, we have to make the grouping unusable
* by uses statement until the type is resolved. We do that the same way as uses statements inside
* grouping. The grouping cannot be used unless the unres counter is 0.
* To remember that the grouping already increased the counter, the LYTYPE_GRP is used as value
* of the type's base member. */
for (par_grp = node; par_grp && (par_grp->nodetype != LYS_GROUPING); par_grp = lys_parent(par_grp));
if (par_grp) {
if (++((struct lys_node_grp *)par_grp)->unres_count == 0) {
LOGERR(ctx, LY_EINT, "Too many unresolved items (type) inside a grouping.");
return -1;
}
stype->value_flags |= LY_VALUE_UNRESGRP;
}
}
break;
case UNRES_IFFEAT:
iff_data = str_snode;
rc = resolve_feature(iff_data->fname, strlen(iff_data->fname), iff_data->node, item);
if (!rc) {
/* success */
if (iff_data->infeature) {
/* store backlink into the target feature to allow reverse changes in case of changing feature status */
feat = *((struct lys_feature **)item);
if (!feat->depfeatures) {
feat->depfeatures = ly_set_new();
}
ly_set_add(feat->depfeatures, iff_data->node, LY_SET_OPT_USEASLIST);
}
/* cleanup temporary data */
lydict_remove(ctx, iff_data->fname);
free(iff_data);
}
break;
case UNRES_FEATURE:
feat = (struct lys_feature *)item;
if (feat->iffeature_size) {
refs = ly_set_new();
procs = ly_set_new();
ly_set_add(procs, feat, 0);
while (procs->number) {
ref = procs->set.g[procs->number - 1];
ly_set_rm_index(procs, procs->number - 1);
for (i = 0; i < ref->iffeature_size; i++) {
resolve_iffeature_getsizes(&ref->iffeature[i], NULL, &j);
for (; j > 0 ; j--) {
if (ref->iffeature[i].features[j - 1]) {
if (ref->iffeature[i].features[j - 1] == feat) {
LOGVAL(ctx, LYE_CIRC_FEATURES, LY_VLOG_NONE, NULL, feat->name);
goto featurecheckdone;
}
if (ref->iffeature[i].features[j - 1]->iffeature_size) {
k = refs->number;
if (ly_set_add(refs, ref->iffeature[i].features[j - 1], 0) == k) {
/* not yet seen feature, add it for processing */
ly_set_add(procs, ref->iffeature[i].features[j - 1], 0);
}
}
} else {
/* forward reference */
rc = EXIT_FAILURE;
goto featurecheckdone;
}
}
}
}
rc = EXIT_SUCCESS;
featurecheckdone:
ly_set_free(refs);
ly_set_free(procs);
}
break;
case UNRES_USES:
rc = resolve_unres_schema_uses(item, unres);
break;
case UNRES_TYPEDEF_DFLT:
parent_type++;
/* falls through */
case UNRES_TYPE_DFLT:
stype = item;
rc = check_default(stype, (const char **)str_snode, mod, parent_type);
if ((rc == EXIT_FAILURE) && !parent_type && (stype->base == LY_TYPE_LEAFREF)) {
for (par_grp = (struct lys_node *)stype->parent;
par_grp && (par_grp->nodetype != LYS_GROUPING);
par_grp = lys_parent(par_grp));
if (par_grp) {
/* checking default value in a grouping finished with forward reference means we cannot check the value */
rc = EXIT_SUCCESS;
}
}
break;
case UNRES_CHOICE_DFLT:
expr = str_snode;
has_str = 1;
choic = item;
if (!choic->dflt) {
choic->dflt = resolve_choice_dflt(choic, expr);
}
if (choic->dflt) {
rc = lyp_check_mandatory_choice((struct lys_node *)choic);
} else {
rc = EXIT_FAILURE;
}
break;
case UNRES_LIST_KEYS:
rc = resolve_list_keys(item, ((struct lys_node_list *)item)->keys_str);
break;
case UNRES_LIST_UNIQ:
unique_info = (struct unres_list_uniq *)item;
rc = resolve_unique(unique_info->list, unique_info->expr, unique_info->trg_type);
break;
case UNRES_AUGMENT:
rc = resolve_augment(item, NULL, unres);
break;
case UNRES_XPATH:
node = (struct lys_node *)item;
rc = check_xpath(node, 1);
break;
case UNRES_MOD_IMPLEMENT:
rc = lys_make_implemented_r(mod, unres);
break;
case UNRES_EXT:
ext_data = (struct unres_ext *)str_snode;
extlist = &(*(struct lys_ext_instance ***)item)[ext_data->ext_index];
rc = resolve_extension(ext_data, extlist, unres);
if (!rc) {
/* success */
/* is there a callback to be done to finalize the extension? */
eplugin = extlist[0]->def->plugin;
if (eplugin) {
if (eplugin->check_result || (eplugin->flags & LYEXT_OPT_INHERIT)) {
u = malloc(sizeof *u);
LY_CHECK_ERR_RETURN(!u, LOGMEM(ctx), -1);
(*u) = ext_data->ext_index;
if (unres_schema_add_node(mod, unres, item, UNRES_EXT_FINALIZE, (struct lys_node *)u) == -1) {
/* something really bad happend since the extension finalization is not actually
* being resolved while adding into unres, so something more serious with the unres
* list itself must happened */
return -1;
}
}
}
}
if (!rc || rc == -1) {
/* cleanup on success or fatal error */
if (ext_data->datatype == LYS_IN_YIN) {
/* YIN */
lyxml_free(ctx, ext_data->data.yin);
} else {
/* YANG */
yang_free_ext_data(ext_data->data.yang);
}
free(ext_data);
}
break;
case UNRES_EXT_FINALIZE:
u = (uint8_t *)str_snode;
ext = (*(struct lys_ext_instance ***)item)[*u];
free(u);
eplugin = ext->def->plugin;
/* inherit */
if ((eplugin->flags & LYEXT_OPT_INHERIT) && (ext->parent_type == LYEXT_PAR_NODE)) {
root = (struct lys_node *)ext->parent;
if (!(root->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
LY_TREE_DFS_BEGIN(root->child, next, node) {
/* first, check if the node already contain instance of the same extension,
* in such a case we won't inherit. In case the node was actually defined as
* augment data, we are supposed to check the same way also the augment node itself */
if (lys_ext_instance_presence(ext->def, node->ext, node->ext_size) != -1) {
goto inherit_dfs_sibling;
} else if (node->parent != root && node->parent->nodetype == LYS_AUGMENT &&
lys_ext_instance_presence(ext->def, node->parent->ext, node->parent->ext_size) != -1) {
goto inherit_dfs_sibling;
}
if (eplugin->check_inherit) {
/* we have a callback to check the inheritance, use it */
switch ((rc = (*eplugin->check_inherit)(ext, node))) {
case 0:
/* yes - continue with the inheriting code */
break;
case 1:
/* no - continue with the node's sibling */
goto inherit_dfs_sibling;
case 2:
/* no, but continue with the children, just skip the inheriting code for this node */
goto inherit_dfs_child;
default:
LOGERR(ctx, LY_EINT, "Plugin's (%s:%s) check_inherit callback returns invalid value (%d),",
ext->def->module->name, ext->def->name, rc);
}
}
/* inherit the extension */
extlist = realloc(node->ext, (node->ext_size + 1) * sizeof *node->ext);
LY_CHECK_ERR_RETURN(!extlist, LOGMEM(ctx), -1);
extlist[node->ext_size] = malloc(sizeof **extlist);
LY_CHECK_ERR_RETURN(!extlist[node->ext_size], LOGMEM(ctx); node->ext = extlist, -1);
memcpy(extlist[node->ext_size], ext, sizeof *ext);
extlist[node->ext_size]->flags |= LYEXT_OPT_INHERIT;
node->ext = extlist;
node->ext_size++;
inherit_dfs_child:
/* modification of - select element for the next run - children first */
if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next = NULL;
} else {
next = node->child;
}
if (!next) {
inherit_dfs_sibling:
/* no children, try siblings */
next = node->next;
}
while (!next) {
/* go to the parent */
node = lys_parent(node);
/* we are done if we are back in the root (the starter's parent */
if (node == root) {
break;
}
/* parent is already processed, go to its sibling */
next = node->next;
}
}
}
}
/* final check */
if (eplugin->check_result) {
if ((*eplugin->check_result)(ext)) {
LOGERR(ctx, LY_EPLUGIN, "Resolving extension failed.");
return -1;
}
}
rc = 0;
break;
default:
LOGINT(ctx);
break;
}
if (has_str && !rc) {
/* the string is no more needed in case of success.
* In case of forward reference, we will try to resolve the string later */
lydict_remove(ctx, str_snode);
}
return rc;
}
/* logs directly */
static void
print_unres_schema_item_fail(void *item, enum UNRES_ITEM type, void *str_node)
{
struct lyxml_elem *xml;
struct lyxml_attr *attr;
struct unres_iffeat_data *iff_data;
const char *name = NULL;
struct unres_ext *extinfo;
switch (type) {
case UNRES_IDENT:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identity", (char *)str_node);
break;
case UNRES_TYPE_IDENTREF:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "identityref", (char *)str_node);
break;
case UNRES_TYPE_LEAFREF:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "leafref",
((struct lys_type *)item)->info.lref.path);
break;
case UNRES_TYPE_DER_EXT:
case UNRES_TYPE_DER_TPDF:
case UNRES_TYPE_DER:
xml = (struct lyxml_elem *)((struct lys_type *)item)->der;
if (xml->flags & LY_YANG_STRUCTURE_FLAG) {
name = ((struct yang_type *)xml)->name;
} else {
LY_TREE_FOR(xml->attr, attr) {
if ((attr->type == LYXML_ATTR_STD) && !strcmp(attr->name, "name")) {
name = attr->value;
break;
}
}
assert(attr);
}
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "derived type", name);
break;
case UNRES_IFFEAT:
iff_data = str_node;
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "if-feature", iff_data->fname);
break;
case UNRES_FEATURE:
LOGVRB("There are unresolved if-features for \"%s\" feature circular dependency check, it will be attempted later",
((struct lys_feature *)item)->name);
break;
case UNRES_USES:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "uses", ((struct lys_node_uses *)item)->name);
break;
case UNRES_TYPEDEF_DFLT:
case UNRES_TYPE_DFLT:
if (*(char **)str_node) {
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "type default", *(char **)str_node);
} /* else no default value in the type itself, but we are checking some restrictions against
* possible default value of some base type. The failure is caused by not resolved base type,
* so it was already reported */
break;
case UNRES_CHOICE_DFLT:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "choice default", (char *)str_node);
break;
case UNRES_LIST_KEYS:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list keys", (char *)str_node);
break;
case UNRES_LIST_UNIQ:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "list unique", (char *)str_node);
break;
case UNRES_AUGMENT:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "augment target",
((struct lys_node_augment *)item)->target_name);
break;
case UNRES_XPATH:
LOGVRB("Resolving %s \"%s\" failed, it will be attempted later.", "XPath expressions of",
((struct lys_node *)item)->name);
break;
case UNRES_EXT:
extinfo = (struct unres_ext *)str_node;
name = extinfo->datatype == LYS_IN_YIN ? extinfo->data.yin->name : NULL; /* TODO YANG extension */
LOGVRB("Resolving extension \"%s\" failed, it will be attempted later.", name);
break;
default:
LOGINT(NULL);
break;
}
}
static int
resolve_unres_schema_types(struct unres_schema *unres, enum UNRES_ITEM types, struct ly_ctx *ctx, int forward_ref,
int print_all_errors, uint32_t *resolved)
{
uint32_t i, unres_count, res_count;
int ret = 0, rc;
struct ly_err_item *prev_eitem;
enum int_log_opts prev_ilo;
LY_ERR prev_ly_errno;
/* if there can be no forward references, every failure is final, so we can print it directly */
if (forward_ref) {
prev_ly_errno = ly_errno;
ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem);
}
do {
unres_count = 0;
res_count = 0;
for (i = 0; i < unres->count; ++i) {
/* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers);
* if-features are resolved here to make sure that we will have all if-features for
* later check of feature circular dependency */
if (unres->type[i] & types) {
++unres_count;
rc = resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres);
if (unres->type[i] == UNRES_EXT_FINALIZE) {
/* to avoid double free */
unres->type[i] = UNRES_RESOLVED;
}
if (!rc || (unres->type[i] == UNRES_XPATH)) {
/* invalid XPath can never cause an error, only a warning */
if (unres->type[i] == UNRES_LIST_UNIQ) {
/* free the allocated structure */
free(unres->item[i]);
}
unres->type[i] = UNRES_RESOLVED;
++(*resolved);
++res_count;
} else if ((rc == EXIT_FAILURE) && forward_ref) {
/* forward reference, erase errors */
ly_err_free_next(ctx, prev_eitem);
} else if (print_all_errors) {
/* just so that we quit the loop */
++res_count;
ret = -1;
} else {
if (forward_ref) {
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1);
}
return -1;
}
}
}
} while (res_count && (res_count < unres_count));
if (res_count < unres_count) {
assert(forward_ref);
/* just print the errors (but we must free the ones we have and get them again :-/ ) */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
for (i = 0; i < unres->count; ++i) {
if (unres->type[i] & types) {
resolve_unres_schema_item(unres->module[i], unres->item[i], unres->type[i], unres->str_snode[i], unres);
}
}
return -1;
}
if (forward_ref) {
/* restore log */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
return ret;
}
/**
* @brief Resolve every unres schema item in the structure. Logs directly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
int
resolve_unres_schema(struct lys_module *mod, struct unres_schema *unres)
{
uint32_t resolved = 0;
assert(unres);
LOGVRB("Resolving \"%s\" unresolved schema nodes and their constraints...", mod->name);
/* UNRES_TYPE_LEAFREF must be resolved (for storing leafref target pointers);
* if-features are resolved here to make sure that we will have all if-features for
* later check of feature circular dependency */
if (resolve_unres_schema_types(unres, UNRES_USES | UNRES_IFFEAT | UNRES_TYPE_DER | UNRES_TYPE_DER_TPDF | UNRES_TYPE_DER_TPDF
| UNRES_TYPE_LEAFREF | UNRES_MOD_IMPLEMENT | UNRES_AUGMENT | UNRES_CHOICE_DFLT | UNRES_IDENT,
mod->ctx, 1, 0, &resolved)) {
return -1;
}
/* another batch of resolved items */
if (resolve_unres_schema_types(unres, UNRES_TYPE_IDENTREF | UNRES_FEATURE | UNRES_TYPEDEF_DFLT | UNRES_TYPE_DFLT
| UNRES_LIST_KEYS | UNRES_LIST_UNIQ | UNRES_EXT, mod->ctx, 1, 0, &resolved)) {
return -1;
}
/* print xpath warnings and finalize extensions, keep it last to provide the complete schema tree information to the plugin's checkers */
if (resolve_unres_schema_types(unres, UNRES_XPATH | UNRES_EXT_FINALIZE, mod->ctx, 0, 1, &resolved)) {
return -1;
}
LOGVRB("All \"%s\" schema nodes and constraints resolved.", mod->name);
unres->count = 0;
return EXIT_SUCCESS;
}
/**
* @brief Try to resolve an unres schema item with a string argument. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
* @param[in] item Item to resolve. Type determined by \p type.
* @param[in] type Type of the unresolved item.
* @param[in] str String argument.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error.
*/
int
unres_schema_add_str(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type,
const char *str)
{
int rc;
const char *dictstr;
dictstr = lydict_insert(mod->ctx, str, 0);
rc = unres_schema_add_node(mod, unres, item, type, (struct lys_node *)dictstr);
if (rc < 0) {
lydict_remove(mod->ctx, dictstr);
}
return rc;
}
/**
* @brief Try to resolve an unres schema item with a schema node argument. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
* @param[in] item Item to resolve. Type determined by \p type.
* @param[in] type Type of the unresolved item. UNRES_TYPE_DER is handled specially!
* @param[in] snode Schema node argument.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on storing the item in unres, -1 on error.
*/
int
unres_schema_add_node(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type,
struct lys_node *snode)
{
int rc;
uint32_t u;
enum int_log_opts prev_ilo;
struct ly_err_item *prev_eitem;
LY_ERR prev_ly_errno;
struct lyxml_elem *yin;
struct ly_ctx *ctx = mod->ctx;
assert(unres && (item || (type == UNRES_MOD_IMPLEMENT)) && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID)
&& (type != UNRES_WHEN) && (type != UNRES_MUST)));
/* check for duplicities in unres */
for (u = 0; u < unres->count; u++) {
if (unres->type[u] == type && unres->item[u] == item &&
unres->str_snode[u] == snode && unres->module[u] == mod) {
/* duplication can happen when the node contains multiple statements of the same type to check,
* this can happen for example when refinement is being applied, so we just postpone the processing
* and do not duplicate the information */
return EXIT_FAILURE;
}
}
if ((type == UNRES_EXT_FINALIZE) || (type == UNRES_XPATH) || (type == UNRES_MOD_IMPLEMENT)) {
/* extension finalization is not even tried when adding the item into the inres list,
* xpath is not tried because it would hide some potential warnings,
* implementing module must be deferred because some other nodes can be added that will need to be traversed
* and their targets made implemented */
rc = EXIT_FAILURE;
} else {
prev_ly_errno = ly_errno;
ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem);
rc = resolve_unres_schema_item(mod, item, type, snode, unres);
if (rc != EXIT_FAILURE) {
ly_ilo_restore(ctx, prev_ilo, prev_eitem, rc == -1 ? 1 : 0);
if (rc != -1) {
ly_errno = prev_ly_errno;
}
if (type == UNRES_LIST_UNIQ) {
/* free the allocated structure */
free(item);
} else if (rc == -1 && type == UNRES_IFFEAT) {
/* free the allocated resources */
free(*((char **)item));
}
return rc;
} else {
/* erase info about validation errors */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
print_unres_schema_item_fail(item, type, snode);
/* HACK unlinking is performed here so that we do not do any (NS) copying in vain */
if (type == UNRES_TYPE_DER || type == UNRES_TYPE_DER_TPDF) {
yin = (struct lyxml_elem *)((struct lys_type *)item)->der;
if (!(yin->flags & LY_YANG_STRUCTURE_FLAG)) {
lyxml_unlink_elem(mod->ctx, yin, 1);
((struct lys_type *)item)->der = (struct lys_tpdf *)yin;
}
}
}
unres->count++;
unres->item = ly_realloc(unres->item, unres->count*sizeof *unres->item);
LY_CHECK_ERR_RETURN(!unres->item, LOGMEM(ctx), -1);
unres->item[unres->count-1] = item;
unres->type = ly_realloc(unres->type, unres->count*sizeof *unres->type);
LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(ctx), -1);
unres->type[unres->count-1] = type;
unres->str_snode = ly_realloc(unres->str_snode, unres->count*sizeof *unres->str_snode);
LY_CHECK_ERR_RETURN(!unres->str_snode, LOGMEM(ctx), -1);
unres->str_snode[unres->count-1] = snode;
unres->module = ly_realloc(unres->module, unres->count*sizeof *unres->module);
LY_CHECK_ERR_RETURN(!unres->module, LOGMEM(ctx), -1);
unres->module[unres->count-1] = mod;
return rc;
}
/**
* @brief Duplicate an unres schema item. Logs indirectly.
*
* @param[in] mod Main module.
* @param[in] unres Unres schema structure to use.
* @param[in] item Old item to be resolved.
* @param[in] type Type of the old unresolved item.
* @param[in] new_item New item to use in the duplicate.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE if item is not in unres, -1 on error.
*/
int
unres_schema_dup(struct lys_module *mod, struct unres_schema *unres, void *item, enum UNRES_ITEM type, void *new_item)
{
int i;
struct unres_list_uniq aux_uniq;
struct unres_iffeat_data *iff_data;
assert(item && new_item && ((type != UNRES_LEAFREF) && (type != UNRES_INSTID) && (type != UNRES_WHEN)));
/* hack for UNRES_LIST_UNIQ, which stores multiple items behind its item */
if (type == UNRES_LIST_UNIQ) {
aux_uniq.list = item;
aux_uniq.expr = ((struct unres_list_uniq *)new_item)->expr;
item = &aux_uniq;
}
i = unres_schema_find(unres, -1, item, type);
if (i == -1) {
if (type == UNRES_LIST_UNIQ) {
free(new_item);
}
return EXIT_FAILURE;
}
if ((type == UNRES_TYPE_LEAFREF) || (type == UNRES_USES) || (type == UNRES_TYPE_DFLT) ||
(type == UNRES_FEATURE) || (type == UNRES_LIST_UNIQ)) {
if (unres_schema_add_node(mod, unres, new_item, type, unres->str_snode[i]) == -1) {
LOGINT(mod->ctx);
return -1;
}
} else if (type == UNRES_IFFEAT) {
/* duplicate unres_iffeature_data */
iff_data = malloc(sizeof *iff_data);
LY_CHECK_ERR_RETURN(!iff_data, LOGMEM(mod->ctx), -1);
iff_data->fname = lydict_insert(mod->ctx, ((struct unres_iffeat_data *)unres->str_snode[i])->fname, 0);
iff_data->node = ((struct unres_iffeat_data *)unres->str_snode[i])->node;
if (unres_schema_add_node(mod, unres, new_item, type, (struct lys_node *)iff_data) == -1) {
LOGINT(mod->ctx);
return -1;
}
} else {
if (unres_schema_add_str(mod, unres, new_item, type, unres->str_snode[i]) == -1) {
LOGINT(mod->ctx);
return -1;
}
}
return EXIT_SUCCESS;
}
/* does not log */
int
unres_schema_find(struct unres_schema *unres, int start_on_backwards, void *item, enum UNRES_ITEM type)
{
int i;
struct unres_list_uniq *aux_uniq1, *aux_uniq2;
if (!unres->count) {
return -1;
}
if (start_on_backwards >= 0) {
i = start_on_backwards;
} else {
i = unres->count - 1;
}
for (; i > -1; i--) {
if (unres->type[i] != type) {
continue;
}
if (type != UNRES_LIST_UNIQ) {
if (unres->item[i] == item) {
break;
}
} else {
aux_uniq1 = (struct unres_list_uniq *)unres->item[i];
aux_uniq2 = (struct unres_list_uniq *)item;
if ((aux_uniq1->list == aux_uniq2->list) && ly_strequal(aux_uniq1->expr, aux_uniq2->expr, 0)) {
break;
}
}
}
return i;
}
static void
unres_schema_free_item(struct ly_ctx *ctx, struct unres_schema *unres, uint32_t i)
{
struct lyxml_elem *yin;
struct yang_type *yang;
struct unres_iffeat_data *iff_data;
switch (unres->type[i]) {
case UNRES_TYPE_DER_TPDF:
case UNRES_TYPE_DER:
yin = (struct lyxml_elem *)((struct lys_type *)unres->item[i])->der;
if (yin->flags & LY_YANG_STRUCTURE_FLAG) {
yang =(struct yang_type *)yin;
((struct lys_type *)unres->item[i])->base = yang->base;
lydict_remove(ctx, yang->name);
free(yang);
if (((struct lys_type *)unres->item[i])->base == LY_TYPE_UNION) {
yang_free_type_union(ctx, (struct lys_type *)unres->item[i]);
}
} else {
lyxml_free(ctx, yin);
}
break;
case UNRES_IFFEAT:
iff_data = (struct unres_iffeat_data *)unres->str_snode[i];
lydict_remove(ctx, iff_data->fname);
free(unres->str_snode[i]);
break;
case UNRES_IDENT:
case UNRES_TYPE_IDENTREF:
case UNRES_CHOICE_DFLT:
case UNRES_LIST_KEYS:
lydict_remove(ctx, (const char *)unres->str_snode[i]);
break;
case UNRES_LIST_UNIQ:
free(unres->item[i]);
break;
case UNRES_EXT:
free(unres->str_snode[i]);
break;
case UNRES_EXT_FINALIZE:
free(unres->str_snode[i]);
default:
break;
}
unres->type[i] = UNRES_RESOLVED;
}
void
unres_schema_free(struct lys_module *module, struct unres_schema **unres, int all)
{
uint32_t i;
unsigned int unresolved = 0;
if (!unres || !(*unres)) {
return;
}
assert(module || ((*unres)->count == 0));
for (i = 0; i < (*unres)->count; ++i) {
if (!all && ((*unres)->module[i] != module)) {
if ((*unres)->type[i] != UNRES_RESOLVED) {
unresolved++;
}
continue;
}
/* free heap memory for the specific item */
unres_schema_free_item(module->ctx, *unres, i);
}
/* free it all */
if (!module || all || (!unresolved && !module->type)) {
free((*unres)->item);
free((*unres)->type);
free((*unres)->str_snode);
free((*unres)->module);
free((*unres));
(*unres) = NULL;
}
}
/* check whether instance-identifier points outside its data subtree (for operation it is any node
* outside the operation subtree, otherwise it is a node from a foreign model) */
static int
check_instid_ext_dep(const struct lys_node *sleaf, const char *json_instid)
{
const struct lys_node *op_node, *first_node;
enum int_log_opts prev_ilo;
char *buf, *tmp;
if (!json_instid || !json_instid[0]) {
/* no/empty value */
return 0;
}
for (op_node = lys_parent(sleaf);
op_node && !(op_node->nodetype & (LYS_NOTIF | LYS_RPC | LYS_ACTION));
op_node = lys_parent(op_node));
if (op_node && lys_parent(op_node)) {
/* nested operation - any absolute path is external */
return 1;
}
/* get the first node from the instid */
tmp = strchr(json_instid + 1, '/');
buf = strndup(json_instid, tmp ? (size_t)(tmp - json_instid) : strlen(json_instid));
if (!buf) {
/* so that we do not have to bother with logging, say it is not external */
return 0;
}
/* find the first schema node, do not log */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
first_node = ly_ctx_get_node(NULL, sleaf, buf, 0);
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
free(buf);
if (!first_node) {
/* unknown path, say it is external */
return 1;
}
/* based on the first schema node in the path we can decide whether it points to an external tree or not */
if (op_node) {
if (op_node != first_node) {
/* it is a top-level operation, so we're good if it points somewhere inside it */
return 1;
}
} else {
if (lys_node_module(sleaf) != lys_node_module(first_node)) {
/* modules differ */
return 1;
}
}
return 0;
}
/**
* @brief Resolve instance-identifier in JSON data format. Logs directly.
*
* @param[in] data Data node where the path is used
* @param[in] path Instance-identifier node value.
* @param[in,out] ret Resolved instance or NULL.
*
* @return 0 on success (even if unresolved and \p ret is NULL), -1 on error.
*/
static int
resolve_instid(struct lyd_node *data, const char *path, int req_inst, struct lyd_node **ret)
{
int i = 0, j, parsed, cur_idx;
const struct lys_module *mod, *prev_mod = NULL;
struct ly_ctx *ctx = data->schema->module->ctx;
struct lyd_node *root, *node;
const char *model = NULL, *name;
char *str;
int mod_len, name_len, has_predicate;
struct unres_data node_match;
memset(&node_match, 0, sizeof node_match);
*ret = NULL;
/* we need root to resolve absolute path */
for (root = data; root->parent; root = root->parent);
/* we're still parsing it and the pointer is not correct yet */
if (root->prev) {
for (; root->prev->next; root = root->prev);
}
/* search for the instance node */
while (path[i]) {
j = parse_instance_identifier(&path[i], &model, &mod_len, &name, &name_len, &has_predicate);
if (j <= 0) {
LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, data, path[i-j], &path[i-j]);
goto error;
}
i += j;
if (model) {
str = strndup(model, mod_len);
if (!str) {
LOGMEM(ctx);
goto error;
}
mod = ly_ctx_get_module(ctx, str, NULL, 1);
if (ctx->data_clb) {
if (!mod) {
mod = ctx->data_clb(ctx, str, NULL, 0, ctx->data_clb_data);
} else if (!mod->implemented) {
mod = ctx->data_clb(ctx, mod->name, mod->ns, LY_MODCLB_NOT_IMPLEMENTED, ctx->data_clb_data);
}
}
free(str);
if (!mod || !mod->implemented || mod->disabled) {
break;
}
} else if (!prev_mod) {
/* first iteration and we are missing module name */
LOGVAL(ctx, LYE_INELEM_LEN, LY_VLOG_LYD, data, name_len, name);
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Instance-identifier is missing prefix in the first node.");
goto error;
} else {
mod = prev_mod;
}
if (resolve_data(mod, name, name_len, root, &node_match)) {
/* no instance exists */
break;
}
if (has_predicate) {
/* we have predicate, so the current results must be list or leaf-list */
parsed = j = 0;
/* index of the current node (for lists with position predicates) */
cur_idx = 1;
while (j < (signed)node_match.count) {
node = node_match.node[j];
parsed = resolve_instid_predicate(mod, &path[i], &node, cur_idx);
if (parsed < 1) {
LOGVAL(ctx, LYE_INPRED, LY_VLOG_LYD, data, &path[i - parsed]);
goto error;
}
if (!node) {
/* current node does not satisfy the predicate */
unres_data_del(&node_match, j);
} else {
++j;
}
++cur_idx;
}
i += parsed;
} else if (node_match.count) {
/* check that we are not addressing lists */
for (j = 0; (unsigned)j < node_match.count; ++j) {
if (node_match.node[j]->schema->nodetype == LYS_LIST) {
unres_data_del(&node_match, j--);
}
}
if (!node_match.count) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYD, data, "Instance identifier is missing list keys.");
}
}
prev_mod = mod;
}
if (!node_match.count) {
/* no instance exists */
if (req_inst > -1) {
LOGVAL(ctx, LYE_NOREQINS, LY_VLOG_LYD, data, path);
return EXIT_FAILURE;
}
LOGVRB("There is no instance of \"%s\", but it is not required.", path);
return EXIT_SUCCESS;
} else if (node_match.count > 1) {
/* instance identifier must resolve to a single node */
LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, data, path, "data tree");
goto error;
} else {
/* we have required result, remember it and cleanup */
*ret = node_match.node[0];
free(node_match.node);
return EXIT_SUCCESS;
}
error:
/* cleanup */
free(node_match.node);
return -1;
}
static int
resolve_leafref(struct lyd_node_leaf_list *leaf, const char *path, int req_inst, struct lyd_node **ret)
{
struct lyxp_set xp_set;
uint32_t i;
memset(&xp_set, 0, sizeof xp_set);
*ret = NULL;
/* syntax was already checked, so just evaluate the path using standard XPath */
if (lyxp_eval(path, (struct lyd_node *)leaf, LYXP_NODE_ELEM, lyd_node_module((struct lyd_node *)leaf), &xp_set, 0) != EXIT_SUCCESS) {
return -1;
}
if (xp_set.type == LYXP_SET_NODE_SET) {
for (i = 0; i < xp_set.used; ++i) {
if ((xp_set.val.nodes[i].type != LYXP_NODE_ELEM) || !(xp_set.val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
continue;
}
/* not that the value is already in canonical form since the parsers does the conversion,
* so we can simply compare just the values */
if (ly_strequal(leaf->value_str, ((struct lyd_node_leaf_list *)xp_set.val.nodes[i].node)->value_str, 1)) {
/* we have the match */
*ret = xp_set.val.nodes[i].node;
break;
}
}
}
lyxp_set_cast(&xp_set, LYXP_SET_EMPTY, (struct lyd_node *)leaf, NULL, 0);
if (!*ret) {
/* reference not found */
if (req_inst > -1) {
LOGVAL(leaf->schema->module->ctx, LYE_NOLEAFREF, LY_VLOG_LYD, leaf, path, leaf->value_str);
return EXIT_FAILURE;
} else {
LOGVRB("There is no leafref \"%s\" with the value \"%s\", but it is not required.", path, leaf->value_str);
}
}
return EXIT_SUCCESS;
}
/* ignore fail because we are parsing edit-config, get, or get-config - but only if the union includes leafref or instid */
int
resolve_union(struct lyd_node_leaf_list *leaf, struct lys_type *type, int store, int ignore_fail,
struct lys_type **resolved_type)
{
struct ly_ctx *ctx = leaf->schema->module->ctx;
struct lys_type *t;
struct lyd_node *ret;
enum int_log_opts prev_ilo;
int found, success = 0, ext_dep, req_inst;
const char *json_val = NULL;
assert(type->base == LY_TYPE_UNION);
if ((leaf->value_type == LY_TYPE_UNION) || ((leaf->value_type == LY_TYPE_INST) && (leaf->value_flags & LY_VALUE_UNRES))) {
/* either NULL or instid previously converted to JSON */
json_val = lydict_insert(ctx, leaf->value.string, 0);
}
if (store) {
lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, &((struct lys_node_leaf *)leaf->schema)->type,
NULL, NULL, NULL);
memset(&leaf->value, 0, sizeof leaf->value);
}
/* turn logging off, we are going to try to validate the value with all the types in order */
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, 0);
t = NULL;
found = 0;
while ((t = lyp_get_next_union_type(type, t, &found))) {
found = 0;
switch (t->base) {
case LY_TYPE_LEAFREF:
if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = t->info.lref.req;
}
if (!resolve_leafref(leaf, t->info.lref.path, req_inst, &ret)) {
if (store) {
if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) {
/* valid resolved */
leaf->value.leafref = ret;
leaf->value_type = LY_TYPE_LEAFREF;
} else {
/* valid unresolved */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (!lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) {
return -1;
}
ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
}
}
success = 1;
}
break;
case LY_TYPE_INST:
ext_dep = check_instid_ext_dep(leaf->schema, (json_val ? json_val : leaf->value_str));
if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = t->info.inst.req;
}
if (!resolve_instid((struct lyd_node *)leaf, (json_val ? json_val : leaf->value_str), req_inst, &ret)) {
if (store) {
if (ret && !ext_dep) {
/* valid resolved */
leaf->value.instance = ret;
leaf->value_type = LY_TYPE_INST;
if (json_val) {
lydict_remove(leaf->schema->module->ctx, leaf->value_str);
leaf->value_str = json_val;
json_val = NULL;
}
} else {
/* valid unresolved */
if (json_val) {
/* put the JSON val back */
leaf->value.string = json_val;
json_val = NULL;
} else {
leaf->value.instance = NULL;
}
leaf->value_type = LY_TYPE_INST;
leaf->value_flags |= LY_VALUE_UNRES;
}
}
success = 1;
}
break;
default:
if (lyp_parse_value(t, &leaf->value_str, NULL, leaf, NULL, NULL, store, 0, 0)) {
success = 1;
}
break;
}
if (success) {
break;
}
/* erase possible present and invalid value data */
if (store) {
lyd_free_value(leaf->value, leaf->value_type, leaf->value_flags, t, NULL, NULL, NULL);
memset(&leaf->value, 0, sizeof leaf->value);
}
}
/* turn logging back on */
ly_ilo_restore(NULL, prev_ilo, NULL, 0);
if (json_val) {
if (!success) {
/* put the value back for now */
assert(leaf->value_type == LY_TYPE_UNION);
leaf->value.string = json_val;
} else {
/* value was ultimately useless, but we could not have known */
lydict_remove(leaf->schema->module->ctx, json_val);
}
}
if (success) {
if (resolved_type) {
*resolved_type = t;
}
} else if (!ignore_fail || !type->info.uni.has_ptr_type) {
/* not found and it is required */
LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, leaf, leaf->value_str ? leaf->value_str : "", leaf->schema->name);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* @brief Resolve a single unres data item. Logs directly.
*
* @param[in] node Data node to resolve.
* @param[in] type Type of the unresolved item.
* @param[in] ignore_fail 0 - no, 1 - yes, 2 - yes, but only for external dependencies.
*
* @return EXIT_SUCCESS on success, EXIT_FAILURE on forward reference, -1 on error.
*/
int
resolve_unres_data_item(struct lyd_node *node, enum UNRES_ITEM type, int ignore_fail, struct lys_when **failed_when)
{
int rc, req_inst, ext_dep;
struct lyd_node_leaf_list *leaf;
struct lyd_node *ret;
struct lys_node_leaf *sleaf;
leaf = (struct lyd_node_leaf_list *)node;
sleaf = (struct lys_node_leaf *)leaf->schema;
switch (type) {
case UNRES_LEAFREF:
assert(sleaf->type.base == LY_TYPE_LEAFREF);
assert(leaf->validity & LYD_VAL_LEAFREF);
if ((ignore_fail == 1) || ((leaf->schema->flags & LYS_LEAFREF_DEP) && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = sleaf->type.info.lref.req;
}
rc = resolve_leafref(leaf, sleaf->type.info.lref.path, req_inst, &ret);
if (!rc) {
if (ret && !(leaf->schema->flags & LYS_LEAFREF_DEP)) {
/* valid resolved */
if (leaf->value_type == LY_TYPE_BITS) {
free(leaf->value.bit);
}
leaf->value.leafref = ret;
leaf->value_type = LY_TYPE_LEAFREF;
leaf->value_flags &= ~LY_VALUE_UNRES;
} else {
/* valid unresolved */
if (!(leaf->value_flags & LY_VALUE_UNRES)) {
if (!lyp_parse_value(&sleaf->type, &leaf->value_str, NULL, leaf, NULL, NULL, 1, 0, 0)) {
return -1;
}
}
}
leaf->validity &= ~LYD_VAL_LEAFREF;
} else {
return rc;
}
break;
case UNRES_INSTID:
assert(sleaf->type.base == LY_TYPE_INST);
ext_dep = check_instid_ext_dep(leaf->schema, leaf->value_str);
if (ext_dep == -1) {
return -1;
}
if ((ignore_fail == 1) || (ext_dep && (ignore_fail == 2))) {
req_inst = -1;
} else {
req_inst = sleaf->type.info.inst.req;
}
rc = resolve_instid(node, leaf->value_str, req_inst, &ret);
if (!rc) {
if (ret && !ext_dep) {
/* valid resolved */
leaf->value.instance = ret;
leaf->value_type = LY_TYPE_INST;
leaf->value_flags &= ~LY_VALUE_UNRES;
} else {
/* valid unresolved */
leaf->value.instance = NULL;
leaf->value_type = LY_TYPE_INST;
leaf->value_flags |= LY_VALUE_UNRES;
}
} else {
return rc;
}
break;
case UNRES_UNION:
assert(sleaf->type.base == LY_TYPE_UNION);
return resolve_union(leaf, &sleaf->type, 1, ignore_fail, NULL);
case UNRES_WHEN:
if ((rc = resolve_when(node, ignore_fail, failed_when))) {
return rc;
}
break;
case UNRES_MUST:
if ((rc = resolve_must(node, 0, ignore_fail))) {
return rc;
}
break;
case UNRES_MUST_INOUT:
if ((rc = resolve_must(node, 1, ignore_fail))) {
return rc;
}
break;
case UNRES_UNIQ_LEAVES:
if (lyv_data_unique(node)) {
return -1;
}
break;
default:
LOGINT(NULL);
return -1;
}
return EXIT_SUCCESS;
}
/**
* @brief add data unres item
*
* @param[in] unres Unres data structure to use.
* @param[in] node Data node to use.
*
* @return 0 on success, -1 on error.
*/
int
unres_data_add(struct unres_data *unres, struct lyd_node *node, enum UNRES_ITEM type)
{
assert(unres && node);
assert((type == UNRES_LEAFREF) || (type == UNRES_INSTID) || (type == UNRES_WHEN) || (type == UNRES_MUST)
|| (type == UNRES_MUST_INOUT) || (type == UNRES_UNION) || (type == UNRES_UNIQ_LEAVES));
unres->count++;
unres->node = ly_realloc(unres->node, unres->count * sizeof *unres->node);
LY_CHECK_ERR_RETURN(!unres->node, LOGMEM(NULL), -1);
unres->node[unres->count - 1] = node;
unres->type = ly_realloc(unres->type, unres->count * sizeof *unres->type);
LY_CHECK_ERR_RETURN(!unres->type, LOGMEM(NULL), -1);
unres->type[unres->count - 1] = type;
return 0;
}
static void
resolve_unres_data_autodel_diff(struct unres_data *unres, uint32_t unres_i)
{
struct lyd_node *next, *child, *parent;
uint32_t i;
for (i = 0; i < unres->diff_idx; ++i) {
if (unres->diff->type[i] == LYD_DIFF_DELETED) {
/* only leaf(-list) default could be removed and there is nothing to be checked in that case */
continue;
}
if (unres->diff->second[i] == unres->node[unres_i]) {
/* 1) default value was supposed to be created, but is disabled by when
* -> remove it from diff altogether
*/
unres_data_diff_rem(unres, i);
/* if diff type is CREATED, the value was just a pointer, it can be freed normally (unlike in 4) */
return;
} else {
parent = unres->diff->second[i]->parent;
while (parent && (parent != unres->node[unres_i])) {
parent = parent->parent;
}
if (parent) {
/* 2) default value was supposed to be created but is disabled by when in some parent
* -> remove this default subtree and add the rest into diff as deleted instead in 4)
*/
unres_data_diff_rem(unres, i);
break;
}
LY_TREE_DFS_BEGIN(unres->diff->second[i]->parent, next, child) {
if (child == unres->node[unres_i]) {
/* 3) some default child of a default value was supposed to be created but has false when
* -> the subtree will be freed later and automatically disconnected from the diff parent node
*/
return;
}
LY_TREE_DFS_END(unres->diff->second[i]->parent, next, child);
}
}
}
/* 4) it does not overlap with created default values in any way
* -> just add it into diff as deleted
*/
unres_data_diff_new(unres, unres->node[unres_i], unres->node[unres_i]->parent, 0);
lyd_unlink(unres->node[unres_i]);
/* should not be freed anymore */
unres->node[unres_i] = NULL;
}
/**
* @brief Resolve every unres data item in the structure. Logs directly.
*
* If options include #LYD_OPT_TRUSTED, the data are considered trusted (must conditions are not expected,
* unresolved leafrefs/instids are accepted, when conditions are normally resolved because at least some implicit
* non-presence containers may need to be deleted).
*
* If options includes #LYD_OPT_WHENAUTODEL, the non-default nodes with false when conditions are auto-deleted.
*
* @param[in] ctx Context used.
* @param[in] unres Unres data structure to use.
* @param[in,out] root Root node of the data tree, can be changed due to autodeletion.
* @param[in] options Data options as described above.
*
* @return EXIT_SUCCESS on success, -1 on error.
*/
int
resolve_unres_data(struct ly_ctx *ctx, struct unres_data *unres, struct lyd_node **root, int options)
{
uint32_t i, j, first, resolved, del_items, stmt_count;
uint8_t prev_when_status;
int rc, progress, ignore_fail;
enum int_log_opts prev_ilo;
struct ly_err_item *prev_eitem;
LY_ERR prev_ly_errno = ly_errno;
struct lyd_node *parent;
struct lys_when *when;
assert(root);
assert(unres);
if (!unres->count) {
return EXIT_SUCCESS;
}
if (options & (LYD_OPT_NOTIF_FILTER | LYD_OPT_GET | LYD_OPT_GETCONFIG | LYD_OPT_EDIT)) {
ignore_fail = 1;
} else if (options & LYD_OPT_NOEXTDEPS) {
ignore_fail = 2;
} else {
ignore_fail = 0;
}
LOGVRB("Resolving unresolved data nodes and their constraints...");
if (!ignore_fail) {
/* remember logging state only if errors are generated and valid */
ly_ilo_change(ctx, ILO_STORE, &prev_ilo, &prev_eitem);
}
/*
* when-stmt first
*/
first = 1;
stmt_count = 0;
resolved = 0;
del_items = 0;
do {
if (!ignore_fail) {
ly_err_free_next(ctx, prev_eitem);
}
progress = 0;
for (i = 0; i < unres->count; i++) {
if (unres->type[i] != UNRES_WHEN) {
continue;
}
if (first) {
/* count when-stmt nodes in unres list */
stmt_count++;
}
/* resolve when condition only when all parent when conditions are already resolved */
for (parent = unres->node[i]->parent;
parent && LYD_WHEN_DONE(parent->when_status);
parent = parent->parent) {
if (!parent->parent && (parent->when_status & LYD_WHEN_FALSE)) {
/* the parent node was already unlinked, do not resolve this node,
* it will be removed anyway, so just mark it as resolved
*/
unres->node[i]->when_status |= LYD_WHEN_FALSE;
unres->type[i] = UNRES_RESOLVED;
resolved++;
break;
}
}
if (parent) {
continue;
}
prev_when_status = unres->node[i]->when_status;
rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, &when);
if (!rc) {
/* finish with error/delete the node only if when was changed from true to false, an external
* dependency was not required, or it was not provided (the flag would not be passed down otherwise,
* checked in upper functions) */
if ((unres->node[i]->when_status & LYD_WHEN_FALSE)
&& (!(when->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP)) || !(options & LYD_OPT_NOEXTDEPS))) {
if ((!(prev_when_status & LYD_WHEN_TRUE) || !(options & LYD_OPT_WHENAUTODEL)) && !unres->node[i]->dflt) {
/* false when condition */
goto error;
} /* follows else */
/* auto-delete */
LOGVRB("Auto-deleting node \"%s\" due to when condition (%s)", ly_errpath(ctx), when->cond);
/* only unlink now, the subtree can contain another nodes stored in the unres list */
/* if it has parent non-presence containers that would be empty, we should actually
* remove the container
*/
for (parent = unres->node[i];
parent->parent && parent->parent->schema->nodetype == LYS_CONTAINER;
parent = parent->parent) {
if (((struct lys_node_container *)parent->parent->schema)->presence) {
/* presence container */
break;
}
if (parent->next || parent->prev != parent) {
/* non empty (the child we are in and we are going to remove is not the only child) */
break;
}
}
unres->node[i] = parent;
if (*root && *root == unres->node[i]) {
*root = (*root)->next;
}
lyd_unlink(unres->node[i]);
unres->type[i] = UNRES_DELETE;
del_items++;
/* update the rest of unres items */
for (j = 0; j < unres->count; j++) {
if (unres->type[j] == UNRES_RESOLVED || unres->type[j] == UNRES_DELETE) {
continue;
}
/* test if the node is in subtree to be deleted */
for (parent = unres->node[j]; parent; parent = parent->parent) {
if (parent == unres->node[i]) {
/* yes, it is */
unres->type[j] = UNRES_RESOLVED;
resolved++;
break;
}
}
}
} else {
unres->type[i] = UNRES_RESOLVED;
}
if (!ignore_fail) {
ly_err_free_next(ctx, prev_eitem);
}
resolved++;
progress = 1;
} else if (rc == -1) {
goto error;
} /* else forward reference */
}
first = 0;
} while (progress && resolved < stmt_count);
/* do we have some unresolved when-stmt? */
if (stmt_count > resolved) {
goto error;
}
for (i = 0; del_items && i < unres->count; i++) {
/* we had some when-stmt resulted to false, so now we have to sanitize the unres list */
if (unres->type[i] != UNRES_DELETE) {
continue;
}
if (!unres->node[i]) {
unres->type[i] = UNRES_RESOLVED;
del_items--;
continue;
}
if (unres->store_diff) {
resolve_unres_data_autodel_diff(unres, i);
}
/* really remove the complete subtree */
lyd_free(unres->node[i]);
unres->type[i] = UNRES_RESOLVED;
del_items--;
}
/*
* now leafrefs
*/
if (options & LYD_OPT_TRUSTED) {
/* we want to attempt to resolve leafrefs */
assert(!ignore_fail);
ignore_fail = 1;
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
first = 1;
stmt_count = 0;
resolved = 0;
do {
progress = 0;
for (i = 0; i < unres->count; i++) {
if (unres->type[i] != UNRES_LEAFREF) {
continue;
}
if (first) {
/* count leafref nodes in unres list */
stmt_count++;
}
rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL);
if (!rc) {
unres->type[i] = UNRES_RESOLVED;
if (!ignore_fail) {
ly_err_free_next(ctx, prev_eitem);
}
resolved++;
progress = 1;
} else if (rc == -1) {
goto error;
} /* else forward reference */
}
first = 0;
} while (progress && resolved < stmt_count);
/* do we have some unresolved leafrefs? */
if (stmt_count > resolved) {
goto error;
}
if (!ignore_fail) {
/* log normally now, throw away irrelevant errors */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 0);
ly_errno = prev_ly_errno;
}
/*
* rest
*/
for (i = 0; i < unres->count; ++i) {
if (unres->type[i] == UNRES_RESOLVED) {
continue;
}
assert(!(options & LYD_OPT_TRUSTED) || ((unres->type[i] != UNRES_MUST) && (unres->type[i] != UNRES_MUST_INOUT)));
rc = resolve_unres_data_item(unres->node[i], unres->type[i], ignore_fail, NULL);
if (rc) {
/* since when was already resolved, a forward reference is an error */
return -1;
}
unres->type[i] = UNRES_RESOLVED;
}
LOGVRB("All data nodes and constraints resolved.");
unres->count = 0;
return EXIT_SUCCESS;
error:
if (!ignore_fail) {
/* print all the new errors */
ly_ilo_restore(ctx, prev_ilo, prev_eitem, 1);
/* do not restore ly_errno, it was udpated properly */
}
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-400/c/good_1362_0 |
crossvul-cpp_data_good_196_3 | /*
* Cantata
*
* Copyright (c) 2011-2018 Craig Drummond <craig.p.drummond@gmail.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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "avahi.h"
#include "avahiservice.h"
#include "serverinterface.h"
#include "servicebrowserinterface.h"
#include <QtDBus>
#include <QUrl>
#include <QDebug>
#ifdef ENABLE_KDE_SUPPORT
#include <KDE/KGlobal>
K_GLOBAL_STATIC(Avahi, instance)
#endif
static bool isLocalDomain(const QString &d)
{
return QLatin1String("local")==d.section('.', -1, -1).toLower();
}
QString Avahi::domainToDNS(const QString &domain)
{
return isLocalDomain(domain) ? domain : QUrl::toAce(domain);
}
static const QLatin1String constServiceType("_smb._tcp");
Avahi * Avahi::self()
{
#ifdef ENABLE_KDE_SUPPORT
return instance;
#else
static Avahi *instance=0;
if(!instance) {
instance=new Avahi;
}
return instance;
#endif
}
Avahi::Avahi()
{
org::freedesktop::Avahi::Server server("org.freedesktop.Avahi", "/", QDBusConnection::systemBus());
QDBusReply<QDBusObjectPath> reply=server.ServiceBrowserNew(-1, -1, constServiceType, domainToDNS(QString()), 0);
if (reply.isValid()) {
service=new OrgFreedesktopAvahiServiceBrowserInterface("org.freedesktop.Avahi", reply.value().path(), QDBusConnection::systemBus());
connect(service, SIGNAL(ItemNew(int,int,QString,QString,QString,uint)), SLOT(addService(int,int,QString,QString,QString,uint)));
connect(service, SIGNAL(ItemRemove(int,int,QString,QString,QString,uint)), SLOT(removeService(int,int,QString,QString,QString,uint)));
}
}
AvahiService * Avahi::getService(const QString &name)
{
return services.contains(name) ? services[name] : 0;
}
void Avahi::addService(int, int, const QString &name, const QString &type, const QString &domain, uint)
{
if (isLocalDomain(domain) && !services.contains(name)) {
AvahiService *srv=new AvahiService(name, type, domain);
services.insert(name, srv);
connect(srv, SIGNAL(serviceResolved(QString)), this, SIGNAL(serviceAdded(QString)));
}
}
void Avahi::removeService(int, int, const QString &name, const QString &, const QString &domain, uint)
{
if (isLocalDomain(domain) && services.contains(name)) {
services[name]->deleteLater();
disconnect(services[name], SIGNAL(serviceResolved(QString)), this, SIGNAL(serviceAdded(QString)));
services.remove(name);
emit serviceRemoved(name);
}
}
#include "moc_avahi.cpp"
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_196_3 |
crossvul-cpp_data_bad_4235_0 | /******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2019, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "TarFileReader.h"
#include <cbang/os/SystemUtilities.h>
#include <cbang/os/SysError.h>
#include <cbang/log/Logger.h>
#include <cbang/iostream/BZip2Decompressor.h>
#include <boost/ref.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
namespace io = boost::iostreams;
using namespace cb;
using namespace std;
struct TarFileReader::private_t {
io::filtering_istream filter;
};
TarFileReader::TarFileReader(const string &path, compression_t compression) :
pri(new private_t), stream(SystemUtilities::iopen(path)),
didReadHeader(false) {
addCompression(compression == TARFILE_AUTO ? infer(path) : compression);
pri->filter.push(*this->stream);
}
TarFileReader::TarFileReader(istream &stream, compression_t compression) :
pri(new private_t), stream(SmartPointer<istream>::Phony(&stream)),
didReadHeader(false) {
addCompression(compression);
pri->filter.push(*this->stream);
}
TarFileReader::~TarFileReader() {
delete pri;
}
bool TarFileReader::hasMore() {
if (!didReadHeader) {
SysError::clear();
if (!readHeader(pri->filter))
THROW("Tar file read failed: " << SysError());
didReadHeader = true;
}
return !isEOF();
}
bool TarFileReader::next() {
if (didReadHeader) {
skipFile(pri->filter);
didReadHeader = false;
}
return hasMore();
}
std::string TarFileReader::extract(const string &_path) {
if (_path.empty()) THROW("path cannot be empty");
if (!hasMore()) THROW("No more tar files");
string path = _path;
if (SystemUtilities::isDirectory(path)) path += "/" + getFilename();
LOG_DEBUG(5, "Extracting: " << path);
return extract(*SystemUtilities::oopen(path));
}
string TarFileReader::extract(ostream &out) {
if (!hasMore()) THROW("No more tar files");
readFile(out, pri->filter);
didReadHeader = false;
return getFilename();
}
void TarFileReader::addCompression(compression_t compression) {
switch (compression) {
case TARFILE_NONE: break; // none
case TARFILE_BZIP2: pri->filter.push(BZip2Decompressor()); break;
case TARFILE_GZIP: pri->filter.push(io::zlib_decompressor()); break;
default: THROW("Invalid compression type " << compression);
}
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_4235_0 |
crossvul-cpp_data_good_4235_19 | /******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2019, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include <cbang/tar/TarFileReader.h>
#include <cbang/Catch.h>
#include <iostream>
using namespace cb;
using namespace std;
int main(int argc, char *argv[]) {
try {
for (int i = 1; i < argc; i++) {
string arg = argv[i];
if (arg == "--extract" && i < argc - 1) {
TarFileReader reader(argv[++i]);
while (reader.hasMore())
cout << reader.extract() << endl;
} else THROWS("Invalid arg '" << arg << "'");
}
return 0;
} catch (const Exception &e) {cerr << e.getMessage();}
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_4235_19 |
crossvul-cpp_data_good_196_5 | /*
* Cantata
*
* Copyright (c) 2011-2018 Craig Drummond <craig.p.drummond@gmail.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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "avahi.h"
#include "avahiservice.h"
#include "serverinterface.h"
#include "serviceresolverinterface.h"
Q_DECLARE_METATYPE(QList<QByteArray>)
AvahiService::AvahiService(const QString &n, const QString &type, const QString &domain)
: name(n)
, port(0)
{
static bool registeredTypes=false;
if (!registeredTypes) {
qDBusRegisterMetaType<QList<QByteArray> >();
registeredTypes=true;
}
org::freedesktop::Avahi::Server server("org.freedesktop.Avahi", "/", QDBusConnection::systemBus());
QDBusReply<QDBusObjectPath> reply=server.ServiceResolverNew(-1, -1, name, type, Avahi::domainToDNS(domain), -1, 8 /*AVAHI_LOOKUP_NO_ADDRESS|AVAHI_LOOKUP_NO_TXT*/);
if (reply.isValid()) {
resolver=new OrgFreedesktopAvahiServiceResolverInterface("org.freedesktop.Avahi", reply.value().path(), QDBusConnection::systemBus());
connect(resolver, SIGNAL(Found(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort,const QList<QByteArray>&, uint)),
this, SLOT(resolved(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort, const QList<QByteArray>&, uint)));
connect(resolver, SIGNAL(Failure(QString)), this, SLOT(error(QString)));
}
}
AvahiService::~AvahiService()
{
stop();
}
void AvahiService::resolved(int, int, const QString &name, const QString &, const QString &, const QString &h, int, const QString &, ushort p, const QList<QByteArray> &, uint)
{
Q_UNUSED(name)
port=p;
host=h;
stop();
emit serviceResolved(name);
}
void AvahiService::error(const QString &)
{
stop();
}
void AvahiService::stop()
{
if (resolver) {
resolver->Free();
resolver->deleteLater();
disconnect(resolver, SIGNAL(Found(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort,const QList<QByteArray>&, uint)),
this, SLOT(resolved(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort, const QList<QByteArray>&, uint)));
disconnect(resolver, SIGNAL(Failure(QString)), this, SLOT(error(QString)));
resolver=0;
}
}
#include "moc_avahiservice.cpp"
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_196_5 |
crossvul-cpp_data_bad_196_3 | /*
* Cantata
*
* Copyright (c) 2011-2018 Craig Drummond <craig.p.drummond@gmail.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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "avahi.h"
#include "avahiservice.h"
#include "serverinterface.h"
#include "servicebrowserinterface.h"
#include <QtDBus>
#include <QUrl>
#include <QDebug>
#ifdef ENABLE_KDE_SUPPORT
#include <KDE/KGlobal>
K_GLOBAL_STATIC(Avahi, instance)
#endif
static bool isLocalDomain(const QString &d)
{
return QLatin1String("local")==d.section('.', -1, -1).toLower();
}
QString Avahi::domainToDNS(const QString &domain)
{
return isLocalDomain(domain) ? domain : QUrl::toAce(domain);
}
static const QLatin1String constServiceType("_smb._tcp");
Avahi * Avahi::self()
{
#ifdef ENABLE_KDE_SUPPORT
return instance;
#else
static Avahi *instance=0;
if(!instance) {
instance=new Avahi;
}
return instance;
#endif
}
Avahi::Avahi()
{
org::freedesktop::Avahi::Server server("org.freedesktop.Avahi", "/", QDBusConnection::systemBus());
QDBusReply<QDBusObjectPath> reply=server.ServiceBrowserNew(-1, -1, constServiceType, domainToDNS(QString()), 0);
if (reply.isValid()) {
service=new OrgFreedesktopAvahiServiceBrowserInterface("org.freedesktop.Avahi", reply.value().path(), QDBusConnection::systemBus());
connect(service, SIGNAL(ItemNew(int,int,QString,QString,QString,uint)), SLOT(addService(int,int,QString,QString,QString,uint)));
connect(service, SIGNAL(ItemRemove(int,int,QString,QString,QString,uint)), SLOT(removeService(int,int,QString,QString,QString,uint)));
}
}
AvahiService * Avahi::getService(const QString &name)
{
return services.contains(name) ? services[name] : 0;
}
void Avahi::addService(int, int, const QString &name, const QString &type, const QString &domain, uint)
{
if (isLocalDomain(domain) && !services.contains(name)) {
AvahiService *srv=new AvahiService(name, type, domain);
services.insert(name, srv);
connect(srv, SIGNAL(serviceResolved(QString)), this, SIGNAL(serviceAdded(QString)));
}
}
void Avahi::removeService(int, int, const QString &name, const QString &, const QString &domain, uint)
{
if (isLocalDomain(domain) && services.contains(name)) {
services[name]->deleteLater();
disconnect(services[name], SIGNAL(serviceResolved(QString)), this, SIGNAL(serviceAdded(QString)));
services.remove(name);
emit serviceRemoved(name);
}
}
#include "moc_avahi.cpp"
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_196_3 |
crossvul-cpp_data_good_2420_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <zip.h>
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/file-util.h"
#include "hphp/runtime/base/preg.h"
#include "hphp/runtime/base/stream-wrapper-registry.h"
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/ext/pcre/ext_pcre.h"
#include "hphp/runtime/ext/std/ext_std_file.h"
namespace HPHP {
static String to_full_path(const String& filename) {
if (filename.charAt(0) == '/') {
return filename;
}
return f_getcwd().toString() + String::FromChar('/') + filename;
}
// A wrapper for `zip_open` that prepares a full path
// file name to consider current working directory.
static zip* _zip_open(const String& filename, int _flags, int* zep) {
return zip_open(to_full_path(filename).c_str(), _flags, zep);
}
struct ZipStream : File {
DECLARE_RESOURCE_ALLOCATION(ZipStream);
ZipStream(zip* z, const String& name) : m_zipFile(nullptr) {
if (name.empty()) {
return;
}
struct zip_stat zipStat;
if (zip_stat(z, name.c_str(), 0, &zipStat) != 0) {
return;
}
m_zipFile = zip_fopen(z, name.c_str(), 0);
}
virtual ~ZipStream() { close(); }
bool open(const String&, const String&) override { return false; }
bool close() override {
bool noError = true;
if (!eof()) {
if (zip_fclose(m_zipFile) != 0) {
noError = false;
}
m_zipFile = nullptr;
}
return noError;
}
int64_t readImpl(char *buffer, int64_t length) override {
auto n = zip_fread(m_zipFile, buffer, length);
if (n <= 0) {
if (n == -1) {
raise_warning("Zip stream error");
n = 0;
}
close();
}
return n;
}
int64_t writeImpl(const char *buffer, int64_t length) override { return 0; }
bool eof() override { return m_zipFile == nullptr; }
private:
zip_file* m_zipFile;
};
void ZipStream::sweep() {
close();
File::sweep();
}
struct ZipStreamWrapper : Stream::Wrapper {
virtual req::ptr<File> open(const String& filename,
const String& mode,
int options,
const req::ptr<StreamContext>& context) {
std::string url(filename.c_str());
auto pound = url.find('#');
if (pound == std::string::npos) {
return nullptr;
}
// 6 is the position after zip://
auto path = url.substr(6, pound - 6);
auto file = url.substr(pound + 1);
if (path.empty() || file.empty()) {
return nullptr;
}
int err;
auto z = _zip_open(path, 0, &err);
if (z == nullptr) {
return nullptr;
}
return req::make<ZipStream>(z, file);
}
};
struct ZipEntry : SweepableResourceData {
DECLARE_RESOURCE_ALLOCATION(ZipEntry);
CLASSNAME_IS("ZipEntry");
// overriding ResourceData
const String& o_getClassNameHook() const override { return classnameof(); }
ZipEntry(zip* z, int index) : m_zipFile(nullptr) {
if (zip_stat_index(z, index, 0, &m_zipStat) == 0) {
m_zipFile = zip_fopen_index(z, index, 0);
}
}
~ZipEntry() {
close();
}
bool close() {
bool noError = true;
if (isValid()) {
if (zip_fclose(m_zipFile) != 0) {
noError = false;
}
m_zipFile = nullptr;
}
return noError;
}
bool isValid() {
return m_zipFile != nullptr;
}
String read(int64_t len) {
StringBuffer sb(len);
auto buf = sb.appendCursor(len);
auto n = zip_fread(m_zipFile, buf, len);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string();
}
uint64_t getCompressedSize() {
return m_zipStat.comp_size;
}
String getCompressionMethod() {
switch (m_zipStat.comp_method) {
case 0:
return "stored";
case 1:
return "shrunk";
case 2:
case 3:
case 4:
case 5:
return "reduced";
case 6:
return "imploded";
case 7:
return "tokenized";
case 8:
return "deflated";
case 9:
return "deflatedX";
case 10:
return "implodedX";
default:
return false;
}
}
String getName() {
return m_zipStat.name;
}
uint64_t getSize() {
return m_zipStat.size;
}
private:
struct zip_stat m_zipStat;
zip_file* m_zipFile;
};
IMPLEMENT_RESOURCE_ALLOCATION(ZipEntry);
struct ZipDirectory : SweepableResourceData {
DECLARE_RESOURCE_ALLOCATION(ZipDirectory);
CLASSNAME_IS("ZipDirectory");
// overriding ResourceData
const String& o_getClassNameHook() const override { return classnameof(); }
explicit ZipDirectory(zip *z) : m_zip(z),
m_numFiles(zip_get_num_files(z)),
m_curIndex(0) {}
~ZipDirectory() { close(); }
bool close() {
bool noError = true;
if (isValid()) {
if (zip_close(m_zip) != 0) {
zip_discard(m_zip);
noError = false;
}
m_zip = nullptr;
}
return noError;
}
bool isValid() const {
return m_zip != nullptr;
}
Variant nextFile() {
if (m_curIndex >= m_numFiles) {
return false;
}
auto zipEntry = req::make<ZipEntry>(m_zip, m_curIndex);
if (!zipEntry->isValid()) {
return false;
}
++m_curIndex;
return Variant(std::move(zipEntry));
}
zip* getZip() {
return m_zip;
}
private:
zip* m_zip;
int m_numFiles;
int m_curIndex;
};
IMPLEMENT_RESOURCE_ALLOCATION(ZipDirectory);
const StaticString s_ZipArchive("ZipArchive");
template<class T>
ALWAYS_INLINE
static req::ptr<T> getResource(ObjectData* obj, const char* varName) {
auto var = obj->o_get(varName, true, s_ZipArchive);
if (var.getType() == KindOfNull) {
return nullptr;
}
return cast<T>(var);
}
ALWAYS_INLINE
static Variant setVariable(const Object& obj, const char* varName, const Variant& varValue) {
return obj->o_set(varName, varValue, s_ZipArchive);
}
#define FAIL_IF_EMPTY_STRING(func, str) \
if (str.empty()) { \
raise_warning(#func "(): Empty string as source"); \
return false; \
}
#define FAIL_IF_EMPTY_STRING_ZIPARCHIVE(func, str) \
if (str.empty()) { \
raise_warning("ZipArchive::" #func "(): Empty string as source"); \
return false; \
}
#define FAIL_IF_INVALID_INDEX(index) \
if (index < 0) { \
return false; \
}
#define FAIL_IF_INVALID_PTR(ptr) \
if (ptr == nullptr) { \
return false; \
}
#define FAIL_IF_INVALID_ZIPARCHIVE(func, res) \
if (res == nullptr || !res->isValid()) { \
raise_warning("ZipArchive::" #func \
"(): Invalid or uninitialized Zip object"); \
return false; \
}
#define FAIL_IF_INVALID_ZIPDIRECTORY(func, res) \
if (!res->isValid()) { \
raise_warning(#func "(): %d is not a valid " \
"Zip Directory resource", res->getId()); \
return false; \
}
#define FAIL_IF_INVALID_ZIPENTRY(func, res) \
if (!res->isValid()) { \
raise_warning(#func "(): %d is not a valid Zip Entry resource", \
res->getId()); \
return false; \
}
//////////////////////////////////////////////////////////////////////////////
// class ZipArchive
static Variant HHVM_METHOD(ZipArchive, getProperty, int64_t property) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
if (zipDir == nullptr) {
switch (property) {
case 0:
case 1:
case 2:
return 0;
case 3:
case 4:
return empty_string_variant();
default:
return init_null();
}
}
switch (property) {
case 0:
case 1:
{
int zep, sys;
zip_error_get(zipDir->getZip(), &zep, &sys);
if (property == 0) {
return zep;
}
return sys;
}
case 2:
{
return zip_get_num_files(zipDir->getZip());
}
case 3:
{
return this_->o_get("filename", true, s_ZipArchive).asCStrRef();
}
case 4:
{
int len;
auto comment = zip_get_archive_comment(zipDir->getZip(), &len, 0);
if (comment == nullptr) {
return empty_string_variant();
}
return String(comment, len, CopyString);
}
default:
return init_null();
}
}
static bool HHVM_METHOD(ZipArchive, addEmptyDir, const String& dirname) {
if (dirname.empty()) {
return false;
}
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addEmptyDir, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addEmptyDir, dirname);
std::string dirStr(dirname.c_str());
if (dirStr[dirStr.length() - 1] != '/') {
dirStr.push_back('/');
}
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), dirStr.c_str(), 0, &zipStat) != -1) {
return false;
}
if (zip_add_dir(zipDir->getZip(), dirStr.c_str()) == -1) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool addFile(zip* zipStruct, const char* source, const char* dest,
int64_t start = 0, int64_t length = 0) {
if (!HHVM_FN(is_file)(source)) {
return false;
}
auto zipSource = zip_source_file(zipStruct, source, start, length);
FAIL_IF_INVALID_PTR(zipSource);
auto index = zip_name_locate(zipStruct, dest, 0);
if (index < 0) {
if (zip_add(zipStruct, dest, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
} else {
if (zip_replace(zipStruct, index, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
}
zip_error_clear(zipStruct);
return true;
}
static bool HHVM_METHOD(ZipArchive, addFile, const String& filename,
const String& localname, int64_t start,
int64_t length) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addFile, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addFile, filename);
return addFile(zipDir->getZip(), filename.c_str(),
localname.empty() ? filename.c_str() : localname.c_str(),
start, length);
}
static bool HHVM_METHOD(ZipArchive, addFromString, const String& localname,
const String& contents) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addFromString, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addFromString, localname);
auto data = malloc(contents.length());
FAIL_IF_INVALID_PTR(data);
memcpy(data, contents.c_str(), contents.length());
auto zipSource = zip_source_buffer(zipDir->getZip(), data, contents.length(),
1); // this will free data ptr
if (zipSource == nullptr) {
free(data);
return false;
}
auto index = zip_name_locate(zipDir->getZip(), localname.c_str(), 0);
if (index < 0) {
if (zip_add(zipDir->getZip(), localname.c_str(), zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
} else {
if (zip_replace(zipDir->getZip(), index, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool addPattern(zip* zipStruct, const String& pattern, const Array& options,
std::string path, int64_t flags, bool glob) {
std::string removePath;
if (options->exists(String("remove_path"))) {
auto var = options->get(String("remove_path"));
if (var.isString()) {
removePath.append(var.asCStrRef().c_str());
}
}
bool removeAllPath = false;
if (options->exists(String("remove_all_path"))) {
auto var = options->get(String("remove_all_path"));
if (var.isBoolean()) {
removeAllPath = var.asBooleanVal();
}
}
std::string addPath;
if (options->exists(String("add_path"))) {
auto var = options->get(String("add_path"));
if (var.isString()) {
addPath.append(var.asCStrRef().c_str());
}
}
Array files;
if (glob) {
auto match = HHVM_FN(glob)(pattern, flags);
if (match.isArray()) {
files = match.toArrRef();
} else {
return false;
}
} else {
if (path[path.size() - 1] != '/') {
path.push_back('/');
}
auto allFiles = HHVM_FN(scandir)(path);
if (allFiles.isArray()) {
files = allFiles.toArrRef();
} else {
return false;
}
}
std::string dest;
auto pathLen = path.size();
for (ArrayIter it(files); it; ++it) {
auto var = it.second();
if (!var.isString()) {
return false;
}
auto source = var.asCStrRef();
if (HHVM_FN(is_dir)(source)) {
continue;
}
if (!glob) {
auto var = preg_match(pattern, source);
if (var.isInteger()) {
if (var.asInt64Val() == 0) {
continue;
}
} else {
return false;
}
}
dest.resize(0);
dest.append(source.c_str());
if (removeAllPath) {
auto index = dest.rfind('/');
if (index != std::string::npos) {
dest.erase(0, index + 1);
}
} else if (!removePath.empty()) {
auto index = dest.find(removePath);
if (index == 0) {
dest.erase(0, removePath.size());
}
}
if (!addPath.empty()) {
dest.insert(0, addPath);
}
path.resize(pathLen);
path.append(source.c_str());
if (!addFile(zipStruct, path.c_str(), dest.c_str())) {
return false;
}
}
zip_error_clear(zipStruct);
return true;
}
static bool HHVM_METHOD(ZipArchive, addGlob, const String& pattern,
int64_t flags, const Array& options) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addGlob, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addGlob, pattern);
return addPattern(zipDir->getZip(), pattern, options, "", flags, true);
}
static bool HHVM_METHOD(ZipArchive, addPattern, const String& pattern,
const String& path, const Array& options) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addPattern, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addPattern, pattern);
return addPattern(zipDir->getZip(), pattern, options, path.c_str(), 0, false);
}
static bool HHVM_METHOD(ZipArchive, close) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(close, zipDir);
bool ret = zipDir->close();
setVariable(Object{this_}, "zipDir", null_resource);
return ret;
}
static bool HHVM_METHOD(ZipArchive, deleteIndex, int64_t index) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(deleteIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (zip_delete(zipDir->getZip(), index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, deleteName, const String& name) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(deleteName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(deleteName, name);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), 0, &zipStat) != 0) {
return false;
}
if (zip_delete(zipDir->getZip(), zipStat.index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
// Make the path relative to "." by flattening.
// This function is named the same and similar in implementation to that in
// php-src:php_zip.c
// One difference is that we canonicalize here whereas php-src is already
// assumed passed a canonicalized path.
static std::string make_relative_path(const std::string& path) {
if (path.empty()) {
return path;
}
// First get the path to a state where we don't have .. in the middle of it
// etc. canonicalize handles Windows paths too.
std::string canonical(FileUtil::canonicalize(path));
// If we have a slash at the beginning, then just remove it and we are
// relative. This check will hold because we have canonicalized the
// path above to remove .. from the path, so we know we can be sure
// we are at a good place for this check.
if (FileUtil::isDirSeparator(canonical[0])) {
return canonical.substr(1);
}
// If we get here, canonical looks something like:
// a/b/c
// Search through the path and if we find a place where we have a slash
// and a "." just before that slash, then cut the path off right there
// and just take everything after the slash.
std::string relative(canonical);
int idx = canonical.length() - 1;
while (1) {
while (idx > 0 && !(FileUtil::isDirSeparator(canonical[idx]))) {
idx--;
}
// If we ever get to idx == 0, then there were no other slashes to deal with
if (idx == 0) {
return canonical;
}
if (idx >= 1 && (canonical[idx - 1] == '.' || canonical[idx - 1] == ':')) {
relative = canonical.substr(idx + 1);
break;
}
idx--;
}
return relative;
}
static bool extractFileTo(zip* zip, const std::string &file, std::string& to,
char* buf, size_t len) {
struct zip_stat zipStat;
// Verify the file to be extracted is actually in the zip file
if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {
return false;
}
auto clean_file = file;
auto sep = std::string::npos;
// Normally would just use std::string::rfind here, but if we want to be
// consistent between Windows and Linux, even if techincally Linux won't use
// backslash for a separator, we are checking for both types.
int idx = file.length() - 1;
while (idx >= 0) {
if (FileUtil::isDirSeparator(file[idx])) {
sep = idx;
break;
}
idx--;
}
if (sep != std::string::npos) {
// make_relative_path so we do not try to put files or dirs in bad
// places. This securely "cleans" the file.
clean_file = make_relative_path(file);
std::string path = to + clean_file;
bool is_dir_only = true;
if (sep < file.length() - 1) { // not just a directory
auto clean_file_dir = HHVM_FN(dirname)(clean_file);
path = to + clean_file_dir.toCppString();
is_dir_only = false;
}
// Make sure the directory path to extract to exists or can be created
if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {
return false;
}
// If we have a good directory to extract to above, we now check whether
// the "file" parameter passed in is a directory or actually a file.
if (is_dir_only) { // directory, like /usr/bin/
return true;
}
// otherwise file is actually a file, so we actually extract.
}
// We have ensured that clean_file will be added to a relative path by the
// time we get here.
to.append(clean_file);
auto zipFile = zip_fopen_index(zip, zipStat.index, 0);
FAIL_IF_INVALID_PTR(zipFile);
auto outFile = fopen(to.c_str(), "wb");
if (outFile == nullptr) {
zip_fclose(zipFile);
return false;
}
for (auto n = zip_fread(zipFile, buf, len); n != 0;
n = zip_fread(zipFile, buf, len)) {
if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {
zip_fclose(zipFile);
fclose(outFile);
remove(to.c_str());
return false;
}
}
zip_fclose(zipFile);
if (fclose(outFile) != 0) {
return false;
}
return true;
}
static bool HHVM_METHOD(ZipArchive, extractTo, const String& destination,
const Variant& entries) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(extractTo, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(extractTo, destination);
auto fileCount = zip_get_num_files(zipDir->getZip());
if (fileCount == -1) {
raise_warning("Illegal archive");
return false;
}
std::string to(destination.c_str());
if (to[to.size() - 1] != '/') {
to.push_back('/');
}
if (!HHVM_FN(is_dir)(to) && !HHVM_FN(mkdir)(to)) {
return false;
}
char buf[1024];
auto toSize = to.size();
if (entries.isString()) {
// extract only this file
if (!extractFileTo(zipDir->getZip(), entries.asCStrRef().c_str(),
to, buf, sizeof(buf))) {
return false;
}
} else if (entries.isArray() && entries.asCArrRef().size() != 0) {
// extract ones in the array
for (ArrayIter it(entries.asCArrRef()); it; ++it) {
auto var = it.second();
if (!var.isString() || !extractFileTo(zipDir->getZip(),
var.asCStrRef().c_str(),
to, buf, sizeof(buf))) {
return false;
}
to.resize(toSize);
}
} else {
// extract all files
for (decltype(fileCount) index = 0; index < fileCount; ++index) {
auto file = zip_get_name(zipDir->getZip(), index, ZIP_FL_UNCHANGED);
if (!extractFileTo(zipDir->getZip(), file, to, buf, sizeof(buf))) {
return false;
}
to.resize(toSize);
}
}
zip_error_clear(zipDir->getZip());
return true;
}
static Variant HHVM_METHOD(ZipArchive, getArchiveComment, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getArchiveComment, zipDir);
int len;
auto comment = zip_get_archive_comment(zipDir->getZip(), &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getCommentIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getCommentIndex, zipDir);
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
int len;
auto comment = zip_get_file_comment(zipDir->getZip(), index, &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getCommentName, const String& name,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getCommentName, zipDir);
if (name.empty()) {
raise_notice("ZipArchive::getCommentName(): Empty string as source");
return false;
}
int index = zip_name_locate(zipDir->getZip(), name.c_str(), 0);
if (index != 0) {
return false;
}
int len;
auto comment = zip_get_file_comment(zipDir->getZip(), index, &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getFromIndex, int64_t index,
int64_t length, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getFromIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (length < 0) {
return empty_string_variant();
}
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
if (zipStat.size < 1) {
return empty_string_variant();
}
auto zipFile = zip_fopen_index(zipDir->getZip(), index, flags);
FAIL_IF_INVALID_PTR(zipFile);
if (length == 0) {
length = zipStat.size;
}
StringBuffer sb(length);
auto buf = sb.appendCursor(length);
auto n = zip_fread(zipFile, buf, length);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string_variant();
}
static Variant HHVM_METHOD(ZipArchive, getFromName, const String& name,
int64_t length, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getFromName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(getFromName, name);
if (length < 0) {
return empty_string_variant();
}
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), flags, &zipStat) != 0) {
return false;
}
if (zipStat.size < 1) {
return empty_string_variant();
}
auto zipFile = zip_fopen(zipDir->getZip(), name.c_str(), flags);
FAIL_IF_INVALID_PTR(zipFile);
if (length == 0) {
length = zipStat.size;
}
StringBuffer sb(length);
auto buf = sb.appendCursor(length);
auto n = zip_fread(zipFile, buf, length);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string_variant();
}
static Variant HHVM_METHOD(ZipArchive, getNameIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getNameIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
auto name = zip_get_name(zipDir->getZip(), index, flags);
FAIL_IF_INVALID_PTR(name);
return String(name, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getStatusString) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getStatusString, zipDir);
int zep, sep, len;
zip_error_get(zipDir->getZip(), &zep, &sep);
char error_string[128];
len = zip_error_to_str(error_string, 128, zep, sep);
return String(error_string, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getStream, const String& name) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getStream, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(getStream, name);
auto zipStream = req::make<ZipStream>(zipDir->getZip(), name);
if (zipStream->eof()) {
return false;
}
return Variant(std::move(zipStream));
}
static Variant HHVM_METHOD(ZipArchive, locateName, const String& name,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(locateName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(locateName, name);
auto index = zip_name_locate(zipDir->getZip(), name.c_str(), flags);
FAIL_IF_INVALID_INDEX(index);
return index;
}
static Variant HHVM_METHOD(ZipArchive, open, const String& filename,
int64_t flags) {
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(open, filename);
int err;
auto z = _zip_open(filename, flags, &err);
if (z == nullptr) {
return err;
}
auto zipDir = req::make<ZipDirectory>(z);
setVariable(Object{this_}, "zipDir", Variant(zipDir));
setVariable(Object{this_}, "filename", filename);
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, renameIndex, int64_t index,
const String& newname) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(renameIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(renameIndex, newname);
if (zip_rename(zipDir->getZip(), index, newname.c_str()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, renameName, const String& name,
const String& newname) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(renameName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(renameName, newname);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), 0, &zipStat) != 0) {
return false;
}
if (zip_rename(zipDir->getZip(), zipStat.index, newname.c_str()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, setArchiveComment, const String& comment) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(setArchiveComment, zipDir);
if (zip_set_archive_comment(zipDir->getZip(), comment.c_str(),
comment.length()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, setCommentIndex, int64_t index,
const String& comment) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(setCommentIndex, zipDir);
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
if (zip_set_file_comment(zipDir->getZip(), index, comment.c_str(),
comment.length()) != 0 ) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, setCommentName, const String& name,
const String& comment) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(setCommentName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(setCommentName, name);
int index = zip_name_locate(zipDir->getZip(), name.c_str(), 0);
FAIL_IF_INVALID_INDEX(index);
if (zip_set_file_comment(zipDir->getZip(), index, comment.c_str(),
comment.length()) != 0 ) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
const StaticString s_name("name");
const StaticString s_index("index");
const StaticString s_crc("crc");
const StaticString s_size("size");
const StaticString s_mtime("mtime");
const StaticString s_comp_size("comp_size");
const StaticString s_comp_method("comp_method");
ALWAYS_INLINE
static Array zipStatToArray(struct zip_stat* zipStat) {
if (zipStat == nullptr) {
return Array();
}
return make_map_array(
s_name, String(zipStat->name),
s_index, VarNR(zipStat->index),
s_crc, VarNR(static_cast<int64_t>(zipStat->crc)),
s_size, VarNR(zipStat->size),
s_mtime, VarNR(zipStat->mtime),
s_comp_size, VarNR(zipStat->comp_size),
s_comp_method, VarNR(zipStat->comp_method)
);
}
static Variant HHVM_METHOD(ZipArchive, statIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(statIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, flags, &zipStat) != 0) {
return false;
}
return zipStatToArray(&zipStat);
}
static Variant HHVM_METHOD(ZipArchive, statName, const String& name,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(statName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(statName, name);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), flags, &zipStat) != 0) {
return false;
}
return zipStatToArray(&zipStat);
}
static bool HHVM_METHOD(ZipArchive, unchangeAll) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeAll, zipDir);
if (zip_unchange_all(zipDir->getZip()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, unchangeArchive) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeArchive, zipDir);
if (zip_unchange_archive(zipDir->getZip()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, unchangeIndex, int64_t index) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (zip_unchange(zipDir->getZip(), index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, unchangeName, const String& name) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(unchangeName, name);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), 0, &zipStat) != 0) {
return false;
}
if (zip_unchange(zipDir->getZip(), zipStat.index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
//////////////////////////////////////////////////////////////////////////////
// functions
static Variant HHVM_FUNCTION(zip_close, const Resource& zip) {
auto zipDir = cast<ZipDirectory>(zip);
FAIL_IF_INVALID_ZIPDIRECTORY(zip_close, zipDir);
zipDir->close();
return init_null();
}
static bool HHVM_FUNCTION(zip_entry_close, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_close, zipEntry);
return zipEntry->close();
}
static Variant HHVM_FUNCTION(zip_entry_compressedsize, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_compressedsize, zipEntry);
return zipEntry->getCompressedSize();
}
static Variant HHVM_FUNCTION(zip_entry_compressionmethod, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_compressionmethod, zipEntry);
return zipEntry->getCompressionMethod();
}
static Variant HHVM_FUNCTION(zip_entry_filesize, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_filesize, zipEntry);
return zipEntry->getSize();
}
static Variant HHVM_FUNCTION(zip_entry_name, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_name, zipEntry);
return zipEntry->getName();
}
static bool HHVM_FUNCTION(zip_entry_open, const Resource& zip, const Resource& zip_entry,
const String& mode) {
auto zipDir = cast<ZipDirectory>(zip);
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPDIRECTORY(zip_entry_open, zipDir);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_open, zipEntry);
zip_error_clear(zipDir->getZip());
return true;
}
static Variant HHVM_FUNCTION(zip_entry_read, const Resource& zip_entry,
int64_t length) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_read, zipEntry);
return zipEntry->read(length > 0 ? length : 1024);
}
static Variant HHVM_FUNCTION(zip_open, const String& filename) {
FAIL_IF_EMPTY_STRING(zip_open, filename);
int err;
auto z = _zip_open(filename, 0, &err);
if (z == nullptr) {
return err;
}
return Variant(req::make<ZipDirectory>(z));
}
static Variant HHVM_FUNCTION(zip_read, const Resource& zip) {
auto zipDir = cast<ZipDirectory>(zip);
FAIL_IF_INVALID_ZIPDIRECTORY(zip_read, zipDir);
return zipDir->nextFile();
}
//////////////////////////////////////////////////////////////////////////////
struct zipExtension final : Extension {
zipExtension() : Extension("zip", "1.12.4-dev") {}
void moduleInit() override {
HHVM_ME(ZipArchive, getProperty);
HHVM_ME(ZipArchive, addEmptyDir);
HHVM_ME(ZipArchive, addFile);
HHVM_ME(ZipArchive, addFromString);
HHVM_ME(ZipArchive, addGlob);
HHVM_ME(ZipArchive, addPattern);
HHVM_ME(ZipArchive, close);
HHVM_ME(ZipArchive, deleteIndex);
HHVM_ME(ZipArchive, deleteName);
HHVM_ME(ZipArchive, extractTo);
HHVM_ME(ZipArchive, getArchiveComment);
HHVM_ME(ZipArchive, getCommentIndex);
HHVM_ME(ZipArchive, getCommentName);
HHVM_ME(ZipArchive, getFromIndex);
HHVM_ME(ZipArchive, getFromName);
HHVM_ME(ZipArchive, getNameIndex);
HHVM_ME(ZipArchive, getStatusString);
HHVM_ME(ZipArchive, getStream);
HHVM_ME(ZipArchive, locateName);
HHVM_ME(ZipArchive, open);
HHVM_ME(ZipArchive, renameIndex);
HHVM_ME(ZipArchive, renameName);
HHVM_ME(ZipArchive, setArchiveComment);
HHVM_ME(ZipArchive, setCommentIndex);
HHVM_ME(ZipArchive, setCommentName);
HHVM_ME(ZipArchive, statIndex);
HHVM_ME(ZipArchive, statName);
HHVM_ME(ZipArchive, unchangeAll);
HHVM_ME(ZipArchive, unchangeArchive);
HHVM_ME(ZipArchive, unchangeIndex);
HHVM_ME(ZipArchive, unchangeName);
HHVM_RCC_INT(ZipArchive, CREATE, ZIP_CREATE);
HHVM_RCC_INT(ZipArchive, EXCL, ZIP_EXCL);
HHVM_RCC_INT(ZipArchive, CHECKCONS, ZIP_CHECKCONS);
HHVM_RCC_INT(ZipArchive, OVERWRITE, ZIP_TRUNCATE);
HHVM_RCC_INT(ZipArchive, FL_NOCASE, ZIP_FL_NOCASE);
HHVM_RCC_INT(ZipArchive, FL_NODIR, ZIP_FL_NODIR);
HHVM_RCC_INT(ZipArchive, FL_COMPRESSED, ZIP_FL_COMPRESSED);
HHVM_RCC_INT(ZipArchive, FL_UNCHANGED, ZIP_FL_UNCHANGED);
HHVM_RCC_INT(ZipArchive, FL_RECOMPRESS, ZIP_FL_RECOMPRESS);
HHVM_RCC_INT(ZipArchive, FL_ENCRYPTED, ZIP_FL_ENCRYPTED);
HHVM_RCC_INT(ZipArchive, ER_OK, ZIP_ER_OK);
HHVM_RCC_INT(ZipArchive, ER_MULTIDISK, ZIP_ER_MULTIDISK);
HHVM_RCC_INT(ZipArchive, ER_RENAME, ZIP_ER_RENAME);
HHVM_RCC_INT(ZipArchive, ER_CLOSE, ZIP_ER_CLOSE);
HHVM_RCC_INT(ZipArchive, ER_SEEK, ZIP_ER_SEEK);
HHVM_RCC_INT(ZipArchive, ER_READ, ZIP_ER_READ);
HHVM_RCC_INT(ZipArchive, ER_WRITE, ZIP_ER_WRITE);
HHVM_RCC_INT(ZipArchive, ER_CRC, ZIP_ER_CRC);
HHVM_RCC_INT(ZipArchive, ER_ZIPCLOSED, ZIP_ER_ZIPCLOSED);
HHVM_RCC_INT(ZipArchive, ER_NOENT, ZIP_ER_NOENT);
HHVM_RCC_INT(ZipArchive, ER_EXISTS, ZIP_ER_EXISTS);
HHVM_RCC_INT(ZipArchive, ER_OPEN, ZIP_ER_OPEN);
HHVM_RCC_INT(ZipArchive, ER_TMPOPEN, ZIP_ER_TMPOPEN);
HHVM_RCC_INT(ZipArchive, ER_ZLIB, ZIP_ER_ZLIB);
HHVM_RCC_INT(ZipArchive, ER_MEMORY, ZIP_ER_MEMORY);
HHVM_RCC_INT(ZipArchive, ER_CHANGED, ZIP_ER_CHANGED);
HHVM_RCC_INT(ZipArchive, ER_COMPNOTSUPP, ZIP_ER_COMPNOTSUPP);
HHVM_RCC_INT(ZipArchive, ER_EOF, ZIP_ER_EOF);
HHVM_RCC_INT(ZipArchive, ER_INVAL, ZIP_ER_INVAL);
HHVM_RCC_INT(ZipArchive, ER_NOZIP, ZIP_ER_NOZIP);
HHVM_RCC_INT(ZipArchive, ER_INTERNAL, ZIP_ER_INTERNAL);
HHVM_RCC_INT(ZipArchive, ER_INCONS, ZIP_ER_INCONS);
HHVM_RCC_INT(ZipArchive, ER_REMOVE, ZIP_ER_REMOVE);
HHVM_RCC_INT(ZipArchive, ER_DELETED, ZIP_ER_DELETED);
HHVM_RCC_INT(ZipArchive, ER_ENCRNOTSUPP, ZIP_ER_ENCRNOTSUPP);
HHVM_RCC_INT(ZipArchive, ER_RDONLY, ZIP_ER_RDONLY);
HHVM_RCC_INT(ZipArchive, ER_NOPASSWD, ZIP_ER_NOPASSWD);
HHVM_RCC_INT(ZipArchive, ER_WRONGPASSWD, ZIP_ER_WRONGPASSWD);
HHVM_RCC_INT(ZipArchive, CM_DEFAULT, ZIP_CM_DEFAULT);
HHVM_RCC_INT(ZipArchive, CM_STORE, ZIP_CM_STORE);
HHVM_RCC_INT(ZipArchive, CM_SHRINK, ZIP_CM_SHRINK);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_1, ZIP_CM_REDUCE_1);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_2, ZIP_CM_REDUCE_2);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_3, ZIP_CM_REDUCE_3);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_4, ZIP_CM_REDUCE_4);
HHVM_RCC_INT(ZipArchive, CM_IMPLODE, ZIP_CM_IMPLODE);
HHVM_RCC_INT(ZipArchive, CM_DEFLATE, ZIP_CM_DEFLATE);
HHVM_RCC_INT(ZipArchive, CM_DEFLATE64, ZIP_CM_DEFLATE64);
HHVM_RCC_INT(ZipArchive, CM_PKWARE_IMPLODE, ZIP_CM_PKWARE_IMPLODE);
HHVM_RCC_INT(ZipArchive, CM_BZIP2, ZIP_CM_BZIP2);
HHVM_RCC_INT(ZipArchive, CM_LZMA, ZIP_CM_LZMA);
HHVM_RCC_INT(ZipArchive, CM_TERSE, ZIP_CM_TERSE);
HHVM_RCC_INT(ZipArchive, CM_LZ77, ZIP_CM_LZ77);
HHVM_RCC_INT(ZipArchive, CM_WAVPACK, ZIP_CM_WAVPACK);
HHVM_RCC_INT(ZipArchive, CM_PPMD, ZIP_CM_PPMD);
HHVM_FE(zip_close);
HHVM_FE(zip_entry_close);
HHVM_FE(zip_entry_compressedsize);
HHVM_FE(zip_entry_compressionmethod);
HHVM_FE(zip_entry_filesize);
HHVM_FE(zip_entry_name);
HHVM_FE(zip_entry_open);
HHVM_FE(zip_entry_read);
HHVM_FE(zip_open);
HHVM_FE(zip_read);
auto wrapper = new ZipStreamWrapper();
if (wrapper == nullptr || !Stream::registerWrapper("zip", wrapper)) {
delete wrapper;
raise_warning("Couldn't register Zip wrapper");
}
loadSystemlib();
}
} s_zip_extension;
// Uncomment for non-bundled module
//HHVM_GET_MODULE(zip);
//////////////////////////////////////////////////////////////////////////////
} // namespace HPHP
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_2420_0 |
crossvul-cpp_data_bad_975_0 | /************************************************************************
**
** Copyright (C) 2016 - 2019 Kevin B. Hendricks, Stratford, Ontario, Canada
** Copyright (C) 2012 John Schember <john@nachtimwald.com>
** Copyright (C) 2009, 2010, 2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil 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.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#ifdef _WIN32
#define NOMINMAX
#endif
#include "unzip.h"
#ifdef _WIN32
#include "iowin32.h"
#endif
#include <string>
#include <QApplication>
#include <QtCore/QtCore>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QFutureSynchronizer>
#include <QtConcurrent/QtConcurrent>
#include <QtCore/QXmlStreamReader>
#include <QDirIterator>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QStringList>
#include <QMessageBox>
#include <QUrl>
#include "BookManipulation/FolderKeeper.h"
#include "BookManipulation/CleanSource.h"
#include "Importers/ImportEPUB.h"
#include "Misc/FontObfuscation.h"
#include "Misc/HTMLEncodingResolver.h"
#include "Misc/QCodePage437Codec.h"
#include "Misc/SettingsStore.h"
#include "Misc/Utility.h"
#include "ResourceObjects/CSSResource.h"
#include "ResourceObjects/HTMLResource.h"
#include "ResourceObjects/OPFResource.h"
#include "ResourceObjects/NCXResource.h"
#include "ResourceObjects/Resource.h"
#include "ResourceObjects/OPFParser.h"
#include "SourceUpdates/UniversalUpdates.h"
#include "sigil_constants.h"
#include "sigil_exception.h"
#ifndef MAX_PATH
// Set Max length to 256 because that's the max path size on many systems.
#define MAX_PATH 256
#endif
// This is the same read buffer size used by Java and Perl.
#define BUFF_SIZE 8192
const QString DUBLIN_CORE_NS = "http://purl.org/dc/elements/1.1/";
static const QString OEBPS_MIMETYPE = "application/oebps-package+xml";
static const QString UPDATE_ERROR_STRING = "SG_ERROR";
const QString NCX_MIMETYPE = "application/x-dtbncx+xml";
static const QString NCX_EXTENSION = "ncx";
const QString ADOBE_FONT_ALGO_ID = "http://ns.adobe.com/pdf/enc#RC";
const QString IDPF_FONT_ALGO_ID = "http://www.idpf.org/2008/embedding";
static const QString CONTAINER_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
" <rootfiles>\n"
" <rootfile full-path=\"%1\" media-type=\"application/oebps-package+xml\"/>\n"
" </rootfiles>\n"
"</container>\n";
static QCodePage437Codec *cp437 = 0;
// Constructor;
// The parameter is the file to be imported
ImportEPUB::ImportEPUB(const QString &fullfilepath)
: Importer(fullfilepath),
m_ExtractedFolderPath(m_TempFolder.GetPath()),
m_HasSpineItems(false),
m_NCXNotInManifest(false),
m_NavResource(NULL)
{
}
// Reads and parses the file
// and returns the created Book
QSharedPointer<Book> ImportEPUB::GetBook(bool extract_metadata)
{
QList<XMLResource *> non_well_formed;
SettingsStore ss;
if (!Utility::IsFileReadable(m_FullFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot read EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
// These read the EPUB file
ExtractContainer();
QHash<QString, QString> encrypted_files = ParseEncryptionXml();
if (BookContentEncrypted(encrypted_files)) {
throw (FileEncryptedWithDrm(""));
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// These mutate the m_Book object
LocateOPF();
m_opfDir = QFileInfo(m_OPFFilePath).dir();
// These mutate the m_Book object
ReadOPF();
AddObfuscatedButUndeclaredFonts(encrypted_files);
AddNonStandardAppleXML();
LoadInfrastructureFiles();
// Check for files missing in the Manifest and create warning
QStringList notInManifest;
foreach(QString file_path, m_ZipFilePaths) {
// skip mimetype and anything in META-INF and the opf itself
if (file_path == "mimetype") continue;
if (file_path.startsWith("META-INF")) continue;
if (m_OPFFilePath.contains(file_path)) continue;
if (!m_ManifestFilePaths.contains(file_path)) {
notInManifest << file_path;
}
}
if (!notInManifest.isEmpty()) {
Utility::DisplayStdWarningDialog(tr("Files exist in epub that are not listed in the manifest, they will be ignored"), notInManifest.join("\n"));
}
const QHash<QString, QString> updates = LoadFolderStructure();
const QList<Resource *> resources = m_Book->GetFolderKeeper()->GetResourceList();
// We're going to check all html files until we find one that isn't well formed then we'll prompt
// the user if they want to auto fix or not.
//
// If we have non-well formed content and they shouldn't be auto fixed we'll pass that on to
// the universal update function so it knows to skip them. Otherwise we won't include them and
// let it modify the file.
for (int i=0; i<resources.count(); ++i) {
if (resources.at(i)->Type() == Resource::HTMLResourceType) {
HTMLResource *hresource = dynamic_cast<HTMLResource *>(resources.at(i));
if (!hresource) {
continue;
}
// Load the content into the HTMLResource so we can perform a well formed check.
try {
hresource->SetText(HTMLEncodingResolver::ReadHTMLFile(hresource->GetFullPath()));
} catch (...) {
if (ss.cleanOn() & CLEANON_OPEN) {
non_well_formed << hresource;
continue;
}
}
if (ss.cleanOn() & CLEANON_OPEN) {
if (!XhtmlDoc::IsDataWellFormed(hresource->GetText(),hresource->GetEpubVersion())) {
non_well_formed << hresource;
}
}
}
}
if (!non_well_formed.isEmpty()) {
QApplication::restoreOverrideCursor();
if (QMessageBox::Yes == QMessageBox::warning(QApplication::activeWindow(),
tr("Sigil"),
tr("This EPUB has HTML files that are not well formed. "
"Sigil can attempt to automatically fix these files, although this "
"can result in data loss.\n\n"
"Do you want to automatically fix the files?"),
QMessageBox::Yes|QMessageBox::No)
) {
non_well_formed.clear();
}
QApplication::setOverrideCursor(Qt::WaitCursor);
}
const QStringList load_errors = UniversalUpdates::PerformUniversalUpdates(false, resources, updates, non_well_formed);
Q_FOREACH (QString err, load_errors) {
AddLoadWarning(QString("%1").arg(err));
}
ProcessFontFiles(resources, updates, encrypted_files);
if (m_PackageVersion.startsWith('3')) {
HTMLResource * nav_resource = NULL;
if (m_NavResource) {
if (m_NavResource->Type() == Resource::HTMLResourceType) {
nav_resource = dynamic_cast<HTMLResource*>(m_NavResource);
}
}
if (!nav_resource) {
// we need to create a nav file here because one was not found
// it will automatically be added to the content.opf
nav_resource = m_Book->CreateEmptyNavFile(true);
Resource * res = dynamic_cast<Resource *>(nav_resource);
m_Book->GetOPF()->SetItemRefLinear(res, false);
}
m_Book->GetOPF()->SetNavResource(nav_resource);
}
if (m_NCXNotInManifest) {
// We manually created an NCX file because there wasn't one in the manifest.
// Need to create a new manifest id for it.
m_NCXId = m_Book->GetOPF()->AddNCXItem(m_NCXFilePath);
}
// Ensure that our spine has a <spine toc="ncx"> element on it now in case it was missing.
m_Book->GetOPF()->UpdateNCXOnSpine(m_NCXId);
// Make sure the <item> for the NCX in the manifest reflects correct href path
m_Book->GetOPF()->UpdateNCXLocationInManifest(m_Book->GetNCX());
// If spine was not present or did not contain any items, recreate the OPF from scratch
// preserving any important metadata elements and making a new reading order.
if (!m_HasSpineItems) {
QList<MetaEntry> originalMetadata = m_Book->GetOPF()->GetDCMetadata();
m_Book->GetOPF()->AutoFixWellFormedErrors();
if (extract_metadata) {
m_Book->GetOPF()->SetDCMetadata(originalMetadata);
}
AddLoadWarning(QObject::tr("The OPF file does not contain a valid spine.") % "\n" %
QObject::tr("Sigil has created a new one for you."));
}
// If we have modified the book to add spine attribute, manifest item or NCX mark as changed.
m_Book->SetModified(GetLoadWarnings().count() > 0);
QApplication::restoreOverrideCursor();
return m_Book;
}
QHash<QString, QString> ImportEPUB::ParseEncryptionXml()
{
QString encrpytion_xml_path = m_ExtractedFolderPath + "/META-INF/encryption.xml";
if (!QFileInfo(encrpytion_xml_path).exists()) {
return QHash<QString, QString>();
}
QXmlStreamReader encryption(Utility::ReadUnicodeTextFile(encrpytion_xml_path));
QHash<QString, QString> encrypted_files;
QString encryption_algo;
QString uri;
while (!encryption.atEnd()) {
encryption.readNext();
if (encryption.isStartElement()) {
if (encryption.name() == "EncryptionMethod") {
encryption_algo = encryption.attributes().value("", "Algorithm").toString();
} else if (encryption.name() == "CipherReference") {
uri = Utility::URLDecodePath(encryption.attributes().value("", "URI").toString());
encrypted_files[ uri ] = encryption_algo;
}
}
}
if (encryption.hasError()) {
const QString error = QString(QObject::tr("Error parsing encryption xml.\nLine: %1 Column %2 - %3"))
.arg(encryption.lineNumber())
.arg(encryption.columnNumber())
.arg(encryption.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
return encrypted_files;
}
bool ImportEPUB::BookContentEncrypted(const QHash<QString, QString> &encrypted_files)
{
foreach(QString algorithm, encrypted_files.values()) {
if (algorithm != ADOBE_FONT_ALGO_ID &&
algorithm != IDPF_FONT_ALGO_ID) {
return true;
}
}
return false;
}
// This is basically a workaround for old versions of InDesign not listing the fonts it
// embedded in the OPF manifest, even though the specs say it has to.
// It does list them in the encryption.xml, so we use that.
void ImportEPUB::AddObfuscatedButUndeclaredFonts(const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
foreach(QString filepath, encrypted_files.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(filepath).suffix().toLower())) {
continue;
}
// Only add the path to the manifest if it is not already included.
QMapIterator<QString, QString> valueSearch(m_Files);
if (!valueSearch.findNext(opf_dir.relativeFilePath(filepath))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(filepath);
}
}
}
// Another workaround for non-standard Apple files
// At present it only handles com.apple.ibooks.display-options.xml, but any
// further iBooks aberrations should be handled here as well.
void ImportEPUB::AddNonStandardAppleXML()
{
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QStringList aberrant_Apple_filenames;
aberrant_Apple_filenames.append(m_ExtractedFolderPath + "/META-INF/com.apple.ibooks.display-options.xml");
for (int i = 0; i < aberrant_Apple_filenames.size(); ++i) {
if (QFile::exists(aberrant_Apple_filenames.at(i))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(aberrant_Apple_filenames.at(i));
}
}
}
// Each resource can provide us with its new path. encrypted_files provides
// a mapping from old resource paths to the obfuscation algorithms.
// So we use the updates hash which provides a mapping from old paths to new
// paths to match the resources to their algorithms.
void ImportEPUB::ProcessFontFiles(const QList<Resource *> &resources,
const QHash<QString, QString> &updates,
const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QList<FontResource *> font_resources = m_Book->GetFolderKeeper()->GetResourceTypeList<FontResource>();
if (font_resources.empty()) {
return;
}
QHash<QString, QString> new_font_paths_to_algorithms;
foreach(QString old_update_path, updates.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(old_update_path).suffix().toLower())) {
continue;
}
QString new_update_path = updates[ old_update_path ];
foreach(QString old_encrypted_path, encrypted_files.keys()) {
if (old_update_path == old_encrypted_path) {
new_font_paths_to_algorithms[ new_update_path ] = encrypted_files[ old_encrypted_path ];
}
}
}
foreach(FontResource * font_resource, font_resources) {
QString match_path = "../" + font_resource->GetRelativePathToOEBPS();
QString algorithm = new_font_paths_to_algorithms.value(match_path);
if (algorithm.isEmpty()) {
continue;
}
font_resource->SetObfuscationAlgorithm(algorithm);
// Actually we are de-obfuscating, but the inverse operations of the obfuscation methods
// are the obfuscation methods themselves. For the math oriented, the obfuscation methods
// are involutary [ f( f( x ) ) = x ].
if (algorithm == ADOBE_FONT_ALGO_ID) {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UuidIdentifierValue);
} else {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UniqueIdentifierValue);
}
}
}
void ImportEPUB::ExtractContainer()
{
int res = 0;
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData());
#endif
if (zfile == NULL) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot unzip EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
QDir dir(m_ExtractedFolderPath);
// Full file path in the temporary directory.
QString file_path = m_ExtractedFolderPath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
// add it to the list of files found inside the zip
if (cp437_file_name.isEmpty()) {
m_ZipFilePaths << qfile_name;
} else {
m_ZipFilePaths << cp437_file_name;
}
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = m_ExtractedFolderPath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot open EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
unzClose(zfile);
}
void ImportEPUB::LocateOPF()
{
QString fullpath = m_ExtractedFolderPath + "/META-INF/container.xml";
QXmlStreamReader container;
try {
container.addData(Utility::ReadUnicodeTextFile(fullpath));
} catch (CannotOpenFile) {
// Find the first OPF file.
QString OPFfile;
QDirIterator files(m_ExtractedFolderPath, QStringList() << "*.opf", QDir::NoFilter, QDirIterator::Subdirectories);
while (files.hasNext()) {
OPFfile = QDir(m_ExtractedFolderPath).relativeFilePath(files.next());
break;
}
if (OPFfile.isEmpty()) {
std::string msg = fullpath.toStdString() + ": " + tr("Epub has missing or improperly specified OPF.").toStdString();
throw (CannotOpenFile(msg));
}
// Create a default container.xml.
QDir folder(m_ExtractedFolderPath);
folder.mkdir("META-INF");
Utility::WriteUnicodeTextFile(CONTAINER_XML.arg(OPFfile), fullpath);
container.addData(Utility::ReadUnicodeTextFile(fullpath));
}
while (!container.atEnd()) {
container.readNext();
if (container.isStartElement() &&
container.name() == "rootfile"
) {
if (container.attributes().hasAttribute("media-type") &&
container.attributes().value("", "media-type") == OEBPS_MIMETYPE
) {
m_OPFFilePath = m_ExtractedFolderPath + "/" + container.attributes().value("", "full-path").toString();
// As per OCF spec, the first rootfile element
// with the OEBPS mimetype is considered the "main" one.
break;
}
}
}
if (container.hasError()) {
const QString error = QString(
QObject::tr("Unable to parse container.xml file.\nLine: %1 Column %2 - %3"))
.arg(container.lineNumber())
.arg(container.columnNumber())
.arg(container.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
if (m_OPFFilePath.isEmpty() || !QFile::exists(m_OPFFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("No appropriate OPF file found")).toStdString()));
}
}
void ImportEPUB::ReadOPF()
{
QString opf_text = CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE);
QXmlStreamReader opf_reader(opf_text);
QString ncx_id_on_spine;
while (!opf_reader.atEnd()) {
opf_reader.readNext();
if (!opf_reader.isStartElement()) {
continue;
}
if (opf_reader.name() == "package") {
m_UniqueIdentifierId = opf_reader.attributes().value("", "unique-identifier").toString();
m_PackageVersion = opf_reader.attributes().value("", "version").toString();
if (m_PackageVersion == "1.0") m_PackageVersion = "2.0";
}
else if (opf_reader.name() == "identifier") {
ReadIdentifierElement(&opf_reader);
}
// epub3 look for linked metadata resources that are included inside the epub
// but that are not and must not be included in the manifest
else if (opf_reader.name() == "link") {
ReadMetadataLinkElement(&opf_reader);
}
// Get the list of content files that
// make up the publication
else if (opf_reader.name() == "item") {
ReadManifestItemElement(&opf_reader);
}
// We read this just to get the NCX id
else if (opf_reader.name() == "spine") {
ncx_id_on_spine = opf_reader.attributes().value("", "toc").toString();
}
else if (opf_reader.name() == "itemref") {
m_HasSpineItems = true;
}
}
if (opf_reader.hasError()) {
const QString error = QString(QObject::tr("Unable to read OPF file.\nLine: %1 Column %2 - %3"))
.arg(opf_reader.lineNumber())
.arg(opf_reader.columnNumber())
.arg(opf_reader.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
// Ensure we have an NCX available
LocateOrCreateNCX(ncx_id_on_spine);
}
void ImportEPUB::ReadIdentifierElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString scheme = opf_reader->attributes().value("", "scheme").toString();
QString value = opf_reader->readElementText();
if (id == m_UniqueIdentifierId) {
m_UniqueIdentifierValue = value;
}
if (m_UuidIdentifierValue.isEmpty() &&
(value.contains("urn:uuid:") || scheme.toLower() == "uuid")) {
m_UuidIdentifierValue = value;
}
}
void ImportEPUB::ReadMetadataLinkElement(QXmlStreamReader *opf_reader)
{
QString relation = opf_reader->attributes().value("", "rel").toString();
QString mtype = opf_reader->attributes().value("", "media-type").toString();
QString props = opf_reader->attributes().value("", "properties").toString();
QString href = opf_reader->attributes().value("", "href").toString();
if (!href.isEmpty()) {
QUrl url = QUrl(href);
if (url.isRelative()) {
// we have a local unmanifested metadata file to handle
// attempt to map deprecated record types into proper media-types
if (relation == "marc21xml-record") {
mtype = "application/marcxml+xml";
}
else if (relation == "mods-record") {
mtype = "application/mods+xml";
}
else if (relation == "onix-record") {
mtype = "application/xml;onix";
}
else if (relation == "xmp-record") {
mtype = "application/xml;xmp";
}
else if (relation == "record") {
if (props == "onix") mtype = "application/xml;onix";
if (props == "xmp") mtype = "application/xml;xmp";
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QString path = opf_dir.absolutePath() + "/" + url.path();
if (QFile::exists(path)) {
QString id = Utility::CreateUUID();
m_Files[ id ] = opf_dir.relativeFilePath(path);
m_FileMimetypes[ id ] = mtype;
}
}
}
}
void ImportEPUB::ReadManifestItemElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString href = opf_reader->attributes().value("", "href").toString();
QString type = opf_reader->attributes().value("", "media-type").toString();
QString properties = opf_reader->attributes().value("", "properties").toString();
// Paths are percent encoded in the OPF, we use "normal" paths internally.
href = Utility::URLDecodePath(href);
QString extension = QFileInfo(href).suffix().toLower();
// find the epub root relative file path from the opf location and the item href
QString file_path = m_opfDir.absolutePath() + "/" + href;
file_path = file_path.remove(0, m_ExtractedFolderPath.length() + 1);
if (type != NCX_MIMETYPE && extension != NCX_EXTENSION) {
if (!m_ManifestFilePaths.contains(file_path)) {
if (m_Files.contains(id)) {
// We have an error situation with a duplicate id in the epub.
// We must warn the user, but attempt to use another id so the epub can still be loaded.
QString base_id = QFileInfo(href).fileName();
QString new_id(base_id);
int duplicate_index = 0;
while (m_Files.contains(new_id)) {
duplicate_index++;
new_id = QString("%1%2").arg(base_id).arg(duplicate_index);
}
const QString load_warning = QObject::tr("The OPF manifest contains duplicate ids for: %1").arg(id) +
" - " + QObject::tr("A temporary id has been assigned to load this EPUB. You should edit your OPF file to remove the duplication.");
id = new_id;
AddLoadWarning(load_warning);
}
m_Files[ id ] = href;
m_FileMimetypes[ id ] = type;
m_ManifestFilePaths << file_path;
// store information about any nav document
if (properties.contains("nav")) {
m_NavId = id;
m_NavHref = href;
}
}
} else {
m_NcxCandidates[ id ] = href;
m_ManifestFilePaths << file_path;
}
}
void ImportEPUB::LocateOrCreateNCX(const QString &ncx_id_on_spine)
{
QString load_warning;
QString ncx_href = "not_found";
m_NCXId = ncx_id_on_spine;
// Handle various failure conditions, such as:
// - ncx not specified in the spine (search for a matching manifest item by extension)
// - ncx specified in spine, but no matching manifest item entry (create a new one)
// - ncx file not physically present (create a new one)
// - ncx not in spine or manifest item (create a new one)
if (!m_NCXId.isEmpty()) {
ncx_href = m_NcxCandidates[ m_NCXId ];
} else {
// Search for the ncx in the manifest by looking for files with
// a .ncx extension.
QHashIterator<QString, QString> ncxSearch(m_NcxCandidates);
while (ncxSearch.hasNext()) {
ncxSearch.next();
if (QFileInfo(ncxSearch.value()).suffix().toLower() == NCX_EXTENSION) {
m_NCXId = ncxSearch.key();
load_warning = QObject::tr("The OPF file did not identify the NCX file correctly.") + "\n" +
" - " + QObject::tr("Sigil has used the following file as the NCX:") +
QString(" %1").arg(m_NcxCandidates[ m_NCXId ]);
ncx_href = m_NcxCandidates[ m_NCXId ];
break;
}
}
}
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % ncx_href;
if (ncx_href.isEmpty() || !QFile::exists(m_NCXFilePath)) {
m_NCXNotInManifest = m_NCXId.isEmpty() || ncx_href.isEmpty();
m_NCXId.clear();
// Things are really bad and no .ncx file was found in the manifest or
// the file does not physically exist. We need to create a new one.
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % NCX_FILE_NAME;
// Create a new file for the NCX.
NCXResource ncx_resource(m_ExtractedFolderPath, m_NCXFilePath, m_Book->GetFolderKeeper());
// We are relying on an identifier being set from the metadata.
// It might not have one if the book does not have the urn:uuid: format.
if (!m_UuidIdentifierValue.isEmpty()) {
ncx_resource.SetMainID(m_UuidIdentifierValue);
}
ncx_resource.SaveToDisk();
if (m_PackageVersion.startsWith('3')) {
load_warning = QObject::tr("Sigil has created a template NCX") + "\n" +
QObject::tr("to support epub2 backwards compatibility.");
} else {
if (ncx_href.isEmpty()) {
load_warning = QObject::tr("The OPF file does not contain an NCX file.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
} else {
load_warning = QObject::tr("The NCX file is not present in this EPUB.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
}
}
}
if (!load_warning.isEmpty()) {
AddLoadWarning(load_warning);
}
}
void ImportEPUB::LoadInfrastructureFiles()
{
// always SetEpubVersion before SetText in OPF as SetText will validate with it
m_Book->GetOPF()->SetEpubVersion(m_PackageVersion);
m_Book->GetOPF()->SetText(CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE));
QString OPFBookRelPath = m_OPFFilePath;
OPFBookRelPath = OPFBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetOPF()->SetCurrentBookRelPath(OPFBookRelPath);
m_Book->GetNCX()->SetText(CleanSource::ProcessXML(Utility::ReadUnicodeTextFile(m_NCXFilePath),"application/x-dtbncx+xml"));
m_Book->GetNCX()->SetEpubVersion(m_PackageVersion);
QString NCXBookRelPath = m_NCXFilePath;
NCXBookRelPath = NCXBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetNCX()->SetCurrentBookRelPath(NCXBookRelPath);
}
QHash<QString, QString> ImportEPUB::LoadFolderStructure()
{
QList<QString> keys = m_Files.keys();
int num_files = keys.count();
QFutureSynchronizer<std::tuple<QString, QString>> sync;
for (int i = 0; i < num_files; ++i) {
QString id = keys.at(i);
sync.addFuture(QtConcurrent::run(
this,
&ImportEPUB::LoadOneFile,
m_Files.value(id),
m_FileMimetypes.value(id)));
}
sync.waitForFinished();
QList<QFuture<std::tuple<QString, QString>>> futures = sync.futures();
int num_futures = futures.count();
QHash<QString, QString> updates;
for (int i = 0; i < num_futures; ++i) {
std::tuple<QString, QString> result = futures.at(i).result();
updates[std::get<0>(result)] = std::get<1>(result);
}
updates.remove(UPDATE_ERROR_STRING);
return updates;
}
std::tuple<QString, QString> ImportEPUB::LoadOneFile(const QString &path, const QString &mimetype)
{
QString fullfilepath = QDir::cleanPath(QFileInfo(m_OPFFilePath).absolutePath() + "/" + path);
QString currentpath = fullfilepath;
currentpath = currentpath.remove(0,m_ExtractedFolderPath.length()+1);
try {
Resource *resource = m_Book->GetFolderKeeper()->AddContentFileToFolder(fullfilepath, false, mimetype);
if (path == m_NavHref) {
m_NavResource = resource;
}
resource->SetCurrentBookRelPath(currentpath);
QString newpath = "../" + resource->GetRelativePathToOEBPS();
return std::make_tuple(currentpath, newpath);
} catch (FileDoesNotExist) {
return std::make_tuple(UPDATE_ERROR_STRING, UPDATE_ERROR_STRING);
}
}
QString ImportEPUB::PrepareOPFForReading(const QString &source)
{
QString source_copy(source);
QString prefix = source_copy.left(XML_DECLARATION_SEARCH_PREFIX_SIZE);
QRegularExpression version(VERSION_ATTRIBUTE);
QRegularExpressionMatch mo = version.match(prefix);
if (mo.hasMatch()) {
// MASSIVE hack for XML 1.1 "support";
// this is only for people who specify
// XML 1.1 when they actually only use XML 1.0
source_copy.replace(mo.capturedStart(1), mo.capturedLength(1), "1.0");
}
return source_copy;
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_975_0 |
crossvul-cpp_data_bad_196_5 | /*
* Cantata
*
* Copyright (c) 2011-2018 Craig Drummond <craig.p.drummond@gmail.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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "avahi.h"
#include "avahiservice.h"
#include "serverinterface.h"
#include "serviceresolverinterface.h"
Q_DECLARE_METATYPE(QList<QByteArray>)
AvahiService::AvahiService(const QString &n, const QString &type, const QString &domain)
: name(n)
, port(0)
{
static bool registeredTypes=false;
if (!registeredTypes) {
qDBusRegisterMetaType<QList<QByteArray> >();
registeredTypes=true;
}
org::freedesktop::Avahi::Server server("org.freedesktop.Avahi", "/", QDBusConnection::systemBus());
QDBusReply<QDBusObjectPath> reply=server.ServiceResolverNew(-1, -1, name, type, Avahi::domainToDNS(domain), -1, 8 /*AVAHI_LOOKUP_NO_ADDRESS|AVAHI_LOOKUP_NO_TXT*/);
if (reply.isValid()) {
resolver=new OrgFreedesktopAvahiServiceResolverInterface("org.freedesktop.Avahi", reply.value().path(), QDBusConnection::systemBus());
connect(resolver, SIGNAL(Found(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort,const QList<QByteArray>&, uint)),
this, SLOT(resolved(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort, const QList<QByteArray>&, uint)));
connect(resolver, SIGNAL(Failure(QString)), this, SLOT(error(QString)));
}
}
AvahiService::~AvahiService()
{
stop();
}
void AvahiService::resolved(int, int, const QString &name, const QString &, const QString &, const QString &h, int, const QString &, ushort p, const QList<QByteArray> &, uint)
{
Q_UNUSED(name)
port=p;
host=h;
stop();
emit serviceResolved(name);
}
void AvahiService::error(const QString &)
{
stop();
}
void AvahiService::stop()
{
if (resolver) {
resolver->Free();
resolver->deleteLater();
disconnect(resolver, SIGNAL(Found(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort,const QList<QByteArray>&, uint)),
this, SLOT(resolved(int,int,const QString &,const QString &,const QString &,const QString &, int, const QString &,ushort, const QList<QByteArray>&, uint)));
disconnect(resolver, SIGNAL(Failure(QString)), this, SLOT(error(QString)));
resolver=0;
}
}
#include "moc_avahiservice.cpp"
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_196_5 |
crossvul-cpp_data_good_4235_0 | /******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2019, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "TarFileReader.h"
#include <cbang/os/SystemUtilities.h>
#include <cbang/os/SysError.h>
#include <cbang/log/Logger.h>
#include <cbang/iostream/BZip2Decompressor.h>
#include <boost/ref.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
namespace io = boost::iostreams;
using namespace cb;
using namespace std;
struct TarFileReader::private_t {
io::filtering_istream filter;
};
TarFileReader::TarFileReader(const string &path, compression_t compression) :
pri(new private_t), stream(SystemUtilities::iopen(path)),
didReadHeader(false) {
addCompression(compression == TARFILE_AUTO ? infer(path) : compression);
pri->filter.push(*this->stream);
}
TarFileReader::TarFileReader(istream &stream, compression_t compression) :
pri(new private_t), stream(SmartPointer<istream>::Phony(&stream)),
didReadHeader(false) {
addCompression(compression);
pri->filter.push(*this->stream);
}
TarFileReader::~TarFileReader() {
delete pri;
}
bool TarFileReader::hasMore() {
if (!didReadHeader) {
SysError::clear();
if (!readHeader(pri->filter))
THROW("Tar file read failed: " << SysError());
didReadHeader = true;
}
return !isEOF();
}
bool TarFileReader::next() {
if (didReadHeader) {
skipFile(pri->filter);
didReadHeader = false;
}
return hasMore();
}
std::string TarFileReader::extract(const string &_path) {
if (_path.empty()) THROW("path cannot be empty");
if (!hasMore()) THROW("No more tar files");
string path = _path;
if (SystemUtilities::isDirectory(path)) {
path += "/" + getFilename();
// Check that path is under the target directory
string a = SystemUtilities::getCanonicalPath(_path);
string b = SystemUtilities::getCanonicalPath(path);
if (!String::startsWith(b, a))
THROW("Tar path points outside of the extraction directory: " << path);
}
LOG_DEBUG(5, "Extracting: " << path);
switch (getType()) {
case NORMAL_FILE: case CONTIGUOUS_FILE:
return extract(*SystemUtilities::oopen(path));
case DIRECTORY: SystemUtilities::ensureDirectory(path); break;
default: THROW("Unsupported tar file type " << getType());
}
return getFilename();
}
string TarFileReader::extract(ostream &out) {
if (!hasMore()) THROW("No more tar files");
readFile(out, pri->filter);
didReadHeader = false;
return getFilename();
}
void TarFileReader::addCompression(compression_t compression) {
switch (compression) {
case TARFILE_NONE: break; // none
case TARFILE_BZIP2: pri->filter.push(BZip2Decompressor()); break;
case TARFILE_GZIP: pri->filter.push(io::zlib_decompressor()); break;
default: THROW("Invalid compression type " << compression);
}
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_4235_0 |
crossvul-cpp_data_bad_974_0 | /************************************************************************
**
** Copyright (C) 2009, 2010, 2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil 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.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#ifdef _WIN32
#define NOMINMAX
#endif
#include "unzip.h"
#ifdef _WIN32
#include "iowin32.h"
#endif
#include <stdio.h>
#include <time.h>
#include <string>
#include <QApplication>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtCore/QStandardPaths>
#include <QtCore/QStringList>
#include <QtCore/QStringRef>
#include <QtCore/QTextStream>
#include <QtCore/QtGlobal>
#include <QtCore/QUrl>
#include <QtCore/QUuid>
#include <QtWidgets/QMainWindow>
#include <QTextEdit>
#include <QMessageBox>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QFile>
#include <QFileInfo>
#include "sigil_constants.h"
#include "sigil_exception.h"
#include "Misc/QCodePage437Codec.h"
#include "Misc/SettingsStore.h"
#include "Misc/SleepFunctions.h"
#ifndef MAX_PATH
// Set Max length to 256 because that's the max path size on many systems.
#define MAX_PATH 256
#endif
// This is the same read buffer size used by Java and Perl.
#define BUFF_SIZE 8192
static QCodePage437Codec *cp437 = 0;
// Subclass QMessageBox for our StdWarningDialog to make any Details Resizable
class SigilMessageBox: public QMessageBox
{
public:
SigilMessageBox(QWidget* parent) : QMessageBox(parent)
{
setSizeGripEnabled(true);
}
private:
virtual void resizeEvent(QResizeEvent * e) {
QMessageBox::resizeEvent(e);
setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
if (QWidget *textEdit = findChild<QTextEdit *>()) {
textEdit->setMaximumHeight(QWIDGETSIZE_MAX);
}
}
};
#include "Misc/Utility.h"
// Define the user preferences location to be used
QString Utility::DefinePrefsDir()
{
// If the SIGIL_PREFS_DIR environment variable override exists; use it.
// It's up to the user to provide a directory they have permission to write to.
if (!SIGIL_PREFS_DIR.isEmpty()) {
return SIGIL_PREFS_DIR;
} else {
return QStandardPaths::writableLocation(QStandardPaths::DataLocation);
}
}
#if !defined(Q_OS_WIN32) && !defined(Q_OS_MAC)
// Return correct path(s) for Linux hunspell dictionaries
QStringList Utility::LinuxHunspellDictionaryDirs()
{
QStringList paths;
// prefer the directory specified by the env var SIGIL_DICTIONARIES above all else.
if (!hunspell_dicts_override.isEmpty()) {
// Handle multiple colon-delimited paths
foreach (QString s, hunspell_dicts_override.split(":")) {
paths << s.trimmed();
}
}
// else use the env var runtime overridden 'share/sigil/hunspell_dictionaries/' location.
else if (!sigil_extra_root.isEmpty()) {
paths.append(sigil_extra_root + "/hunspell_dictionaries/");
}
// Bundled dicts were not installed use standard system dictionary location.
else if (!dicts_are_bundled) {
paths.append("/usr/share/hunspell");
// Add additional hunspell dictionary directories. Provided at compile
// time via the cmake option EXTRA_DICT_DIRS (colon separated list).
if (!extra_dict_dirs.isEmpty()) {
foreach (QString s, extra_dict_dirs.split(":")) {
paths << s.trimmed();
}
}
}
else {
// else use the standard build time 'share/sigil/hunspell_dictionaries/'location.
paths.append(sigil_share_root + "/hunspell_dictionaries/");
}
return paths;
}
#endif
// Uses QUuid to generate a random UUID but also removes
// the curly braces that QUuid::createUuid() adds
QString Utility::CreateUUID()
{
return QUuid::createUuid().toString().remove("{").remove("}");
}
// Convert the casing of the text, returning the result.
QString Utility::ChangeCase(const QString &text, const Utility::Casing &casing)
{
if (text.isEmpty()) {
return text;
}
switch (casing) {
case Utility::Casing_Lowercase: {
return text.toLower();
}
case Utility::Casing_Uppercase: {
return text.toUpper();
}
case Utility::Casing_Titlecase: {
// This is a super crude algorithm, could be replaced by something more clever.
QString new_text = text.toLower();
// Skip past any leading spaces
int i = 0;
while (i < text.length() && new_text.at(i).isSpace()) {
i++;
}
while (i < text.length()) {
if (i == 0 || new_text.at(i - 1).isSpace()) {
new_text.replace(i, 1, new_text.at(i).toUpper());
}
i++;
}
return new_text;
}
case Utility::Casing_Capitalize: {
// This is a super crude algorithm, could be replaced by something more clever.
QString new_text = text.toLower();
// Skip past any leading spaces
int i = 0;
while (i < text.length() && new_text.at(i).isSpace()) {
i++;
}
if (i < text.length()) {
new_text.replace(i, 1, new_text.at(i).toUpper());
}
return new_text;
}
default:
return text;
}
}
// Returns true if the string is mixed case, false otherwise.
// For instance, "test" and "TEST" return false, "teSt" returns true.
// If the string is empty, returns false.
bool Utility::IsMixedCase(const QString &string)
{
if (string.isEmpty() || string.length() == 1) {
return false;
}
bool first_char_lower = string[ 0 ].isLower();
for (int i = 1; i < string.length(); ++i) {
if (string[ i ].isLower() != first_char_lower) {
return true;
}
}
return false;
}
// Returns a substring of a specified string;
// the characters included are in the interval:
// [ start_index, end_index >
QString Utility::Substring(int start_index, int end_index, const QString &string)
{
return string.mid(start_index, end_index - start_index);
}
// Returns a substring of a specified string;
// the characters included are in the interval:
// [ start_index, end_index >
QStringRef Utility::SubstringRef(int start_index, int end_index, const QString &string)
{
return string.midRef(start_index, end_index - start_index);
}
// Replace the first occurrence of string "before"
// with string "after" in string "string"
QString Utility::ReplaceFirst(const QString &before, const QString &after, const QString &string)
{
int start_index = string.indexOf(before);
int end_index = start_index + before.length();
return Substring(0, start_index, string) + after + Substring(end_index, string.length(), string);
}
QStringList Utility::GetAbsolutePathsToFolderDescendantFiles(const QString &fullfolderpath)
{
QDir folder(fullfolderpath);
QStringList files;
foreach(QFileInfo file, folder.entryInfoList()) {
if ((file.fileName() != ".") && (file.fileName() != "..")) {
// If it's a file, add it to the list
if (file.isFile()) {
files.append(Utility::URLEncodePath(file.absoluteFilePath()));
}
// Else it's a directory, so
// we add all files from that dir
else {
files.append(GetAbsolutePathsToFolderDescendantFiles(file.absoluteFilePath()));
}
}
}
return files;
}
// Copies every file and folder in the source folder
// to the destination folder; the paths to the folders are submitted;
// the destination folder needs to be created in advance
void Utility::CopyFiles(const QString &fullfolderpath_source, const QString &fullfolderpath_destination)
{
QDir folder_source(fullfolderpath_source);
QDir folder_destination(fullfolderpath_destination);
// Erase all the files in this folder
foreach(QFileInfo file, folder_source.entryInfoList()) {
if ((file.fileName() != ".") && (file.fileName() != "..")) {
// If it's a file, copy it
if (file.isFile()) {
QString destination = fullfolderpath_destination + "/" + file.fileName();
bool success = QFile::copy(file.absoluteFilePath(), destination);
if (!success) {
std::string msg = file.absoluteFilePath().toStdString() + ": " + destination.toStdString();
throw(CannotCopyFile(msg));
}
}
// Else it's a directory, copy everything in it
// to a new folder of the same name in the destination folder
else {
folder_destination.mkpath(file.fileName());
CopyFiles(file.absoluteFilePath(), fullfolderpath_destination + "/" + file.fileName());
}
}
}
}
//
// Delete a directory along with all of its contents.
//
// \param dirName Path of directory to remove.
// \return true on success; false on error.
//
bool Utility::removeDir(const QString &dirName)
{
bool result = true;
QDir dir(dirName);
if (dir.exists(dirName)) {
Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
if (info.isDir()) {
result = removeDir(info.absoluteFilePath());
} else {
result = QFile::remove(info.absoluteFilePath());
}
if (!result) {
return result;
}
}
result = dir.rmdir(dirName);
}
return result;
}
// Deletes the specified file if it exists
bool Utility::SDeleteFile(const QString &fullfilepath)
{
// Make sure the path exists, otherwise very
// bad things could happen
if (!QFileInfo(fullfilepath).exists()) {
return false;
}
QFile file(fullfilepath);
bool deleted = file.remove();
// Some multiple file deletion operations fail on Windows, so we try once more.
if (!deleted) {
qApp->processEvents();
SleepFunctions::msleep(100);
deleted = file.remove();
}
return deleted;
}
// Copies File from full Inpath to full OutPath with overwrite if needed
bool Utility::ForceCopyFile(const QString &fullinpath, const QString &fulloutpath)
{
if (!QFileInfo(fullinpath).exists()) {
return false;
}
if (QFileInfo::exists(fulloutpath)) {
Utility::SDeleteFile(fulloutpath);
}
return QFile::copy(fullinpath, fulloutpath);
}
bool Utility::RenameFile(const QString &oldfilepath, const QString &newfilepath)
{
// Make sure the path exists, otherwise very
// bad things could happen
if (!QFileInfo(oldfilepath).exists()) {
return false;
}
// Ensure that the newfilepath doesn't already exist but due to case insenstive file systems
// check if we are actually renaming to an identical path with a different case.
if (QFileInfo(newfilepath).exists() && QFileInfo(oldfilepath) != QFileInfo(newfilepath)) {
return false;
}
// On case insensitive file systems, QFile::rename fails when the new name is the
// same (case insensitive) to the old one. This is workaround for that issue.
int ret = -1;
#if defined(Q_OS_WIN32)
ret = _wrename(Utility::QStringToStdWString(oldfilepath).data(), Utility::QStringToStdWString(newfilepath).data());
#else
ret = rename(oldfilepath.toUtf8().data(), newfilepath.toUtf8().data());
#endif
if (ret == 0) {
return true;
}
return false;
}
QString Utility::GetTemporaryFileNameWithExtension(const QString &extension)
{
SettingsStore ss;
QString temp_path = ss.tempFolderHome();
if (temp_path == "<SIGIL_DEFAULT_TEMP_HOME>") {
temp_path = QDir::tempPath();
}
return temp_path + "/sigil_" + Utility::CreateUUID() + extension;
}
// Returns true if the file can be read;
// shows an error dialog if it can't
// with a message elaborating what's wrong
bool Utility::IsFileReadable(const QString &fullfilepath)
{
// Qt has <QFileInfo>.exists() and <QFileInfo>.isReadable()
// functions, but then we would have to create our own error
// message for each of those situations (and more). Trying to
// actually open the file enables us to retrieve the exact
// reason preventing us from reading the file in an error string.
QFile file(fullfilepath);
// Check if we can open the file
if (!file.open(QFile::ReadOnly)) {
Utility::DisplayStdErrorDialog(
QObject::tr("Cannot read file %1:\n%2.")
.arg(fullfilepath)
.arg(file.errorString())
);
return false;
}
file.close();
return true;
}
// Reads the text file specified with the full file path;
// text needs to be in UTF-8 or UTF-16; if the file cannot
// be read, an error dialog is shown and an empty string returned
QString Utility::ReadUnicodeTextFile(const QString &fullfilepath)
{
// TODO: throw an exception instead of
// returning an empty string
QFile file(fullfilepath);
// Check if we can open the file
if (!file.open(QFile::ReadOnly)) {
std::string msg = fullfilepath.toStdString() + ": " + file.errorString().toStdString();
throw(CannotOpenFile(msg));
}
QTextStream in(&file);
// Input should be UTF-8
in.setCodec("UTF-8");
// This will automatically switch reading from
// UTF-8 to UTF-16 if a BOM is detected
in.setAutoDetectUnicode(true);
return ConvertLineEndings(in.readAll());
}
// Writes the provided text variable to the specified
// file; if the file exists, it is truncated
void Utility::WriteUnicodeTextFile(const QString &text, const QString &fullfilepath)
{
QFile file(fullfilepath);
if (!file.open(QIODevice::WriteOnly |
QIODevice::Truncate |
QIODevice::Text
)
) {
std::string msg = file.fileName().toStdString() + ": " + file.errorString().toStdString();
throw(CannotOpenFile(msg));
}
QTextStream out(&file);
// We ALWAYS output in UTF-8
out.setCodec("UTF-8");
out << text;
}
// Converts Mac and Windows style line endings to Unix style
// line endings that are expected throughout the Qt framework
QString Utility::ConvertLineEndings(const QString &text)
{
QString newtext(text);
return newtext.replace("\x0D\x0A", "\x0A").replace("\x0D", "\x0A");
}
// Decodes XML escaped string to normal text
// & -> "&" ' -> "'" " -> "\"" < -> "<" > -> ">"
QString Utility::DecodeXML(const QString &text)
{
QString newtext(text);
newtext.replace("'", "'");
newtext.replace(""", "\"");
newtext.replace("<", "<");
newtext.replace(">", ">");
newtext.replace("&", "&");
return newtext;
}
QString Utility::EncodeXML(const QString &text)
{
QString newtext(text);
return newtext.toHtmlEscaped();
}
QString Utility::URLEncodePath(const QString &path)
{
QString newpath = path;
QUrl href = QUrl(newpath);
QString scheme = href.scheme();
if (!scheme.isEmpty()) {
scheme = scheme + "://";
newpath.remove(0, scheme.length());
}
QByteArray encoded_url = QUrl::toPercentEncoding(newpath, QByteArray("/#"));
return scheme + QString::fromUtf8(encoded_url.constData(), encoded_url.count());
}
QString Utility::URLDecodePath(const QString &path)
{
return QUrl::fromPercentEncoding(path.toUtf8());
}
void Utility::DisplayExceptionErrorDialog(const QString &error_info)
{
QMessageBox message_box(QApplication::activeWindow());
message_box.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
message_box.setModal(true);
message_box.setIcon(QMessageBox::Critical);
message_box.setWindowTitle("Sigil");
// Spaces are added to the end because otherwise the dialog is too small.
message_box.setText(QObject::tr("Sigil has encountered a problem.") % " ");
message_box.setInformativeText(QObject::tr("Sigil may need to close."));
message_box.setStandardButtons(QMessageBox::Close);
QStringList detailed_text;
detailed_text << "Error info: " + error_info
<< "Sigil version: " + QString(SIGIL_FULL_VERSION)
<< "Runtime Qt: " + QString(qVersion())
<< "Compiled Qt: " + QString(QT_VERSION_STR);
#if defined Q_OS_WIN32
detailed_text << "Platform: Windows SysInfo ID " + QString::number(QSysInfo::WindowsVersion);
#elif defined Q_OS_MAC
detailed_text << "Platform: Mac SysInfo ID " + QString::number(QSysInfo::MacintoshVersion);
#else
detailed_text << "Platform: Linux";
#endif
message_box.setDetailedText(detailed_text.join("\n"));
message_box.exec();
}
void Utility::DisplayStdErrorDialog(const QString &error_message, const QString &detailed_text)
{
QMessageBox message_box(QApplication::activeWindow());
message_box.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
message_box.setModal(true);
message_box.setIcon(QMessageBox::Critical);
message_box.setWindowTitle("Sigil");
message_box.setText(error_message);
if (!detailed_text.isEmpty()) {
message_box.setDetailedText(detailed_text);
}
message_box.setStandardButtons(QMessageBox::Close);
message_box.exec();
}
void Utility::DisplayStdWarningDialog(const QString &warning_message, const QString &detailed_text)
{
SigilMessageBox message_box(QApplication::activeWindow());
message_box.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
message_box.setModal(true);
message_box.setIcon(QMessageBox::Warning);
message_box.setWindowTitle("Sigil");
message_box.setText(warning_message);
message_box.setTextFormat(Qt::RichText);
if (!detailed_text.isEmpty()) {
message_box.setDetailedText(detailed_text);
}
message_box.setStandardButtons(QMessageBox::Close);
message_box.exec();
}
// Returns a value for the environment variable name passed;
// if the env var isn't set, it returns an empty string
QString Utility::GetEnvironmentVar(const QString &variable_name)
{
// Renaming this function (and all references to it)
// to GetEnvironmentVariable gets you a linker error
// on MSVC 9. Funny, innit?
QRegularExpression search_for_name("^" + QRegularExpression::escape(variable_name) + "=");
QString variable = QProcess::systemEnvironment().filter(search_for_name).value(0);
if (!variable.isEmpty()) {
return variable.split("=")[ 1 ];
} else {
return QString();
}
}
// Returns the same number, but rounded to one decimal place
float Utility::RoundToOneDecimal(float number)
{
return QString::number(number, 'f', 1).toFloat();
}
QWidget *Utility::GetMainWindow()
{
QWidget *parent_window = QApplication::activeWindow();
while (parent_window && !(dynamic_cast<QMainWindow *>(parent_window))) {
parent_window = parent_window->parentWidget();
}
return parent_window;
}
QString Utility::getSpellingSafeText(const QString &raw_text)
{
// There is currently a problem with Hunspell if we attempt to pass
// words with smart apostrophes from the CodeView encoding.
// Hunspell dictionaries typically store their main wordlist using
// the dumb apostrophe variants only to save space and speed checking
QString text(raw_text);
return text.replace(QChar(0x2019),QChar(0x27));
}
bool Utility::has_non_ascii_chars(const QString &str)
{
QRegularExpression not_ascii("[^\\x00-\\x7F]");
QRegularExpressionMatch mo = not_ascii.match(str);
return mo.hasMatch();
}
bool Utility::use_filename_warning(const QString &filename)
{
if (has_non_ascii_chars(filename)) {
return QMessageBox::Apply == QMessageBox::warning(QApplication::activeWindow(),
tr("Sigil"),
tr("The requested file name contains non-ASCII characters. "
"You should only use ASCII characters in filenames. "
"Using non-ASCII characters can prevent the EPUB from working "
"with some readers.\n\n"
"Continue using the requested filename?"),
QMessageBox::Cancel|QMessageBox::Apply);
}
return true;
}
#if defined(Q_OS_WIN32)
std::wstring Utility::QStringToStdWString(const QString &str)
{
return std::wstring((const wchar_t *)str.utf16());
}
QString Utility::stdWStringToQString(const std::wstring &str)
{
return QString::fromUtf16((const ushort *)str.c_str());
}
#endif
bool Utility::UnZip(const QString &zippath, const QString &destpath)
{
int res = 0;
QDir dir(destpath);
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData());
#endif
if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) {
return false;
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
// Full file path in the temporary directory.
QString file_path = destpath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
return false;
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
return false;
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
return false;
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
return false;
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = destpath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
return false;
}
unzClose(zfile);
return true;
}
QStringList Utility::ZipInspect(const QString &zippath)
{
QStringList filelist;
int res = 0;
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData());
#endif
if ((zfile == NULL) || (!IsFileReadable(zippath))) {
return filelist;
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
filelist.append(cp437_file_name);
} else {
filelist.append(qfile_name);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
unzClose(zfile);
return filelist;
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_974_0 |
crossvul-cpp_data_bad_4235_19 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_4235_19 |
crossvul-cpp_data_good_975_0 | /************************************************************************
**
** Copyright (C) 2016 - 2019 Kevin B. Hendricks, Stratford, Ontario, Canada
** Copyright (C) 2012 John Schember <john@nachtimwald.com>
** Copyright (C) 2009, 2010, 2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil 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.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#ifdef _WIN32
#define NOMINMAX
#endif
#include "unzip.h"
#ifdef _WIN32
#include "iowin32.h"
#endif
#include <string>
#include <QApplication>
#include <QtCore/QtCore>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QFutureSynchronizer>
#include <QtConcurrent/QtConcurrent>
#include <QtCore/QXmlStreamReader>
#include <QDirIterator>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QStringList>
#include <QMessageBox>
#include <QUrl>
#include "BookManipulation/FolderKeeper.h"
#include "BookManipulation/CleanSource.h"
#include "Importers/ImportEPUB.h"
#include "Misc/FontObfuscation.h"
#include "Misc/HTMLEncodingResolver.h"
#include "Misc/QCodePage437Codec.h"
#include "Misc/SettingsStore.h"
#include "Misc/Utility.h"
#include "ResourceObjects/CSSResource.h"
#include "ResourceObjects/HTMLResource.h"
#include "ResourceObjects/OPFResource.h"
#include "ResourceObjects/NCXResource.h"
#include "ResourceObjects/Resource.h"
#include "ResourceObjects/OPFParser.h"
#include "SourceUpdates/UniversalUpdates.h"
#include "sigil_constants.h"
#include "sigil_exception.h"
#ifndef MAX_PATH
// Set Max length to 256 because that's the max path size on many systems.
#define MAX_PATH 256
#endif
// This is the same read buffer size used by Java and Perl.
#define BUFF_SIZE 8192
const QString DUBLIN_CORE_NS = "http://purl.org/dc/elements/1.1/";
static const QString OEBPS_MIMETYPE = "application/oebps-package+xml";
static const QString UPDATE_ERROR_STRING = "SG_ERROR";
const QString NCX_MIMETYPE = "application/x-dtbncx+xml";
static const QString NCX_EXTENSION = "ncx";
const QString ADOBE_FONT_ALGO_ID = "http://ns.adobe.com/pdf/enc#RC";
const QString IDPF_FONT_ALGO_ID = "http://www.idpf.org/2008/embedding";
static const QString CONTAINER_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
" <rootfiles>\n"
" <rootfile full-path=\"%1\" media-type=\"application/oebps-package+xml\"/>\n"
" </rootfiles>\n"
"</container>\n";
static QCodePage437Codec *cp437 = 0;
// Constructor;
// The parameter is the file to be imported
ImportEPUB::ImportEPUB(const QString &fullfilepath)
: Importer(fullfilepath),
m_ExtractedFolderPath(m_TempFolder.GetPath()),
m_HasSpineItems(false),
m_NCXNotInManifest(false),
m_NavResource(NULL)
{
}
// Reads and parses the file
// and returns the created Book
QSharedPointer<Book> ImportEPUB::GetBook(bool extract_metadata)
{
QList<XMLResource *> non_well_formed;
SettingsStore ss;
if (!Utility::IsFileReadable(m_FullFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot read EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
// These read the EPUB file
ExtractContainer();
QHash<QString, QString> encrypted_files = ParseEncryptionXml();
if (BookContentEncrypted(encrypted_files)) {
throw (FileEncryptedWithDrm(""));
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// These mutate the m_Book object
LocateOPF();
m_opfDir = QFileInfo(m_OPFFilePath).dir();
// These mutate the m_Book object
ReadOPF();
AddObfuscatedButUndeclaredFonts(encrypted_files);
AddNonStandardAppleXML();
LoadInfrastructureFiles();
// Check for files missing in the Manifest and create warning
QStringList notInManifest;
foreach(QString file_path, m_ZipFilePaths) {
// skip mimetype and anything in META-INF and the opf itself
if (file_path == "mimetype") continue;
if (file_path.startsWith("META-INF")) continue;
if (m_OPFFilePath.contains(file_path)) continue;
if (!m_ManifestFilePaths.contains(file_path)) {
notInManifest << file_path;
}
}
if (!notInManifest.isEmpty()) {
Utility::DisplayStdWarningDialog(tr("Files exist in epub that are not listed in the manifest, they will be ignored"), notInManifest.join("\n"));
}
const QHash<QString, QString> updates = LoadFolderStructure();
const QList<Resource *> resources = m_Book->GetFolderKeeper()->GetResourceList();
// We're going to check all html files until we find one that isn't well formed then we'll prompt
// the user if they want to auto fix or not.
//
// If we have non-well formed content and they shouldn't be auto fixed we'll pass that on to
// the universal update function so it knows to skip them. Otherwise we won't include them and
// let it modify the file.
for (int i=0; i<resources.count(); ++i) {
if (resources.at(i)->Type() == Resource::HTMLResourceType) {
HTMLResource *hresource = dynamic_cast<HTMLResource *>(resources.at(i));
if (!hresource) {
continue;
}
// Load the content into the HTMLResource so we can perform a well formed check.
try {
hresource->SetText(HTMLEncodingResolver::ReadHTMLFile(hresource->GetFullPath()));
} catch (...) {
if (ss.cleanOn() & CLEANON_OPEN) {
non_well_formed << hresource;
continue;
}
}
if (ss.cleanOn() & CLEANON_OPEN) {
if (!XhtmlDoc::IsDataWellFormed(hresource->GetText(),hresource->GetEpubVersion())) {
non_well_formed << hresource;
}
}
}
}
if (!non_well_formed.isEmpty()) {
QApplication::restoreOverrideCursor();
if (QMessageBox::Yes == QMessageBox::warning(QApplication::activeWindow(),
tr("Sigil"),
tr("This EPUB has HTML files that are not well formed. "
"Sigil can attempt to automatically fix these files, although this "
"can result in data loss.\n\n"
"Do you want to automatically fix the files?"),
QMessageBox::Yes|QMessageBox::No)
) {
non_well_formed.clear();
}
QApplication::setOverrideCursor(Qt::WaitCursor);
}
const QStringList load_errors = UniversalUpdates::PerformUniversalUpdates(false, resources, updates, non_well_formed);
Q_FOREACH (QString err, load_errors) {
AddLoadWarning(QString("%1").arg(err));
}
ProcessFontFiles(resources, updates, encrypted_files);
if (m_PackageVersion.startsWith('3')) {
HTMLResource * nav_resource = NULL;
if (m_NavResource) {
if (m_NavResource->Type() == Resource::HTMLResourceType) {
nav_resource = dynamic_cast<HTMLResource*>(m_NavResource);
}
}
if (!nav_resource) {
// we need to create a nav file here because one was not found
// it will automatically be added to the content.opf
nav_resource = m_Book->CreateEmptyNavFile(true);
Resource * res = dynamic_cast<Resource *>(nav_resource);
m_Book->GetOPF()->SetItemRefLinear(res, false);
}
m_Book->GetOPF()->SetNavResource(nav_resource);
}
if (m_NCXNotInManifest) {
// We manually created an NCX file because there wasn't one in the manifest.
// Need to create a new manifest id for it.
m_NCXId = m_Book->GetOPF()->AddNCXItem(m_NCXFilePath);
}
// Ensure that our spine has a <spine toc="ncx"> element on it now in case it was missing.
m_Book->GetOPF()->UpdateNCXOnSpine(m_NCXId);
// Make sure the <item> for the NCX in the manifest reflects correct href path
m_Book->GetOPF()->UpdateNCXLocationInManifest(m_Book->GetNCX());
// If spine was not present or did not contain any items, recreate the OPF from scratch
// preserving any important metadata elements and making a new reading order.
if (!m_HasSpineItems) {
QList<MetaEntry> originalMetadata = m_Book->GetOPF()->GetDCMetadata();
m_Book->GetOPF()->AutoFixWellFormedErrors();
if (extract_metadata) {
m_Book->GetOPF()->SetDCMetadata(originalMetadata);
}
AddLoadWarning(QObject::tr("The OPF file does not contain a valid spine.") % "\n" %
QObject::tr("Sigil has created a new one for you."));
}
// If we have modified the book to add spine attribute, manifest item or NCX mark as changed.
m_Book->SetModified(GetLoadWarnings().count() > 0);
QApplication::restoreOverrideCursor();
return m_Book;
}
QHash<QString, QString> ImportEPUB::ParseEncryptionXml()
{
QString encrpytion_xml_path = m_ExtractedFolderPath + "/META-INF/encryption.xml";
if (!QFileInfo(encrpytion_xml_path).exists()) {
return QHash<QString, QString>();
}
QXmlStreamReader encryption(Utility::ReadUnicodeTextFile(encrpytion_xml_path));
QHash<QString, QString> encrypted_files;
QString encryption_algo;
QString uri;
while (!encryption.atEnd()) {
encryption.readNext();
if (encryption.isStartElement()) {
if (encryption.name() == "EncryptionMethod") {
encryption_algo = encryption.attributes().value("", "Algorithm").toString();
} else if (encryption.name() == "CipherReference") {
uri = Utility::URLDecodePath(encryption.attributes().value("", "URI").toString());
encrypted_files[ uri ] = encryption_algo;
}
}
}
if (encryption.hasError()) {
const QString error = QString(QObject::tr("Error parsing encryption xml.\nLine: %1 Column %2 - %3"))
.arg(encryption.lineNumber())
.arg(encryption.columnNumber())
.arg(encryption.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
return encrypted_files;
}
bool ImportEPUB::BookContentEncrypted(const QHash<QString, QString> &encrypted_files)
{
foreach(QString algorithm, encrypted_files.values()) {
if (algorithm != ADOBE_FONT_ALGO_ID &&
algorithm != IDPF_FONT_ALGO_ID) {
return true;
}
}
return false;
}
// This is basically a workaround for old versions of InDesign not listing the fonts it
// embedded in the OPF manifest, even though the specs say it has to.
// It does list them in the encryption.xml, so we use that.
void ImportEPUB::AddObfuscatedButUndeclaredFonts(const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
foreach(QString filepath, encrypted_files.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(filepath).suffix().toLower())) {
continue;
}
// Only add the path to the manifest if it is not already included.
QMapIterator<QString, QString> valueSearch(m_Files);
if (!valueSearch.findNext(opf_dir.relativeFilePath(filepath))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(filepath);
}
}
}
// Another workaround for non-standard Apple files
// At present it only handles com.apple.ibooks.display-options.xml, but any
// further iBooks aberrations should be handled here as well.
void ImportEPUB::AddNonStandardAppleXML()
{
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QStringList aberrant_Apple_filenames;
aberrant_Apple_filenames.append(m_ExtractedFolderPath + "/META-INF/com.apple.ibooks.display-options.xml");
for (int i = 0; i < aberrant_Apple_filenames.size(); ++i) {
if (QFile::exists(aberrant_Apple_filenames.at(i))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(aberrant_Apple_filenames.at(i));
}
}
}
// Each resource can provide us with its new path. encrypted_files provides
// a mapping from old resource paths to the obfuscation algorithms.
// So we use the updates hash which provides a mapping from old paths to new
// paths to match the resources to their algorithms.
void ImportEPUB::ProcessFontFiles(const QList<Resource *> &resources,
const QHash<QString, QString> &updates,
const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QList<FontResource *> font_resources = m_Book->GetFolderKeeper()->GetResourceTypeList<FontResource>();
if (font_resources.empty()) {
return;
}
QHash<QString, QString> new_font_paths_to_algorithms;
foreach(QString old_update_path, updates.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(old_update_path).suffix().toLower())) {
continue;
}
QString new_update_path = updates[ old_update_path ];
foreach(QString old_encrypted_path, encrypted_files.keys()) {
if (old_update_path == old_encrypted_path) {
new_font_paths_to_algorithms[ new_update_path ] = encrypted_files[ old_encrypted_path ];
}
}
}
foreach(FontResource * font_resource, font_resources) {
QString match_path = "../" + font_resource->GetRelativePathToOEBPS();
QString algorithm = new_font_paths_to_algorithms.value(match_path);
if (algorithm.isEmpty()) {
continue;
}
font_resource->SetObfuscationAlgorithm(algorithm);
// Actually we are de-obfuscating, but the inverse operations of the obfuscation methods
// are the obfuscation methods themselves. For the math oriented, the obfuscation methods
// are involutary [ f( f( x ) ) = x ].
if (algorithm == ADOBE_FONT_ALGO_ID) {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UuidIdentifierValue);
} else {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UniqueIdentifierValue);
}
}
}
void ImportEPUB::ExtractContainer()
{
int res = 0;
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData());
#endif
if (zfile == NULL) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot unzip EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// for security reasons we need the file path to always be inside the
// target folder and not outside, so we will remove all relative upward
// paths segments ".." from the file path before prepending the target
// folder to create the final target path
qfile_name = qfile_name.replace("../","");
cp437_file_name = cp437_file_name.replace("../","");
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
QDir dir(m_ExtractedFolderPath);
// Full file path in the temporary directory.
QString file_path = m_ExtractedFolderPath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
// add it to the list of files found inside the zip
if (cp437_file_name.isEmpty()) {
m_ZipFilePaths << qfile_name;
} else {
m_ZipFilePaths << cp437_file_name;
}
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = m_ExtractedFolderPath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot open EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
unzClose(zfile);
}
void ImportEPUB::LocateOPF()
{
QString fullpath = m_ExtractedFolderPath + "/META-INF/container.xml";
QXmlStreamReader container;
try {
container.addData(Utility::ReadUnicodeTextFile(fullpath));
} catch (CannotOpenFile) {
// Find the first OPF file.
QString OPFfile;
QDirIterator files(m_ExtractedFolderPath, QStringList() << "*.opf", QDir::NoFilter, QDirIterator::Subdirectories);
while (files.hasNext()) {
OPFfile = QDir(m_ExtractedFolderPath).relativeFilePath(files.next());
break;
}
if (OPFfile.isEmpty()) {
std::string msg = fullpath.toStdString() + ": " + tr("Epub has missing or improperly specified OPF.").toStdString();
throw (CannotOpenFile(msg));
}
// Create a default container.xml.
QDir folder(m_ExtractedFolderPath);
folder.mkdir("META-INF");
Utility::WriteUnicodeTextFile(CONTAINER_XML.arg(OPFfile), fullpath);
container.addData(Utility::ReadUnicodeTextFile(fullpath));
}
while (!container.atEnd()) {
container.readNext();
if (container.isStartElement() &&
container.name() == "rootfile"
) {
if (container.attributes().hasAttribute("media-type") &&
container.attributes().value("", "media-type") == OEBPS_MIMETYPE
) {
m_OPFFilePath = m_ExtractedFolderPath + "/" + container.attributes().value("", "full-path").toString();
// As per OCF spec, the first rootfile element
// with the OEBPS mimetype is considered the "main" one.
break;
}
}
}
if (container.hasError()) {
const QString error = QString(
QObject::tr("Unable to parse container.xml file.\nLine: %1 Column %2 - %3"))
.arg(container.lineNumber())
.arg(container.columnNumber())
.arg(container.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
if (m_OPFFilePath.isEmpty() || !QFile::exists(m_OPFFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("No appropriate OPF file found")).toStdString()));
}
}
void ImportEPUB::ReadOPF()
{
QString opf_text = CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE);
QXmlStreamReader opf_reader(opf_text);
QString ncx_id_on_spine;
while (!opf_reader.atEnd()) {
opf_reader.readNext();
if (!opf_reader.isStartElement()) {
continue;
}
if (opf_reader.name() == "package") {
m_UniqueIdentifierId = opf_reader.attributes().value("", "unique-identifier").toString();
m_PackageVersion = opf_reader.attributes().value("", "version").toString();
if (m_PackageVersion == "1.0") m_PackageVersion = "2.0";
}
else if (opf_reader.name() == "identifier") {
ReadIdentifierElement(&opf_reader);
}
// epub3 look for linked metadata resources that are included inside the epub
// but that are not and must not be included in the manifest
else if (opf_reader.name() == "link") {
ReadMetadataLinkElement(&opf_reader);
}
// Get the list of content files that
// make up the publication
else if (opf_reader.name() == "item") {
ReadManifestItemElement(&opf_reader);
}
// We read this just to get the NCX id
else if (opf_reader.name() == "spine") {
ncx_id_on_spine = opf_reader.attributes().value("", "toc").toString();
}
else if (opf_reader.name() == "itemref") {
m_HasSpineItems = true;
}
}
if (opf_reader.hasError()) {
const QString error = QString(QObject::tr("Unable to read OPF file.\nLine: %1 Column %2 - %3"))
.arg(opf_reader.lineNumber())
.arg(opf_reader.columnNumber())
.arg(opf_reader.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
// Ensure we have an NCX available
LocateOrCreateNCX(ncx_id_on_spine);
}
void ImportEPUB::ReadIdentifierElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString scheme = opf_reader->attributes().value("", "scheme").toString();
QString value = opf_reader->readElementText();
if (id == m_UniqueIdentifierId) {
m_UniqueIdentifierValue = value;
}
if (m_UuidIdentifierValue.isEmpty() &&
(value.contains("urn:uuid:") || scheme.toLower() == "uuid")) {
m_UuidIdentifierValue = value;
}
}
void ImportEPUB::ReadMetadataLinkElement(QXmlStreamReader *opf_reader)
{
QString relation = opf_reader->attributes().value("", "rel").toString();
QString mtype = opf_reader->attributes().value("", "media-type").toString();
QString props = opf_reader->attributes().value("", "properties").toString();
QString href = opf_reader->attributes().value("", "href").toString();
if (!href.isEmpty()) {
QUrl url = QUrl(href);
if (url.isRelative()) {
// we have a local unmanifested metadata file to handle
// attempt to map deprecated record types into proper media-types
if (relation == "marc21xml-record") {
mtype = "application/marcxml+xml";
}
else if (relation == "mods-record") {
mtype = "application/mods+xml";
}
else if (relation == "onix-record") {
mtype = "application/xml;onix";
}
else if (relation == "xmp-record") {
mtype = "application/xml;xmp";
}
else if (relation == "record") {
if (props == "onix") mtype = "application/xml;onix";
if (props == "xmp") mtype = "application/xml;xmp";
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QString path = opf_dir.absolutePath() + "/" + url.path();
if (QFile::exists(path)) {
QString id = Utility::CreateUUID();
m_Files[ id ] = opf_dir.relativeFilePath(path);
m_FileMimetypes[ id ] = mtype;
}
}
}
}
void ImportEPUB::ReadManifestItemElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString href = opf_reader->attributes().value("", "href").toString();
QString type = opf_reader->attributes().value("", "media-type").toString();
QString properties = opf_reader->attributes().value("", "properties").toString();
// Paths are percent encoded in the OPF, we use "normal" paths internally.
href = Utility::URLDecodePath(href);
QString extension = QFileInfo(href).suffix().toLower();
// find the epub root relative file path from the opf location and the item href
QString file_path = m_opfDir.absolutePath() + "/" + href;
file_path = file_path.remove(0, m_ExtractedFolderPath.length() + 1);
if (type != NCX_MIMETYPE && extension != NCX_EXTENSION) {
if (!m_ManifestFilePaths.contains(file_path)) {
if (m_Files.contains(id)) {
// We have an error situation with a duplicate id in the epub.
// We must warn the user, but attempt to use another id so the epub can still be loaded.
QString base_id = QFileInfo(href).fileName();
QString new_id(base_id);
int duplicate_index = 0;
while (m_Files.contains(new_id)) {
duplicate_index++;
new_id = QString("%1%2").arg(base_id).arg(duplicate_index);
}
const QString load_warning = QObject::tr("The OPF manifest contains duplicate ids for: %1").arg(id) +
" - " + QObject::tr("A temporary id has been assigned to load this EPUB. You should edit your OPF file to remove the duplication.");
id = new_id;
AddLoadWarning(load_warning);
}
m_Files[ id ] = href;
m_FileMimetypes[ id ] = type;
m_ManifestFilePaths << file_path;
// store information about any nav document
if (properties.contains("nav")) {
m_NavId = id;
m_NavHref = href;
}
}
} else {
m_NcxCandidates[ id ] = href;
m_ManifestFilePaths << file_path;
}
}
void ImportEPUB::LocateOrCreateNCX(const QString &ncx_id_on_spine)
{
QString load_warning;
QString ncx_href = "not_found";
m_NCXId = ncx_id_on_spine;
// Handle various failure conditions, such as:
// - ncx not specified in the spine (search for a matching manifest item by extension)
// - ncx specified in spine, but no matching manifest item entry (create a new one)
// - ncx file not physically present (create a new one)
// - ncx not in spine or manifest item (create a new one)
if (!m_NCXId.isEmpty()) {
ncx_href = m_NcxCandidates[ m_NCXId ];
} else {
// Search for the ncx in the manifest by looking for files with
// a .ncx extension.
QHashIterator<QString, QString> ncxSearch(m_NcxCandidates);
while (ncxSearch.hasNext()) {
ncxSearch.next();
if (QFileInfo(ncxSearch.value()).suffix().toLower() == NCX_EXTENSION) {
m_NCXId = ncxSearch.key();
load_warning = QObject::tr("The OPF file did not identify the NCX file correctly.") + "\n" +
" - " + QObject::tr("Sigil has used the following file as the NCX:") +
QString(" %1").arg(m_NcxCandidates[ m_NCXId ]);
ncx_href = m_NcxCandidates[ m_NCXId ];
break;
}
}
}
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % ncx_href;
if (ncx_href.isEmpty() || !QFile::exists(m_NCXFilePath)) {
m_NCXNotInManifest = m_NCXId.isEmpty() || ncx_href.isEmpty();
m_NCXId.clear();
// Things are really bad and no .ncx file was found in the manifest or
// the file does not physically exist. We need to create a new one.
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % NCX_FILE_NAME;
// Create a new file for the NCX.
NCXResource ncx_resource(m_ExtractedFolderPath, m_NCXFilePath, m_Book->GetFolderKeeper());
// We are relying on an identifier being set from the metadata.
// It might not have one if the book does not have the urn:uuid: format.
if (!m_UuidIdentifierValue.isEmpty()) {
ncx_resource.SetMainID(m_UuidIdentifierValue);
}
ncx_resource.SaveToDisk();
if (m_PackageVersion.startsWith('3')) {
load_warning = QObject::tr("Sigil has created a template NCX") + "\n" +
QObject::tr("to support epub2 backwards compatibility.");
} else {
if (ncx_href.isEmpty()) {
load_warning = QObject::tr("The OPF file does not contain an NCX file.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
} else {
load_warning = QObject::tr("The NCX file is not present in this EPUB.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
}
}
}
if (!load_warning.isEmpty()) {
AddLoadWarning(load_warning);
}
}
void ImportEPUB::LoadInfrastructureFiles()
{
// always SetEpubVersion before SetText in OPF as SetText will validate with it
m_Book->GetOPF()->SetEpubVersion(m_PackageVersion);
m_Book->GetOPF()->SetText(CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE));
QString OPFBookRelPath = m_OPFFilePath;
OPFBookRelPath = OPFBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetOPF()->SetCurrentBookRelPath(OPFBookRelPath);
m_Book->GetNCX()->SetText(CleanSource::ProcessXML(Utility::ReadUnicodeTextFile(m_NCXFilePath),"application/x-dtbncx+xml"));
m_Book->GetNCX()->SetEpubVersion(m_PackageVersion);
QString NCXBookRelPath = m_NCXFilePath;
NCXBookRelPath = NCXBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetNCX()->SetCurrentBookRelPath(NCXBookRelPath);
}
QHash<QString, QString> ImportEPUB::LoadFolderStructure()
{
QList<QString> keys = m_Files.keys();
int num_files = keys.count();
QFutureSynchronizer<std::tuple<QString, QString>> sync;
for (int i = 0; i < num_files; ++i) {
QString id = keys.at(i);
sync.addFuture(QtConcurrent::run(
this,
&ImportEPUB::LoadOneFile,
m_Files.value(id),
m_FileMimetypes.value(id)));
}
sync.waitForFinished();
QList<QFuture<std::tuple<QString, QString>>> futures = sync.futures();
int num_futures = futures.count();
QHash<QString, QString> updates;
for (int i = 0; i < num_futures; ++i) {
std::tuple<QString, QString> result = futures.at(i).result();
updates[std::get<0>(result)] = std::get<1>(result);
}
updates.remove(UPDATE_ERROR_STRING);
return updates;
}
std::tuple<QString, QString> ImportEPUB::LoadOneFile(const QString &path, const QString &mimetype)
{
QString fullfilepath = QDir::cleanPath(QFileInfo(m_OPFFilePath).absolutePath() + "/" + path);
QString currentpath = fullfilepath;
currentpath = currentpath.remove(0,m_ExtractedFolderPath.length()+1);
try {
Resource *resource = m_Book->GetFolderKeeper()->AddContentFileToFolder(fullfilepath, false, mimetype);
if (path == m_NavHref) {
m_NavResource = resource;
}
resource->SetCurrentBookRelPath(currentpath);
QString newpath = "../" + resource->GetRelativePathToOEBPS();
return std::make_tuple(currentpath, newpath);
} catch (FileDoesNotExist) {
return std::make_tuple(UPDATE_ERROR_STRING, UPDATE_ERROR_STRING);
}
}
QString ImportEPUB::PrepareOPFForReading(const QString &source)
{
QString source_copy(source);
QString prefix = source_copy.left(XML_DECLARATION_SEARCH_PREFIX_SIZE);
QRegularExpression version(VERSION_ATTRIBUTE);
QRegularExpressionMatch mo = version.match(prefix);
if (mo.hasMatch()) {
// MASSIVE hack for XML 1.1 "support";
// this is only for people who specify
// XML 1.1 when they actually only use XML 1.0
source_copy.replace(mo.capturedStart(1), mo.capturedLength(1), "1.0");
}
return source_copy;
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_975_0 |
crossvul-cpp_data_bad_2420_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <zip.h>
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/preg.h"
#include "hphp/runtime/base/stream-wrapper-registry.h"
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/ext/pcre/ext_pcre.h"
#include "hphp/runtime/ext/std/ext_std_file.h"
namespace HPHP {
static String to_full_path(const String& filename) {
if (filename.charAt(0) == '/') {
return filename;
}
return f_getcwd().toString() + String::FromChar('/') + filename;
}
// A wrapper for `zip_open` that prepares a full path
// file name to consider current working directory.
static zip* _zip_open(const String& filename, int _flags, int* zep) {
return zip_open(to_full_path(filename).c_str(), _flags, zep);
}
struct ZipStream : File {
DECLARE_RESOURCE_ALLOCATION(ZipStream);
ZipStream(zip* z, const String& name) : m_zipFile(nullptr) {
if (name.empty()) {
return;
}
struct zip_stat zipStat;
if (zip_stat(z, name.c_str(), 0, &zipStat) != 0) {
return;
}
m_zipFile = zip_fopen(z, name.c_str(), 0);
}
virtual ~ZipStream() { close(); }
bool open(const String&, const String&) override { return false; }
bool close() override {
bool noError = true;
if (!eof()) {
if (zip_fclose(m_zipFile) != 0) {
noError = false;
}
m_zipFile = nullptr;
}
return noError;
}
int64_t readImpl(char *buffer, int64_t length) override {
auto n = zip_fread(m_zipFile, buffer, length);
if (n <= 0) {
if (n == -1) {
raise_warning("Zip stream error");
n = 0;
}
close();
}
return n;
}
int64_t writeImpl(const char *buffer, int64_t length) override { return 0; }
bool eof() override { return m_zipFile == nullptr; }
private:
zip_file* m_zipFile;
};
void ZipStream::sweep() {
close();
File::sweep();
}
struct ZipStreamWrapper : Stream::Wrapper {
virtual req::ptr<File> open(const String& filename,
const String& mode,
int options,
const req::ptr<StreamContext>& context) {
std::string url(filename.c_str());
auto pound = url.find('#');
if (pound == std::string::npos) {
return nullptr;
}
// 6 is the position after zip://
auto path = url.substr(6, pound - 6);
auto file = url.substr(pound + 1);
if (path.empty() || file.empty()) {
return nullptr;
}
int err;
auto z = _zip_open(path, 0, &err);
if (z == nullptr) {
return nullptr;
}
return req::make<ZipStream>(z, file);
}
};
struct ZipEntry : SweepableResourceData {
DECLARE_RESOURCE_ALLOCATION(ZipEntry);
CLASSNAME_IS("ZipEntry");
// overriding ResourceData
const String& o_getClassNameHook() const override { return classnameof(); }
ZipEntry(zip* z, int index) : m_zipFile(nullptr) {
if (zip_stat_index(z, index, 0, &m_zipStat) == 0) {
m_zipFile = zip_fopen_index(z, index, 0);
}
}
~ZipEntry() {
close();
}
bool close() {
bool noError = true;
if (isValid()) {
if (zip_fclose(m_zipFile) != 0) {
noError = false;
}
m_zipFile = nullptr;
}
return noError;
}
bool isValid() {
return m_zipFile != nullptr;
}
String read(int64_t len) {
StringBuffer sb(len);
auto buf = sb.appendCursor(len);
auto n = zip_fread(m_zipFile, buf, len);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string();
}
uint64_t getCompressedSize() {
return m_zipStat.comp_size;
}
String getCompressionMethod() {
switch (m_zipStat.comp_method) {
case 0:
return "stored";
case 1:
return "shrunk";
case 2:
case 3:
case 4:
case 5:
return "reduced";
case 6:
return "imploded";
case 7:
return "tokenized";
case 8:
return "deflated";
case 9:
return "deflatedX";
case 10:
return "implodedX";
default:
return false;
}
}
String getName() {
return m_zipStat.name;
}
uint64_t getSize() {
return m_zipStat.size;
}
private:
struct zip_stat m_zipStat;
zip_file* m_zipFile;
};
IMPLEMENT_RESOURCE_ALLOCATION(ZipEntry);
struct ZipDirectory : SweepableResourceData {
DECLARE_RESOURCE_ALLOCATION(ZipDirectory);
CLASSNAME_IS("ZipDirectory");
// overriding ResourceData
const String& o_getClassNameHook() const override { return classnameof(); }
explicit ZipDirectory(zip *z) : m_zip(z),
m_numFiles(zip_get_num_files(z)),
m_curIndex(0) {}
~ZipDirectory() { close(); }
bool close() {
bool noError = true;
if (isValid()) {
if (zip_close(m_zip) != 0) {
zip_discard(m_zip);
noError = false;
}
m_zip = nullptr;
}
return noError;
}
bool isValid() const {
return m_zip != nullptr;
}
Variant nextFile() {
if (m_curIndex >= m_numFiles) {
return false;
}
auto zipEntry = req::make<ZipEntry>(m_zip, m_curIndex);
if (!zipEntry->isValid()) {
return false;
}
++m_curIndex;
return Variant(std::move(zipEntry));
}
zip* getZip() {
return m_zip;
}
private:
zip* m_zip;
int m_numFiles;
int m_curIndex;
};
IMPLEMENT_RESOURCE_ALLOCATION(ZipDirectory);
const StaticString s_ZipArchive("ZipArchive");
template<class T>
ALWAYS_INLINE
static req::ptr<T> getResource(ObjectData* obj, const char* varName) {
auto var = obj->o_get(varName, true, s_ZipArchive);
if (var.getType() == KindOfNull) {
return nullptr;
}
return cast<T>(var);
}
ALWAYS_INLINE
static Variant setVariable(const Object& obj, const char* varName, const Variant& varValue) {
return obj->o_set(varName, varValue, s_ZipArchive);
}
#define FAIL_IF_EMPTY_STRING(func, str) \
if (str.empty()) { \
raise_warning(#func "(): Empty string as source"); \
return false; \
}
#define FAIL_IF_EMPTY_STRING_ZIPARCHIVE(func, str) \
if (str.empty()) { \
raise_warning("ZipArchive::" #func "(): Empty string as source"); \
return false; \
}
#define FAIL_IF_INVALID_INDEX(index) \
if (index < 0) { \
return false; \
}
#define FAIL_IF_INVALID_PTR(ptr) \
if (ptr == nullptr) { \
return false; \
}
#define FAIL_IF_INVALID_ZIPARCHIVE(func, res) \
if (res == nullptr || !res->isValid()) { \
raise_warning("ZipArchive::" #func \
"(): Invalid or uninitialized Zip object"); \
return false; \
}
#define FAIL_IF_INVALID_ZIPDIRECTORY(func, res) \
if (!res->isValid()) { \
raise_warning(#func "(): %d is not a valid " \
"Zip Directory resource", res->getId()); \
return false; \
}
#define FAIL_IF_INVALID_ZIPENTRY(func, res) \
if (!res->isValid()) { \
raise_warning(#func "(): %d is not a valid Zip Entry resource", \
res->getId()); \
return false; \
}
//////////////////////////////////////////////////////////////////////////////
// class ZipArchive
static Variant HHVM_METHOD(ZipArchive, getProperty, int64_t property) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
if (zipDir == nullptr) {
switch (property) {
case 0:
case 1:
case 2:
return 0;
case 3:
case 4:
return empty_string_variant();
default:
return init_null();
}
}
switch (property) {
case 0:
case 1:
{
int zep, sys;
zip_error_get(zipDir->getZip(), &zep, &sys);
if (property == 0) {
return zep;
}
return sys;
}
case 2:
{
return zip_get_num_files(zipDir->getZip());
}
case 3:
{
return this_->o_get("filename", true, s_ZipArchive).asCStrRef();
}
case 4:
{
int len;
auto comment = zip_get_archive_comment(zipDir->getZip(), &len, 0);
if (comment == nullptr) {
return empty_string_variant();
}
return String(comment, len, CopyString);
}
default:
return init_null();
}
}
static bool HHVM_METHOD(ZipArchive, addEmptyDir, const String& dirname) {
if (dirname.empty()) {
return false;
}
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addEmptyDir, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addEmptyDir, dirname);
std::string dirStr(dirname.c_str());
if (dirStr[dirStr.length() - 1] != '/') {
dirStr.push_back('/');
}
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), dirStr.c_str(), 0, &zipStat) != -1) {
return false;
}
if (zip_add_dir(zipDir->getZip(), dirStr.c_str()) == -1) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool addFile(zip* zipStruct, const char* source, const char* dest,
int64_t start = 0, int64_t length = 0) {
if (!HHVM_FN(is_file)(source)) {
return false;
}
auto zipSource = zip_source_file(zipStruct, source, start, length);
FAIL_IF_INVALID_PTR(zipSource);
auto index = zip_name_locate(zipStruct, dest, 0);
if (index < 0) {
if (zip_add(zipStruct, dest, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
} else {
if (zip_replace(zipStruct, index, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
}
zip_error_clear(zipStruct);
return true;
}
static bool HHVM_METHOD(ZipArchive, addFile, const String& filename,
const String& localname, int64_t start,
int64_t length) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addFile, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addFile, filename);
return addFile(zipDir->getZip(), filename.c_str(),
localname.empty() ? filename.c_str() : localname.c_str(),
start, length);
}
static bool HHVM_METHOD(ZipArchive, addFromString, const String& localname,
const String& contents) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addFromString, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addFromString, localname);
auto data = malloc(contents.length());
FAIL_IF_INVALID_PTR(data);
memcpy(data, contents.c_str(), contents.length());
auto zipSource = zip_source_buffer(zipDir->getZip(), data, contents.length(),
1); // this will free data ptr
if (zipSource == nullptr) {
free(data);
return false;
}
auto index = zip_name_locate(zipDir->getZip(), localname.c_str(), 0);
if (index < 0) {
if (zip_add(zipDir->getZip(), localname.c_str(), zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
} else {
if (zip_replace(zipDir->getZip(), index, zipSource) == -1) {
zip_source_free(zipSource);
return false;
}
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool addPattern(zip* zipStruct, const String& pattern, const Array& options,
std::string path, int64_t flags, bool glob) {
std::string removePath;
if (options->exists(String("remove_path"))) {
auto var = options->get(String("remove_path"));
if (var.isString()) {
removePath.append(var.asCStrRef().c_str());
}
}
bool removeAllPath = false;
if (options->exists(String("remove_all_path"))) {
auto var = options->get(String("remove_all_path"));
if (var.isBoolean()) {
removeAllPath = var.asBooleanVal();
}
}
std::string addPath;
if (options->exists(String("add_path"))) {
auto var = options->get(String("add_path"));
if (var.isString()) {
addPath.append(var.asCStrRef().c_str());
}
}
Array files;
if (glob) {
auto match = HHVM_FN(glob)(pattern, flags);
if (match.isArray()) {
files = match.toArrRef();
} else {
return false;
}
} else {
if (path[path.size() - 1] != '/') {
path.push_back('/');
}
auto allFiles = HHVM_FN(scandir)(path);
if (allFiles.isArray()) {
files = allFiles.toArrRef();
} else {
return false;
}
}
std::string dest;
auto pathLen = path.size();
for (ArrayIter it(files); it; ++it) {
auto var = it.second();
if (!var.isString()) {
return false;
}
auto source = var.asCStrRef();
if (HHVM_FN(is_dir)(source)) {
continue;
}
if (!glob) {
auto var = preg_match(pattern, source);
if (var.isInteger()) {
if (var.asInt64Val() == 0) {
continue;
}
} else {
return false;
}
}
dest.resize(0);
dest.append(source.c_str());
if (removeAllPath) {
auto index = dest.rfind('/');
if (index != std::string::npos) {
dest.erase(0, index + 1);
}
} else if (!removePath.empty()) {
auto index = dest.find(removePath);
if (index == 0) {
dest.erase(0, removePath.size());
}
}
if (!addPath.empty()) {
dest.insert(0, addPath);
}
path.resize(pathLen);
path.append(source.c_str());
if (!addFile(zipStruct, path.c_str(), dest.c_str())) {
return false;
}
}
zip_error_clear(zipStruct);
return true;
}
static bool HHVM_METHOD(ZipArchive, addGlob, const String& pattern,
int64_t flags, const Array& options) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addGlob, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addGlob, pattern);
return addPattern(zipDir->getZip(), pattern, options, "", flags, true);
}
static bool HHVM_METHOD(ZipArchive, addPattern, const String& pattern,
const String& path, const Array& options) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(addPattern, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addPattern, pattern);
return addPattern(zipDir->getZip(), pattern, options, path.c_str(), 0, false);
}
static bool HHVM_METHOD(ZipArchive, close) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(close, zipDir);
bool ret = zipDir->close();
setVariable(Object{this_}, "zipDir", null_resource);
return ret;
}
static bool HHVM_METHOD(ZipArchive, deleteIndex, int64_t index) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(deleteIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (zip_delete(zipDir->getZip(), index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, deleteName, const String& name) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(deleteName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(deleteName, name);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), 0, &zipStat) != 0) {
return false;
}
if (zip_delete(zipDir->getZip(), zipStat.index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool extractFileTo(zip* zip, const std::string &file, std::string& to,
char* buf, size_t len) {
auto sep = file.rfind('/');
if (sep != std::string::npos) {
auto path = to + file.substr(0, sep);
if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {
return false;
}
if (sep == file.length() - 1) {
return true;
}
}
to.append(file);
struct zip_stat zipStat;
if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {
return false;
}
auto zipFile = zip_fopen_index(zip, zipStat.index, 0);
FAIL_IF_INVALID_PTR(zipFile);
auto outFile = fopen(to.c_str(), "wb");
if (outFile == nullptr) {
zip_fclose(zipFile);
return false;
}
for (auto n = zip_fread(zipFile, buf, len); n != 0;
n = zip_fread(zipFile, buf, len)) {
if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {
zip_fclose(zipFile);
fclose(outFile);
remove(to.c_str());
return false;
}
}
zip_fclose(zipFile);
if (fclose(outFile) != 0) {
return false;
}
return true;
}
static bool HHVM_METHOD(ZipArchive, extractTo, const String& destination,
const Variant& entries) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(extractTo, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(extractTo, destination);
auto fileCount = zip_get_num_files(zipDir->getZip());
if (fileCount == -1) {
raise_warning("Illegal archive");
return false;
}
std::string to(destination.c_str());
if (to[to.size() - 1] != '/') {
to.push_back('/');
}
if (!HHVM_FN(is_dir)(to) && !HHVM_FN(mkdir)(to)) {
return false;
}
char buf[1024];
auto toSize = to.size();
if (entries.isString()) {
// extract only this file
if (!extractFileTo(zipDir->getZip(), entries.asCStrRef().c_str(),
to, buf, sizeof(buf))) {
return false;
}
} else if (entries.isArray() && entries.asCArrRef().size() != 0) {
// extract ones in the array
for (ArrayIter it(entries.asCArrRef()); it; ++it) {
auto var = it.second();
if (!var.isString() || !extractFileTo(zipDir->getZip(),
var.asCStrRef().c_str(),
to, buf, sizeof(buf))) {
return false;
}
to.resize(toSize);
}
} else {
// extract all files
for (decltype(fileCount) index = 0; index < fileCount; ++index) {
auto file = zip_get_name(zipDir->getZip(), index, ZIP_FL_UNCHANGED);
if (!extractFileTo(zipDir->getZip(), file, to, buf, sizeof(buf))) {
return false;
}
to.resize(toSize);
}
}
zip_error_clear(zipDir->getZip());
return true;
}
static Variant HHVM_METHOD(ZipArchive, getArchiveComment, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getArchiveComment, zipDir);
int len;
auto comment = zip_get_archive_comment(zipDir->getZip(), &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getCommentIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getCommentIndex, zipDir);
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
int len;
auto comment = zip_get_file_comment(zipDir->getZip(), index, &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getCommentName, const String& name,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getCommentName, zipDir);
if (name.empty()) {
raise_notice("ZipArchive::getCommentName(): Empty string as source");
return false;
}
int index = zip_name_locate(zipDir->getZip(), name.c_str(), 0);
if (index != 0) {
return false;
}
int len;
auto comment = zip_get_file_comment(zipDir->getZip(), index, &len, flags);
FAIL_IF_INVALID_PTR(comment);
return String(comment, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getFromIndex, int64_t index,
int64_t length, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getFromIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (length < 0) {
return empty_string_variant();
}
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
if (zipStat.size < 1) {
return empty_string_variant();
}
auto zipFile = zip_fopen_index(zipDir->getZip(), index, flags);
FAIL_IF_INVALID_PTR(zipFile);
if (length == 0) {
length = zipStat.size;
}
StringBuffer sb(length);
auto buf = sb.appendCursor(length);
auto n = zip_fread(zipFile, buf, length);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string_variant();
}
static Variant HHVM_METHOD(ZipArchive, getFromName, const String& name,
int64_t length, int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getFromName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(getFromName, name);
if (length < 0) {
return empty_string_variant();
}
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), flags, &zipStat) != 0) {
return false;
}
if (zipStat.size < 1) {
return empty_string_variant();
}
auto zipFile = zip_fopen(zipDir->getZip(), name.c_str(), flags);
FAIL_IF_INVALID_PTR(zipFile);
if (length == 0) {
length = zipStat.size;
}
StringBuffer sb(length);
auto buf = sb.appendCursor(length);
auto n = zip_fread(zipFile, buf, length);
if (n > 0) {
sb.resize(n);
return sb.detach();
}
return empty_string_variant();
}
static Variant HHVM_METHOD(ZipArchive, getNameIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getNameIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
auto name = zip_get_name(zipDir->getZip(), index, flags);
FAIL_IF_INVALID_PTR(name);
return String(name, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getStatusString) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getStatusString, zipDir);
int zep, sep, len;
zip_error_get(zipDir->getZip(), &zep, &sep);
char error_string[128];
len = zip_error_to_str(error_string, 128, zep, sep);
return String(error_string, len, CopyString);
}
static Variant HHVM_METHOD(ZipArchive, getStream, const String& name) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(getStream, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(getStream, name);
auto zipStream = req::make<ZipStream>(zipDir->getZip(), name);
if (zipStream->eof()) {
return false;
}
return Variant(std::move(zipStream));
}
static Variant HHVM_METHOD(ZipArchive, locateName, const String& name,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(locateName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(locateName, name);
auto index = zip_name_locate(zipDir->getZip(), name.c_str(), flags);
FAIL_IF_INVALID_INDEX(index);
return index;
}
static Variant HHVM_METHOD(ZipArchive, open, const String& filename,
int64_t flags) {
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(open, filename);
int err;
auto z = _zip_open(filename, flags, &err);
if (z == nullptr) {
return err;
}
auto zipDir = req::make<ZipDirectory>(z);
setVariable(Object{this_}, "zipDir", Variant(zipDir));
setVariable(Object{this_}, "filename", filename);
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, renameIndex, int64_t index,
const String& newname) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(renameIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(renameIndex, newname);
if (zip_rename(zipDir->getZip(), index, newname.c_str()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, renameName, const String& name,
const String& newname) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(renameName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(renameName, newname);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), 0, &zipStat) != 0) {
return false;
}
if (zip_rename(zipDir->getZip(), zipStat.index, newname.c_str()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, setArchiveComment, const String& comment) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(setArchiveComment, zipDir);
if (zip_set_archive_comment(zipDir->getZip(), comment.c_str(),
comment.length()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, setCommentIndex, int64_t index,
const String& comment) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(setCommentIndex, zipDir);
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, 0, &zipStat) != 0) {
return false;
}
if (zip_set_file_comment(zipDir->getZip(), index, comment.c_str(),
comment.length()) != 0 ) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, setCommentName, const String& name,
const String& comment) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(setCommentName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(setCommentName, name);
int index = zip_name_locate(zipDir->getZip(), name.c_str(), 0);
FAIL_IF_INVALID_INDEX(index);
if (zip_set_file_comment(zipDir->getZip(), index, comment.c_str(),
comment.length()) != 0 ) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
const StaticString s_name("name");
const StaticString s_index("index");
const StaticString s_crc("crc");
const StaticString s_size("size");
const StaticString s_mtime("mtime");
const StaticString s_comp_size("comp_size");
const StaticString s_comp_method("comp_method");
ALWAYS_INLINE
static Array zipStatToArray(struct zip_stat* zipStat) {
if (zipStat == nullptr) {
return Array();
}
return make_map_array(
s_name, String(zipStat->name),
s_index, VarNR(zipStat->index),
s_crc, VarNR(static_cast<int64_t>(zipStat->crc)),
s_size, VarNR(zipStat->size),
s_mtime, VarNR(zipStat->mtime),
s_comp_size, VarNR(zipStat->comp_size),
s_comp_method, VarNR(zipStat->comp_method)
);
}
static Variant HHVM_METHOD(ZipArchive, statIndex, int64_t index,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(statIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
struct zip_stat zipStat;
if (zip_stat_index(zipDir->getZip(), index, flags, &zipStat) != 0) {
return false;
}
return zipStatToArray(&zipStat);
}
static Variant HHVM_METHOD(ZipArchive, statName, const String& name,
int64_t flags) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(statName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(statName, name);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), flags, &zipStat) != 0) {
return false;
}
return zipStatToArray(&zipStat);
}
static bool HHVM_METHOD(ZipArchive, unchangeAll) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeAll, zipDir);
if (zip_unchange_all(zipDir->getZip()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, unchangeArchive) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeArchive, zipDir);
if (zip_unchange_archive(zipDir->getZip()) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, unchangeIndex, int64_t index) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeIndex, zipDir);
FAIL_IF_INVALID_INDEX(index);
if (zip_unchange(zipDir->getZip(), index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
static bool HHVM_METHOD(ZipArchive, unchangeName, const String& name) {
auto zipDir = getResource<ZipDirectory>(this_, "zipDir");
FAIL_IF_INVALID_ZIPARCHIVE(unchangeName, zipDir);
FAIL_IF_EMPTY_STRING_ZIPARCHIVE(unchangeName, name);
struct zip_stat zipStat;
if (zip_stat(zipDir->getZip(), name.c_str(), 0, &zipStat) != 0) {
return false;
}
if (zip_unchange(zipDir->getZip(), zipStat.index) != 0) {
return false;
}
zip_error_clear(zipDir->getZip());
return true;
}
//////////////////////////////////////////////////////////////////////////////
// functions
static Variant HHVM_FUNCTION(zip_close, const Resource& zip) {
auto zipDir = cast<ZipDirectory>(zip);
FAIL_IF_INVALID_ZIPDIRECTORY(zip_close, zipDir);
zipDir->close();
return init_null();
}
static bool HHVM_FUNCTION(zip_entry_close, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_close, zipEntry);
return zipEntry->close();
}
static Variant HHVM_FUNCTION(zip_entry_compressedsize, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_compressedsize, zipEntry);
return zipEntry->getCompressedSize();
}
static Variant HHVM_FUNCTION(zip_entry_compressionmethod, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_compressionmethod, zipEntry);
return zipEntry->getCompressionMethod();
}
static Variant HHVM_FUNCTION(zip_entry_filesize, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_filesize, zipEntry);
return zipEntry->getSize();
}
static Variant HHVM_FUNCTION(zip_entry_name, const Resource& zip_entry) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_name, zipEntry);
return zipEntry->getName();
}
static bool HHVM_FUNCTION(zip_entry_open, const Resource& zip, const Resource& zip_entry,
const String& mode) {
auto zipDir = cast<ZipDirectory>(zip);
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPDIRECTORY(zip_entry_open, zipDir);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_open, zipEntry);
zip_error_clear(zipDir->getZip());
return true;
}
static Variant HHVM_FUNCTION(zip_entry_read, const Resource& zip_entry,
int64_t length) {
auto zipEntry = cast<ZipEntry>(zip_entry);
FAIL_IF_INVALID_ZIPENTRY(zip_entry_read, zipEntry);
return zipEntry->read(length > 0 ? length : 1024);
}
static Variant HHVM_FUNCTION(zip_open, const String& filename) {
FAIL_IF_EMPTY_STRING(zip_open, filename);
int err;
auto z = _zip_open(filename, 0, &err);
if (z == nullptr) {
return err;
}
return Variant(req::make<ZipDirectory>(z));
}
static Variant HHVM_FUNCTION(zip_read, const Resource& zip) {
auto zipDir = cast<ZipDirectory>(zip);
FAIL_IF_INVALID_ZIPDIRECTORY(zip_read, zipDir);
return zipDir->nextFile();
}
//////////////////////////////////////////////////////////////////////////////
struct zipExtension final : Extension {
zipExtension() : Extension("zip", "1.12.4-dev") {}
void moduleInit() override {
HHVM_ME(ZipArchive, getProperty);
HHVM_ME(ZipArchive, addEmptyDir);
HHVM_ME(ZipArchive, addFile);
HHVM_ME(ZipArchive, addFromString);
HHVM_ME(ZipArchive, addGlob);
HHVM_ME(ZipArchive, addPattern);
HHVM_ME(ZipArchive, close);
HHVM_ME(ZipArchive, deleteIndex);
HHVM_ME(ZipArchive, deleteName);
HHVM_ME(ZipArchive, extractTo);
HHVM_ME(ZipArchive, getArchiveComment);
HHVM_ME(ZipArchive, getCommentIndex);
HHVM_ME(ZipArchive, getCommentName);
HHVM_ME(ZipArchive, getFromIndex);
HHVM_ME(ZipArchive, getFromName);
HHVM_ME(ZipArchive, getNameIndex);
HHVM_ME(ZipArchive, getStatusString);
HHVM_ME(ZipArchive, getStream);
HHVM_ME(ZipArchive, locateName);
HHVM_ME(ZipArchive, open);
HHVM_ME(ZipArchive, renameIndex);
HHVM_ME(ZipArchive, renameName);
HHVM_ME(ZipArchive, setArchiveComment);
HHVM_ME(ZipArchive, setCommentIndex);
HHVM_ME(ZipArchive, setCommentName);
HHVM_ME(ZipArchive, statIndex);
HHVM_ME(ZipArchive, statName);
HHVM_ME(ZipArchive, unchangeAll);
HHVM_ME(ZipArchive, unchangeArchive);
HHVM_ME(ZipArchive, unchangeIndex);
HHVM_ME(ZipArchive, unchangeName);
HHVM_RCC_INT(ZipArchive, CREATE, ZIP_CREATE);
HHVM_RCC_INT(ZipArchive, EXCL, ZIP_EXCL);
HHVM_RCC_INT(ZipArchive, CHECKCONS, ZIP_CHECKCONS);
HHVM_RCC_INT(ZipArchive, OVERWRITE, ZIP_TRUNCATE);
HHVM_RCC_INT(ZipArchive, FL_NOCASE, ZIP_FL_NOCASE);
HHVM_RCC_INT(ZipArchive, FL_NODIR, ZIP_FL_NODIR);
HHVM_RCC_INT(ZipArchive, FL_COMPRESSED, ZIP_FL_COMPRESSED);
HHVM_RCC_INT(ZipArchive, FL_UNCHANGED, ZIP_FL_UNCHANGED);
HHVM_RCC_INT(ZipArchive, FL_RECOMPRESS, ZIP_FL_RECOMPRESS);
HHVM_RCC_INT(ZipArchive, FL_ENCRYPTED, ZIP_FL_ENCRYPTED);
HHVM_RCC_INT(ZipArchive, ER_OK, ZIP_ER_OK);
HHVM_RCC_INT(ZipArchive, ER_MULTIDISK, ZIP_ER_MULTIDISK);
HHVM_RCC_INT(ZipArchive, ER_RENAME, ZIP_ER_RENAME);
HHVM_RCC_INT(ZipArchive, ER_CLOSE, ZIP_ER_CLOSE);
HHVM_RCC_INT(ZipArchive, ER_SEEK, ZIP_ER_SEEK);
HHVM_RCC_INT(ZipArchive, ER_READ, ZIP_ER_READ);
HHVM_RCC_INT(ZipArchive, ER_WRITE, ZIP_ER_WRITE);
HHVM_RCC_INT(ZipArchive, ER_CRC, ZIP_ER_CRC);
HHVM_RCC_INT(ZipArchive, ER_ZIPCLOSED, ZIP_ER_ZIPCLOSED);
HHVM_RCC_INT(ZipArchive, ER_NOENT, ZIP_ER_NOENT);
HHVM_RCC_INT(ZipArchive, ER_EXISTS, ZIP_ER_EXISTS);
HHVM_RCC_INT(ZipArchive, ER_OPEN, ZIP_ER_OPEN);
HHVM_RCC_INT(ZipArchive, ER_TMPOPEN, ZIP_ER_TMPOPEN);
HHVM_RCC_INT(ZipArchive, ER_ZLIB, ZIP_ER_ZLIB);
HHVM_RCC_INT(ZipArchive, ER_MEMORY, ZIP_ER_MEMORY);
HHVM_RCC_INT(ZipArchive, ER_CHANGED, ZIP_ER_CHANGED);
HHVM_RCC_INT(ZipArchive, ER_COMPNOTSUPP, ZIP_ER_COMPNOTSUPP);
HHVM_RCC_INT(ZipArchive, ER_EOF, ZIP_ER_EOF);
HHVM_RCC_INT(ZipArchive, ER_INVAL, ZIP_ER_INVAL);
HHVM_RCC_INT(ZipArchive, ER_NOZIP, ZIP_ER_NOZIP);
HHVM_RCC_INT(ZipArchive, ER_INTERNAL, ZIP_ER_INTERNAL);
HHVM_RCC_INT(ZipArchive, ER_INCONS, ZIP_ER_INCONS);
HHVM_RCC_INT(ZipArchive, ER_REMOVE, ZIP_ER_REMOVE);
HHVM_RCC_INT(ZipArchive, ER_DELETED, ZIP_ER_DELETED);
HHVM_RCC_INT(ZipArchive, ER_ENCRNOTSUPP, ZIP_ER_ENCRNOTSUPP);
HHVM_RCC_INT(ZipArchive, ER_RDONLY, ZIP_ER_RDONLY);
HHVM_RCC_INT(ZipArchive, ER_NOPASSWD, ZIP_ER_NOPASSWD);
HHVM_RCC_INT(ZipArchive, ER_WRONGPASSWD, ZIP_ER_WRONGPASSWD);
HHVM_RCC_INT(ZipArchive, CM_DEFAULT, ZIP_CM_DEFAULT);
HHVM_RCC_INT(ZipArchive, CM_STORE, ZIP_CM_STORE);
HHVM_RCC_INT(ZipArchive, CM_SHRINK, ZIP_CM_SHRINK);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_1, ZIP_CM_REDUCE_1);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_2, ZIP_CM_REDUCE_2);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_3, ZIP_CM_REDUCE_3);
HHVM_RCC_INT(ZipArchive, CM_REDUCE_4, ZIP_CM_REDUCE_4);
HHVM_RCC_INT(ZipArchive, CM_IMPLODE, ZIP_CM_IMPLODE);
HHVM_RCC_INT(ZipArchive, CM_DEFLATE, ZIP_CM_DEFLATE);
HHVM_RCC_INT(ZipArchive, CM_DEFLATE64, ZIP_CM_DEFLATE64);
HHVM_RCC_INT(ZipArchive, CM_PKWARE_IMPLODE, ZIP_CM_PKWARE_IMPLODE);
HHVM_RCC_INT(ZipArchive, CM_BZIP2, ZIP_CM_BZIP2);
HHVM_RCC_INT(ZipArchive, CM_LZMA, ZIP_CM_LZMA);
HHVM_RCC_INT(ZipArchive, CM_TERSE, ZIP_CM_TERSE);
HHVM_RCC_INT(ZipArchive, CM_LZ77, ZIP_CM_LZ77);
HHVM_RCC_INT(ZipArchive, CM_WAVPACK, ZIP_CM_WAVPACK);
HHVM_RCC_INT(ZipArchive, CM_PPMD, ZIP_CM_PPMD);
HHVM_FE(zip_close);
HHVM_FE(zip_entry_close);
HHVM_FE(zip_entry_compressedsize);
HHVM_FE(zip_entry_compressionmethod);
HHVM_FE(zip_entry_filesize);
HHVM_FE(zip_entry_name);
HHVM_FE(zip_entry_open);
HHVM_FE(zip_entry_read);
HHVM_FE(zip_open);
HHVM_FE(zip_read);
auto wrapper = new ZipStreamWrapper();
if (wrapper == nullptr || !Stream::registerWrapper("zip", wrapper)) {
delete wrapper;
raise_warning("Couldn't register Zip wrapper");
}
loadSystemlib();
}
} s_zip_extension;
// Uncomment for non-bundled module
//HHVM_GET_MODULE(zip);
//////////////////////////////////////////////////////////////////////////////
} // namespace HPHP
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_2420_0 |
crossvul-cpp_data_good_974_0 | /************************************************************************
**
** Copyright (C) 2019 Kevin B. Hendricks, Stratford, Ontario Canada
** Copyright (C) 2009, 2010, 2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil 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.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#ifdef _WIN32
#define NOMINMAX
#endif
#include "unzip.h"
#ifdef _WIN32
#include "iowin32.h"
#endif
#include <stdio.h>
#include <time.h>
#include <string>
#include <QApplication>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtCore/QStandardPaths>
#include <QtCore/QStringList>
#include <QtCore/QStringRef>
#include <QtCore/QTextStream>
#include <QtCore/QtGlobal>
#include <QtCore/QUrl>
#include <QtCore/QUuid>
#include <QtWidgets/QMainWindow>
#include <QTextEdit>
#include <QMessageBox>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QFile>
#include <QFileInfo>
#include "sigil_constants.h"
#include "sigil_exception.h"
#include "Misc/QCodePage437Codec.h"
#include "Misc/SettingsStore.h"
#include "Misc/SleepFunctions.h"
#ifndef MAX_PATH
// Set Max length to 256 because that's the max path size on many systems.
#define MAX_PATH 256
#endif
// This is the same read buffer size used by Java and Perl.
#define BUFF_SIZE 8192
static QCodePage437Codec *cp437 = 0;
// Subclass QMessageBox for our StdWarningDialog to make any Details Resizable
class SigilMessageBox: public QMessageBox
{
public:
SigilMessageBox(QWidget* parent) : QMessageBox(parent)
{
setSizeGripEnabled(true);
}
private:
virtual void resizeEvent(QResizeEvent * e) {
QMessageBox::resizeEvent(e);
setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
if (QWidget *textEdit = findChild<QTextEdit *>()) {
textEdit->setMaximumHeight(QWIDGETSIZE_MAX);
}
}
};
#include "Misc/Utility.h"
// Define the user preferences location to be used
QString Utility::DefinePrefsDir()
{
// If the SIGIL_PREFS_DIR environment variable override exists; use it.
// It's up to the user to provide a directory they have permission to write to.
if (!SIGIL_PREFS_DIR.isEmpty()) {
return SIGIL_PREFS_DIR;
} else {
return QStandardPaths::writableLocation(QStandardPaths::DataLocation);
}
}
#if !defined(Q_OS_WIN32) && !defined(Q_OS_MAC)
// Return correct path(s) for Linux hunspell dictionaries
QStringList Utility::LinuxHunspellDictionaryDirs()
{
QStringList paths;
// prefer the directory specified by the env var SIGIL_DICTIONARIES above all else.
if (!hunspell_dicts_override.isEmpty()) {
// Handle multiple colon-delimited paths
foreach (QString s, hunspell_dicts_override.split(":")) {
paths << s.trimmed();
}
}
// else use the env var runtime overridden 'share/sigil/hunspell_dictionaries/' location.
else if (!sigil_extra_root.isEmpty()) {
paths.append(sigil_extra_root + "/hunspell_dictionaries/");
}
// Bundled dicts were not installed use standard system dictionary location.
else if (!dicts_are_bundled) {
paths.append("/usr/share/hunspell");
// Add additional hunspell dictionary directories. Provided at compile
// time via the cmake option EXTRA_DICT_DIRS (colon separated list).
if (!extra_dict_dirs.isEmpty()) {
foreach (QString s, extra_dict_dirs.split(":")) {
paths << s.trimmed();
}
}
}
else {
// else use the standard build time 'share/sigil/hunspell_dictionaries/'location.
paths.append(sigil_share_root + "/hunspell_dictionaries/");
}
return paths;
}
#endif
// Uses QUuid to generate a random UUID but also removes
// the curly braces that QUuid::createUuid() adds
QString Utility::CreateUUID()
{
return QUuid::createUuid().toString().remove("{").remove("}");
}
// Convert the casing of the text, returning the result.
QString Utility::ChangeCase(const QString &text, const Utility::Casing &casing)
{
if (text.isEmpty()) {
return text;
}
switch (casing) {
case Utility::Casing_Lowercase: {
return text.toLower();
}
case Utility::Casing_Uppercase: {
return text.toUpper();
}
case Utility::Casing_Titlecase: {
// This is a super crude algorithm, could be replaced by something more clever.
QString new_text = text.toLower();
// Skip past any leading spaces
int i = 0;
while (i < text.length() && new_text.at(i).isSpace()) {
i++;
}
while (i < text.length()) {
if (i == 0 || new_text.at(i - 1).isSpace()) {
new_text.replace(i, 1, new_text.at(i).toUpper());
}
i++;
}
return new_text;
}
case Utility::Casing_Capitalize: {
// This is a super crude algorithm, could be replaced by something more clever.
QString new_text = text.toLower();
// Skip past any leading spaces
int i = 0;
while (i < text.length() && new_text.at(i).isSpace()) {
i++;
}
if (i < text.length()) {
new_text.replace(i, 1, new_text.at(i).toUpper());
}
return new_text;
}
default:
return text;
}
}
// Returns true if the string is mixed case, false otherwise.
// For instance, "test" and "TEST" return false, "teSt" returns true.
// If the string is empty, returns false.
bool Utility::IsMixedCase(const QString &string)
{
if (string.isEmpty() || string.length() == 1) {
return false;
}
bool first_char_lower = string[ 0 ].isLower();
for (int i = 1; i < string.length(); ++i) {
if (string[ i ].isLower() != first_char_lower) {
return true;
}
}
return false;
}
// Returns a substring of a specified string;
// the characters included are in the interval:
// [ start_index, end_index >
QString Utility::Substring(int start_index, int end_index, const QString &string)
{
return string.mid(start_index, end_index - start_index);
}
// Returns a substring of a specified string;
// the characters included are in the interval:
// [ start_index, end_index >
QStringRef Utility::SubstringRef(int start_index, int end_index, const QString &string)
{
return string.midRef(start_index, end_index - start_index);
}
// Replace the first occurrence of string "before"
// with string "after" in string "string"
QString Utility::ReplaceFirst(const QString &before, const QString &after, const QString &string)
{
int start_index = string.indexOf(before);
int end_index = start_index + before.length();
return Substring(0, start_index, string) + after + Substring(end_index, string.length(), string);
}
QStringList Utility::GetAbsolutePathsToFolderDescendantFiles(const QString &fullfolderpath)
{
QDir folder(fullfolderpath);
QStringList files;
foreach(QFileInfo file, folder.entryInfoList()) {
if ((file.fileName() != ".") && (file.fileName() != "..")) {
// If it's a file, add it to the list
if (file.isFile()) {
files.append(Utility::URLEncodePath(file.absoluteFilePath()));
}
// Else it's a directory, so
// we add all files from that dir
else {
files.append(GetAbsolutePathsToFolderDescendantFiles(file.absoluteFilePath()));
}
}
}
return files;
}
// Copies every file and folder in the source folder
// to the destination folder; the paths to the folders are submitted;
// the destination folder needs to be created in advance
void Utility::CopyFiles(const QString &fullfolderpath_source, const QString &fullfolderpath_destination)
{
QDir folder_source(fullfolderpath_source);
QDir folder_destination(fullfolderpath_destination);
// Erase all the files in this folder
foreach(QFileInfo file, folder_source.entryInfoList()) {
if ((file.fileName() != ".") && (file.fileName() != "..")) {
// If it's a file, copy it
if (file.isFile()) {
QString destination = fullfolderpath_destination + "/" + file.fileName();
bool success = QFile::copy(file.absoluteFilePath(), destination);
if (!success) {
std::string msg = file.absoluteFilePath().toStdString() + ": " + destination.toStdString();
throw(CannotCopyFile(msg));
}
}
// Else it's a directory, copy everything in it
// to a new folder of the same name in the destination folder
else {
folder_destination.mkpath(file.fileName());
CopyFiles(file.absoluteFilePath(), fullfolderpath_destination + "/" + file.fileName());
}
}
}
}
//
// Delete a directory along with all of its contents.
//
// \param dirName Path of directory to remove.
// \return true on success; false on error.
//
bool Utility::removeDir(const QString &dirName)
{
bool result = true;
QDir dir(dirName);
if (dir.exists(dirName)) {
Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
if (info.isDir()) {
result = removeDir(info.absoluteFilePath());
} else {
result = QFile::remove(info.absoluteFilePath());
}
if (!result) {
return result;
}
}
result = dir.rmdir(dirName);
}
return result;
}
// Deletes the specified file if it exists
bool Utility::SDeleteFile(const QString &fullfilepath)
{
// Make sure the path exists, otherwise very
// bad things could happen
if (!QFileInfo(fullfilepath).exists()) {
return false;
}
QFile file(fullfilepath);
bool deleted = file.remove();
// Some multiple file deletion operations fail on Windows, so we try once more.
if (!deleted) {
qApp->processEvents();
SleepFunctions::msleep(100);
deleted = file.remove();
}
return deleted;
}
// Copies File from full Inpath to full OutPath with overwrite if needed
bool Utility::ForceCopyFile(const QString &fullinpath, const QString &fulloutpath)
{
if (!QFileInfo(fullinpath).exists()) {
return false;
}
if (QFileInfo::exists(fulloutpath)) {
Utility::SDeleteFile(fulloutpath);
}
return QFile::copy(fullinpath, fulloutpath);
}
bool Utility::RenameFile(const QString &oldfilepath, const QString &newfilepath)
{
// Make sure the path exists, otherwise very
// bad things could happen
if (!QFileInfo(oldfilepath).exists()) {
return false;
}
// Ensure that the newfilepath doesn't already exist but due to case insenstive file systems
// check if we are actually renaming to an identical path with a different case.
if (QFileInfo(newfilepath).exists() && QFileInfo(oldfilepath) != QFileInfo(newfilepath)) {
return false;
}
// On case insensitive file systems, QFile::rename fails when the new name is the
// same (case insensitive) to the old one. This is workaround for that issue.
int ret = -1;
#if defined(Q_OS_WIN32)
ret = _wrename(Utility::QStringToStdWString(oldfilepath).data(), Utility::QStringToStdWString(newfilepath).data());
#else
ret = rename(oldfilepath.toUtf8().data(), newfilepath.toUtf8().data());
#endif
if (ret == 0) {
return true;
}
return false;
}
QString Utility::GetTemporaryFileNameWithExtension(const QString &extension)
{
SettingsStore ss;
QString temp_path = ss.tempFolderHome();
if (temp_path == "<SIGIL_DEFAULT_TEMP_HOME>") {
temp_path = QDir::tempPath();
}
return temp_path + "/sigil_" + Utility::CreateUUID() + extension;
}
// Returns true if the file can be read;
// shows an error dialog if it can't
// with a message elaborating what's wrong
bool Utility::IsFileReadable(const QString &fullfilepath)
{
// Qt has <QFileInfo>.exists() and <QFileInfo>.isReadable()
// functions, but then we would have to create our own error
// message for each of those situations (and more). Trying to
// actually open the file enables us to retrieve the exact
// reason preventing us from reading the file in an error string.
QFile file(fullfilepath);
// Check if we can open the file
if (!file.open(QFile::ReadOnly)) {
Utility::DisplayStdErrorDialog(
QObject::tr("Cannot read file %1:\n%2.")
.arg(fullfilepath)
.arg(file.errorString())
);
return false;
}
file.close();
return true;
}
// Reads the text file specified with the full file path;
// text needs to be in UTF-8 or UTF-16; if the file cannot
// be read, an error dialog is shown and an empty string returned
QString Utility::ReadUnicodeTextFile(const QString &fullfilepath)
{
// TODO: throw an exception instead of
// returning an empty string
QFile file(fullfilepath);
// Check if we can open the file
if (!file.open(QFile::ReadOnly)) {
std::string msg = fullfilepath.toStdString() + ": " + file.errorString().toStdString();
throw(CannotOpenFile(msg));
}
QTextStream in(&file);
// Input should be UTF-8
in.setCodec("UTF-8");
// This will automatically switch reading from
// UTF-8 to UTF-16 if a BOM is detected
in.setAutoDetectUnicode(true);
return ConvertLineEndings(in.readAll());
}
// Writes the provided text variable to the specified
// file; if the file exists, it is truncated
void Utility::WriteUnicodeTextFile(const QString &text, const QString &fullfilepath)
{
QFile file(fullfilepath);
if (!file.open(QIODevice::WriteOnly |
QIODevice::Truncate |
QIODevice::Text
)
) {
std::string msg = file.fileName().toStdString() + ": " + file.errorString().toStdString();
throw(CannotOpenFile(msg));
}
QTextStream out(&file);
// We ALWAYS output in UTF-8
out.setCodec("UTF-8");
out << text;
}
// Converts Mac and Windows style line endings to Unix style
// line endings that are expected throughout the Qt framework
QString Utility::ConvertLineEndings(const QString &text)
{
QString newtext(text);
return newtext.replace("\x0D\x0A", "\x0A").replace("\x0D", "\x0A");
}
// Decodes XML escaped string to normal text
// & -> "&" ' -> "'" " -> "\"" < -> "<" > -> ">"
QString Utility::DecodeXML(const QString &text)
{
QString newtext(text);
newtext.replace("'", "'");
newtext.replace(""", "\"");
newtext.replace("<", "<");
newtext.replace(">", ">");
newtext.replace("&", "&");
return newtext;
}
QString Utility::EncodeXML(const QString &text)
{
QString newtext(text);
return newtext.toHtmlEscaped();
}
QString Utility::URLEncodePath(const QString &path)
{
QString newpath = path;
QUrl href = QUrl(newpath);
QString scheme = href.scheme();
if (!scheme.isEmpty()) {
scheme = scheme + "://";
newpath.remove(0, scheme.length());
}
QByteArray encoded_url = QUrl::toPercentEncoding(newpath, QByteArray("/#"));
return scheme + QString::fromUtf8(encoded_url.constData(), encoded_url.count());
}
QString Utility::URLDecodePath(const QString &path)
{
return QUrl::fromPercentEncoding(path.toUtf8());
}
void Utility::DisplayExceptionErrorDialog(const QString &error_info)
{
QMessageBox message_box(QApplication::activeWindow());
message_box.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
message_box.setModal(true);
message_box.setIcon(QMessageBox::Critical);
message_box.setWindowTitle("Sigil");
// Spaces are added to the end because otherwise the dialog is too small.
message_box.setText(QObject::tr("Sigil has encountered a problem.") % " ");
message_box.setInformativeText(QObject::tr("Sigil may need to close."));
message_box.setStandardButtons(QMessageBox::Close);
QStringList detailed_text;
detailed_text << "Error info: " + error_info
<< "Sigil version: " + QString(SIGIL_FULL_VERSION)
<< "Runtime Qt: " + QString(qVersion())
<< "Compiled Qt: " + QString(QT_VERSION_STR);
#if defined Q_OS_WIN32
detailed_text << "Platform: Windows SysInfo ID " + QString::number(QSysInfo::WindowsVersion);
#elif defined Q_OS_MAC
detailed_text << "Platform: Mac SysInfo ID " + QString::number(QSysInfo::MacintoshVersion);
#else
detailed_text << "Platform: Linux";
#endif
message_box.setDetailedText(detailed_text.join("\n"));
message_box.exec();
}
void Utility::DisplayStdErrorDialog(const QString &error_message, const QString &detailed_text)
{
QMessageBox message_box(QApplication::activeWindow());
message_box.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
message_box.setModal(true);
message_box.setIcon(QMessageBox::Critical);
message_box.setWindowTitle("Sigil");
message_box.setText(error_message);
if (!detailed_text.isEmpty()) {
message_box.setDetailedText(detailed_text);
}
message_box.setStandardButtons(QMessageBox::Close);
message_box.exec();
}
void Utility::DisplayStdWarningDialog(const QString &warning_message, const QString &detailed_text)
{
SigilMessageBox message_box(QApplication::activeWindow());
message_box.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint);
message_box.setModal(true);
message_box.setIcon(QMessageBox::Warning);
message_box.setWindowTitle("Sigil");
message_box.setText(warning_message);
message_box.setTextFormat(Qt::RichText);
if (!detailed_text.isEmpty()) {
message_box.setDetailedText(detailed_text);
}
message_box.setStandardButtons(QMessageBox::Close);
message_box.exec();
}
// Returns a value for the environment variable name passed;
// if the env var isn't set, it returns an empty string
QString Utility::GetEnvironmentVar(const QString &variable_name)
{
// Renaming this function (and all references to it)
// to GetEnvironmentVariable gets you a linker error
// on MSVC 9. Funny, innit?
QRegularExpression search_for_name("^" + QRegularExpression::escape(variable_name) + "=");
QString variable = QProcess::systemEnvironment().filter(search_for_name).value(0);
if (!variable.isEmpty()) {
return variable.split("=")[ 1 ];
} else {
return QString();
}
}
// Returns the same number, but rounded to one decimal place
float Utility::RoundToOneDecimal(float number)
{
return QString::number(number, 'f', 1).toFloat();
}
QWidget *Utility::GetMainWindow()
{
QWidget *parent_window = QApplication::activeWindow();
while (parent_window && !(dynamic_cast<QMainWindow *>(parent_window))) {
parent_window = parent_window->parentWidget();
}
return parent_window;
}
QString Utility::getSpellingSafeText(const QString &raw_text)
{
// There is currently a problem with Hunspell if we attempt to pass
// words with smart apostrophes from the CodeView encoding.
// Hunspell dictionaries typically store their main wordlist using
// the dumb apostrophe variants only to save space and speed checking
QString text(raw_text);
return text.replace(QChar(0x2019),QChar(0x27));
}
bool Utility::has_non_ascii_chars(const QString &str)
{
QRegularExpression not_ascii("[^\\x00-\\x7F]");
QRegularExpressionMatch mo = not_ascii.match(str);
return mo.hasMatch();
}
bool Utility::use_filename_warning(const QString &filename)
{
if (has_non_ascii_chars(filename)) {
return QMessageBox::Apply == QMessageBox::warning(QApplication::activeWindow(),
tr("Sigil"),
tr("The requested file name contains non-ASCII characters. "
"You should only use ASCII characters in filenames. "
"Using non-ASCII characters can prevent the EPUB from working "
"with some readers.\n\n"
"Continue using the requested filename?"),
QMessageBox::Cancel|QMessageBox::Apply);
}
return true;
}
#if defined(Q_OS_WIN32)
std::wstring Utility::QStringToStdWString(const QString &str)
{
return std::wstring((const wchar_t *)str.utf16());
}
QString Utility::stdWStringToQString(const std::wstring &str)
{
return QString::fromUtf16((const ushort *)str.c_str());
}
#endif
bool Utility::UnZip(const QString &zippath, const QString &destpath)
{
int res = 0;
QDir dir(destpath);
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData());
#endif
if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) {
return false;
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// for security reasons against maliciously crafted zip archives
// we need the file path to always be inside the target folder
// and not outside, so we will remove all illegal backslashes
// and all relative upward paths segments "/../" from the zip's local
// file name/path before prepending the target folder to create
// the final path
QString original_path = qfile_name;
bool evil_or_corrupt_epub = false;
if (qfile_name.contains("\\")) evil_or_corrupt_epub = true;
qfile_name = "/" + qfile_name.replace("\\","");
if (qfile_name.contains("/../")) evil_or_corrupt_epub = true;
qfile_name = qfile_name.replace("/../","/");
while(qfile_name.startsWith("/")) {
qfile_name = qfile_name.remove(0,1);
}
if (cp437_file_name.contains("\\")) evil_or_corrupt_epub = true;
cp437_file_name = "/" + cp437_file_name.replace("\\","");
if (cp437_file_name.contains("/../")) evil_or_corrupt_epub = true;
cp437_file_name = cp437_file_name.replace("/../","/");
while(cp437_file_name.startsWith("/")) {
cp437_file_name = cp437_file_name.remove(0,1);
}
if (evil_or_corrupt_epub) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
// throw (UNZIPLoadParseError(QString(QObject::tr("Possible evil or corrupt zip file name: %1")).arg(original_path).toStdString()));
return false;
}
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
// Full file path in the temporary directory.
QString file_path = destpath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
return false;
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
return false;
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
return false;
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
return false;
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = destpath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
return false;
}
unzClose(zfile);
return true;
}
QStringList Utility::ZipInspect(const QString &zippath)
{
QStringList filelist;
int res = 0;
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData());
#endif
if ((zfile == NULL) || (!IsFileReadable(zippath))) {
return filelist;
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
filelist.append(cp437_file_name);
} else {
filelist.append(qfile_name);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
unzClose(zfile);
return filelist;
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_974_0 |
crossvul-cpp_data_bad_973_0 | /************************************************************************
**
** Copyright (C) 2016 - 2019 Kevin B. Hendricks, Stratford, Ontario, Canada
** Copyright (C) 2012 John Schember <john@nachtimwald.com>
** Copyright (C) 2009, 2010, 2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil 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.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#ifdef _WIN32
#define NOMINMAX
#endif
#include "unzip.h"
#ifdef _WIN32
#include "iowin32.h"
#endif
#include <string>
#include <QApplication>
#include <QtCore/QtCore>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QFutureSynchronizer>
#include <QtConcurrent/QtConcurrent>
#include <QtCore/QXmlStreamReader>
#include <QDirIterator>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QStringList>
#include <QMessageBox>
#include <QUrl>
#include "BookManipulation/FolderKeeper.h"
#include "BookManipulation/CleanSource.h"
#include "Importers/ImportEPUB.h"
#include "Misc/FontObfuscation.h"
#include "Misc/HTMLEncodingResolver.h"
#include "Misc/QCodePage437Codec.h"
#include "Misc/SettingsStore.h"
#include "Misc/Utility.h"
#include "ResourceObjects/CSSResource.h"
#include "ResourceObjects/HTMLResource.h"
#include "ResourceObjects/OPFResource.h"
#include "ResourceObjects/NCXResource.h"
#include "ResourceObjects/Resource.h"
#include "ResourceObjects/OPFParser.h"
#include "SourceUpdates/UniversalUpdates.h"
#include "sigil_constants.h"
#include "sigil_exception.h"
#ifndef MAX_PATH
// Set Max length to 256 because that's the max path size on many systems.
#define MAX_PATH 256
#endif
// This is the same read buffer size used by Java and Perl.
#define BUFF_SIZE 8192
const QString DUBLIN_CORE_NS = "http://purl.org/dc/elements/1.1/";
static const QString OEBPS_MIMETYPE = "application/oebps-package+xml";
static const QString UPDATE_ERROR_STRING = "SG_ERROR";
const QString NCX_MIMETYPE = "application/x-dtbncx+xml";
static const QString NCX_EXTENSION = "ncx";
const QString ADOBE_FONT_ALGO_ID = "http://ns.adobe.com/pdf/enc#RC";
const QString IDPF_FONT_ALGO_ID = "http://www.idpf.org/2008/embedding";
static const QString CONTAINER_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
" <rootfiles>\n"
" <rootfile full-path=\"%1\" media-type=\"application/oebps-package+xml\"/>\n"
" </rootfiles>\n"
"</container>\n";
static QCodePage437Codec *cp437 = 0;
// Constructor;
// The parameter is the file to be imported
ImportEPUB::ImportEPUB(const QString &fullfilepath)
: Importer(fullfilepath),
m_ExtractedFolderPath(m_TempFolder.GetPath()),
m_HasSpineItems(false),
m_NCXNotInManifest(false),
m_NavResource(NULL)
{
}
// Reads and parses the file
// and returns the created Book
QSharedPointer<Book> ImportEPUB::GetBook(bool extract_metadata)
{
QList<XMLResource *> non_well_formed;
SettingsStore ss;
if (!Utility::IsFileReadable(m_FullFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot read EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
// These read the EPUB file
ExtractContainer();
QHash<QString, QString> encrypted_files = ParseEncryptionXml();
if (BookContentEncrypted(encrypted_files)) {
throw (FileEncryptedWithDrm(""));
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// These mutate the m_Book object
LocateOPF();
m_opfDir = QFileInfo(m_OPFFilePath).dir();
// These mutate the m_Book object
ReadOPF();
AddObfuscatedButUndeclaredFonts(encrypted_files);
AddNonStandardAppleXML();
LoadInfrastructureFiles();
// Check for files missing in the Manifest and create warning
QStringList notInManifest;
foreach(QString file_path, m_ZipFilePaths) {
// skip mimetype and anything in META-INF and the opf itself
if (file_path == "mimetype") continue;
if (file_path.startsWith("META-INF")) continue;
if (m_OPFFilePath.contains(file_path)) continue;
if (!m_ManifestFilePaths.contains(file_path)) {
notInManifest << file_path;
}
}
if (!notInManifest.isEmpty()) {
Utility::DisplayStdWarningDialog(tr("Files exist in epub that are not listed in the manifest, they will be ignored"), notInManifest.join("\n"));
}
const QHash<QString, QString> updates = LoadFolderStructure();
const QList<Resource *> resources = m_Book->GetFolderKeeper()->GetResourceList();
// We're going to check all html files until we find one that isn't well formed then we'll prompt
// the user if they want to auto fix or not.
//
// If we have non-well formed content and they shouldn't be auto fixed we'll pass that on to
// the universal update function so it knows to skip them. Otherwise we won't include them and
// let it modify the file.
for (int i=0; i<resources.count(); ++i) {
if (resources.at(i)->Type() == Resource::HTMLResourceType) {
HTMLResource *hresource = dynamic_cast<HTMLResource *>(resources.at(i));
if (!hresource) {
continue;
}
// Load the content into the HTMLResource so we can perform a well formed check.
try {
hresource->SetText(HTMLEncodingResolver::ReadHTMLFile(hresource->GetFullPath()));
} catch (...) {
if (ss.cleanOn() & CLEANON_OPEN) {
non_well_formed << hresource;
continue;
}
}
if (ss.cleanOn() & CLEANON_OPEN) {
if (!XhtmlDoc::IsDataWellFormed(hresource->GetText(),hresource->GetEpubVersion())) {
non_well_formed << hresource;
}
}
}
}
if (!non_well_formed.isEmpty()) {
QApplication::restoreOverrideCursor();
if (QMessageBox::Yes == QMessageBox::warning(QApplication::activeWindow(),
tr("Sigil"),
tr("This EPUB has HTML files that are not well formed. "
"Sigil can attempt to automatically fix these files, although this "
"can result in data loss.\n\n"
"Do you want to automatically fix the files?"),
QMessageBox::Yes|QMessageBox::No)
) {
non_well_formed.clear();
}
QApplication::setOverrideCursor(Qt::WaitCursor);
}
const QStringList load_errors = UniversalUpdates::PerformUniversalUpdates(false, resources, updates, non_well_formed);
Q_FOREACH (QString err, load_errors) {
AddLoadWarning(QString("%1").arg(err));
}
ProcessFontFiles(resources, updates, encrypted_files);
if (m_PackageVersion.startsWith('3')) {
HTMLResource * nav_resource = NULL;
if (m_NavResource) {
if (m_NavResource->Type() == Resource::HTMLResourceType) {
nav_resource = dynamic_cast<HTMLResource*>(m_NavResource);
}
}
if (!nav_resource) {
// we need to create a nav file here because one was not found
// it will automatically be added to the content.opf
nav_resource = m_Book->CreateEmptyNavFile(true);
Resource * res = dynamic_cast<Resource *>(nav_resource);
m_Book->GetOPF()->SetItemRefLinear(res, false);
}
m_Book->GetOPF()->SetNavResource(nav_resource);
}
if (m_NCXNotInManifest) {
// We manually created an NCX file because there wasn't one in the manifest.
// Need to create a new manifest id for it.
m_NCXId = m_Book->GetOPF()->AddNCXItem(m_NCXFilePath);
}
// Ensure that our spine has a <spine toc="ncx"> element on it now in case it was missing.
m_Book->GetOPF()->UpdateNCXOnSpine(m_NCXId);
// Make sure the <item> for the NCX in the manifest reflects correct href path
m_Book->GetOPF()->UpdateNCXLocationInManifest(m_Book->GetNCX());
// If spine was not present or did not contain any items, recreate the OPF from scratch
// preserving any important metadata elements and making a new reading order.
if (!m_HasSpineItems) {
QList<MetaEntry> originalMetadata = m_Book->GetOPF()->GetDCMetadata();
m_Book->GetOPF()->AutoFixWellFormedErrors();
if (extract_metadata) {
m_Book->GetOPF()->SetDCMetadata(originalMetadata);
}
AddLoadWarning(QObject::tr("The OPF file does not contain a valid spine.") % "\n" %
QObject::tr("Sigil has created a new one for you."));
}
// If we have modified the book to add spine attribute, manifest item or NCX mark as changed.
m_Book->SetModified(GetLoadWarnings().count() > 0);
QApplication::restoreOverrideCursor();
return m_Book;
}
QHash<QString, QString> ImportEPUB::ParseEncryptionXml()
{
QString encrpytion_xml_path = m_ExtractedFolderPath + "/META-INF/encryption.xml";
if (!QFileInfo(encrpytion_xml_path).exists()) {
return QHash<QString, QString>();
}
QXmlStreamReader encryption(Utility::ReadUnicodeTextFile(encrpytion_xml_path));
QHash<QString, QString> encrypted_files;
QString encryption_algo;
QString uri;
while (!encryption.atEnd()) {
encryption.readNext();
if (encryption.isStartElement()) {
if (encryption.name() == "EncryptionMethod") {
encryption_algo = encryption.attributes().value("", "Algorithm").toString();
} else if (encryption.name() == "CipherReference") {
uri = Utility::URLDecodePath(encryption.attributes().value("", "URI").toString());
encrypted_files[ uri ] = encryption_algo;
}
}
}
if (encryption.hasError()) {
const QString error = QString(QObject::tr("Error parsing encryption xml.\nLine: %1 Column %2 - %3"))
.arg(encryption.lineNumber())
.arg(encryption.columnNumber())
.arg(encryption.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
return encrypted_files;
}
bool ImportEPUB::BookContentEncrypted(const QHash<QString, QString> &encrypted_files)
{
foreach(QString algorithm, encrypted_files.values()) {
if (algorithm != ADOBE_FONT_ALGO_ID &&
algorithm != IDPF_FONT_ALGO_ID) {
return true;
}
}
return false;
}
// This is basically a workaround for old versions of InDesign not listing the fonts it
// embedded in the OPF manifest, even though the specs say it has to.
// It does list them in the encryption.xml, so we use that.
void ImportEPUB::AddObfuscatedButUndeclaredFonts(const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
foreach(QString filepath, encrypted_files.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(filepath).suffix().toLower())) {
continue;
}
// Only add the path to the manifest if it is not already included.
QMapIterator<QString, QString> valueSearch(m_Files);
if (!valueSearch.findNext(opf_dir.relativeFilePath(filepath))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(filepath);
}
}
}
// Another workaround for non-standard Apple files
// At present it only handles com.apple.ibooks.display-options.xml, but any
// further iBooks aberrations should be handled here as well.
void ImportEPUB::AddNonStandardAppleXML()
{
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QStringList aberrant_Apple_filenames;
aberrant_Apple_filenames.append(m_ExtractedFolderPath + "/META-INF/com.apple.ibooks.display-options.xml");
for (int i = 0; i < aberrant_Apple_filenames.size(); ++i) {
if (QFile::exists(aberrant_Apple_filenames.at(i))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(aberrant_Apple_filenames.at(i));
}
}
}
// Each resource can provide us with its new path. encrypted_files provides
// a mapping from old resource paths to the obfuscation algorithms.
// So we use the updates hash which provides a mapping from old paths to new
// paths to match the resources to their algorithms.
void ImportEPUB::ProcessFontFiles(const QList<Resource *> &resources,
const QHash<QString, QString> &updates,
const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QList<FontResource *> font_resources = m_Book->GetFolderKeeper()->GetResourceTypeList<FontResource>();
if (font_resources.empty()) {
return;
}
QHash<QString, QString> new_font_paths_to_algorithms;
foreach(QString old_update_path, updates.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(old_update_path).suffix().toLower())) {
continue;
}
QString new_update_path = updates[ old_update_path ];
foreach(QString old_encrypted_path, encrypted_files.keys()) {
if (old_update_path == old_encrypted_path) {
new_font_paths_to_algorithms[ new_update_path ] = encrypted_files[ old_encrypted_path ];
}
}
}
foreach(FontResource * font_resource, font_resources) {
QString match_path = "../" + font_resource->GetRelativePathToOEBPS();
QString algorithm = new_font_paths_to_algorithms.value(match_path);
if (algorithm.isEmpty()) {
continue;
}
font_resource->SetObfuscationAlgorithm(algorithm);
// Actually we are de-obfuscating, but the inverse operations of the obfuscation methods
// are the obfuscation methods themselves. For the math oriented, the obfuscation methods
// are involutary [ f( f( x ) ) = x ].
if (algorithm == ADOBE_FONT_ALGO_ID) {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UuidIdentifierValue);
} else {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UniqueIdentifierValue);
}
}
}
void ImportEPUB::ExtractContainer()
{
int res = 0;
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData());
#endif
if (zfile == NULL) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot unzip EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// for security reasons we need the file path to always be inside the
// target folder and not outside, so we will remove all relative upward
// paths segments ".." from the file path before prepending the target
// folder to create the final target path
qfile_name = qfile_name.replace("../","");
cp437_file_name = cp437_file_name.replace("../","");
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
QDir dir(m_ExtractedFolderPath);
// Full file path in the temporary directory.
QString file_path = m_ExtractedFolderPath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
// add it to the list of files found inside the zip
if (cp437_file_name.isEmpty()) {
m_ZipFilePaths << qfile_name;
} else {
m_ZipFilePaths << cp437_file_name;
}
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = m_ExtractedFolderPath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot open EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
unzClose(zfile);
}
void ImportEPUB::LocateOPF()
{
QString fullpath = m_ExtractedFolderPath + "/META-INF/container.xml";
QXmlStreamReader container;
try {
container.addData(Utility::ReadUnicodeTextFile(fullpath));
} catch (CannotOpenFile) {
// Find the first OPF file.
QString OPFfile;
QDirIterator files(m_ExtractedFolderPath, QStringList() << "*.opf", QDir::NoFilter, QDirIterator::Subdirectories);
while (files.hasNext()) {
OPFfile = QDir(m_ExtractedFolderPath).relativeFilePath(files.next());
break;
}
if (OPFfile.isEmpty()) {
std::string msg = fullpath.toStdString() + ": " + tr("Epub has missing or improperly specified OPF.").toStdString();
throw (CannotOpenFile(msg));
}
// Create a default container.xml.
QDir folder(m_ExtractedFolderPath);
folder.mkdir("META-INF");
Utility::WriteUnicodeTextFile(CONTAINER_XML.arg(OPFfile), fullpath);
container.addData(Utility::ReadUnicodeTextFile(fullpath));
}
while (!container.atEnd()) {
container.readNext();
if (container.isStartElement() &&
container.name() == "rootfile"
) {
if (container.attributes().hasAttribute("media-type") &&
container.attributes().value("", "media-type") == OEBPS_MIMETYPE
) {
m_OPFFilePath = m_ExtractedFolderPath + "/" + container.attributes().value("", "full-path").toString();
// As per OCF spec, the first rootfile element
// with the OEBPS mimetype is considered the "main" one.
break;
}
}
}
if (container.hasError()) {
const QString error = QString(
QObject::tr("Unable to parse container.xml file.\nLine: %1 Column %2 - %3"))
.arg(container.lineNumber())
.arg(container.columnNumber())
.arg(container.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
if (m_OPFFilePath.isEmpty() || !QFile::exists(m_OPFFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("No appropriate OPF file found")).toStdString()));
}
}
void ImportEPUB::ReadOPF()
{
QString opf_text = CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE);
QXmlStreamReader opf_reader(opf_text);
QString ncx_id_on_spine;
while (!opf_reader.atEnd()) {
opf_reader.readNext();
if (!opf_reader.isStartElement()) {
continue;
}
if (opf_reader.name() == "package") {
m_UniqueIdentifierId = opf_reader.attributes().value("", "unique-identifier").toString();
m_PackageVersion = opf_reader.attributes().value("", "version").toString();
if (m_PackageVersion == "1.0") m_PackageVersion = "2.0";
}
else if (opf_reader.name() == "identifier") {
ReadIdentifierElement(&opf_reader);
}
// epub3 look for linked metadata resources that are included inside the epub
// but that are not and must not be included in the manifest
else if (opf_reader.name() == "link") {
ReadMetadataLinkElement(&opf_reader);
}
// Get the list of content files that
// make up the publication
else if (opf_reader.name() == "item") {
ReadManifestItemElement(&opf_reader);
}
// We read this just to get the NCX id
else if (opf_reader.name() == "spine") {
ncx_id_on_spine = opf_reader.attributes().value("", "toc").toString();
}
else if (opf_reader.name() == "itemref") {
m_HasSpineItems = true;
}
}
if (opf_reader.hasError()) {
const QString error = QString(QObject::tr("Unable to read OPF file.\nLine: %1 Column %2 - %3"))
.arg(opf_reader.lineNumber())
.arg(opf_reader.columnNumber())
.arg(opf_reader.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
// Ensure we have an NCX available
LocateOrCreateNCX(ncx_id_on_spine);
}
void ImportEPUB::ReadIdentifierElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString scheme = opf_reader->attributes().value("", "scheme").toString();
QString value = opf_reader->readElementText();
if (id == m_UniqueIdentifierId) {
m_UniqueIdentifierValue = value;
}
if (m_UuidIdentifierValue.isEmpty() &&
(value.contains("urn:uuid:") || scheme.toLower() == "uuid")) {
m_UuidIdentifierValue = value;
}
}
void ImportEPUB::ReadMetadataLinkElement(QXmlStreamReader *opf_reader)
{
QString relation = opf_reader->attributes().value("", "rel").toString();
QString mtype = opf_reader->attributes().value("", "media-type").toString();
QString props = opf_reader->attributes().value("", "properties").toString();
QString href = opf_reader->attributes().value("", "href").toString();
if (!href.isEmpty()) {
QUrl url = QUrl(href);
if (url.isRelative()) {
// we have a local unmanifested metadata file to handle
// attempt to map deprecated record types into proper media-types
if (relation == "marc21xml-record") {
mtype = "application/marcxml+xml";
}
else if (relation == "mods-record") {
mtype = "application/mods+xml";
}
else if (relation == "onix-record") {
mtype = "application/xml;onix";
}
else if (relation == "xmp-record") {
mtype = "application/xml;xmp";
}
else if (relation == "record") {
if (props == "onix") mtype = "application/xml;onix";
if (props == "xmp") mtype = "application/xml;xmp";
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QString path = opf_dir.absolutePath() + "/" + url.path();
if (QFile::exists(path)) {
QString id = Utility::CreateUUID();
m_Files[ id ] = opf_dir.relativeFilePath(path);
m_FileMimetypes[ id ] = mtype;
}
}
}
}
void ImportEPUB::ReadManifestItemElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString href = opf_reader->attributes().value("", "href").toString();
QString type = opf_reader->attributes().value("", "media-type").toString();
QString properties = opf_reader->attributes().value("", "properties").toString();
// Paths are percent encoded in the OPF, we use "normal" paths internally.
href = Utility::URLDecodePath(href);
QString extension = QFileInfo(href).suffix().toLower();
// find the epub root relative file path from the opf location and the item href
QString file_path = m_opfDir.absolutePath() + "/" + href;
file_path = file_path.remove(0, m_ExtractedFolderPath.length() + 1);
if (type != NCX_MIMETYPE && extension != NCX_EXTENSION) {
if (!m_ManifestFilePaths.contains(file_path)) {
if (m_Files.contains(id)) {
// We have an error situation with a duplicate id in the epub.
// We must warn the user, but attempt to use another id so the epub can still be loaded.
QString base_id = QFileInfo(href).fileName();
QString new_id(base_id);
int duplicate_index = 0;
while (m_Files.contains(new_id)) {
duplicate_index++;
new_id = QString("%1%2").arg(base_id).arg(duplicate_index);
}
const QString load_warning = QObject::tr("The OPF manifest contains duplicate ids for: %1").arg(id) +
" - " + QObject::tr("A temporary id has been assigned to load this EPUB. You should edit your OPF file to remove the duplication.");
id = new_id;
AddLoadWarning(load_warning);
}
m_Files[ id ] = href;
m_FileMimetypes[ id ] = type;
m_ManifestFilePaths << file_path;
// store information about any nav document
if (properties.contains("nav")) {
m_NavId = id;
m_NavHref = href;
}
}
} else {
m_NcxCandidates[ id ] = href;
m_ManifestFilePaths << file_path;
}
}
void ImportEPUB::LocateOrCreateNCX(const QString &ncx_id_on_spine)
{
QString load_warning;
QString ncx_href = "not_found";
m_NCXId = ncx_id_on_spine;
// Handle various failure conditions, such as:
// - ncx not specified in the spine (search for a matching manifest item by extension)
// - ncx specified in spine, but no matching manifest item entry (create a new one)
// - ncx file not physically present (create a new one)
// - ncx not in spine or manifest item (create a new one)
if (!m_NCXId.isEmpty()) {
ncx_href = m_NcxCandidates[ m_NCXId ];
} else {
// Search for the ncx in the manifest by looking for files with
// a .ncx extension.
QHashIterator<QString, QString> ncxSearch(m_NcxCandidates);
while (ncxSearch.hasNext()) {
ncxSearch.next();
if (QFileInfo(ncxSearch.value()).suffix().toLower() == NCX_EXTENSION) {
m_NCXId = ncxSearch.key();
load_warning = QObject::tr("The OPF file did not identify the NCX file correctly.") + "\n" +
" - " + QObject::tr("Sigil has used the following file as the NCX:") +
QString(" %1").arg(m_NcxCandidates[ m_NCXId ]);
ncx_href = m_NcxCandidates[ m_NCXId ];
break;
}
}
}
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % ncx_href;
if (ncx_href.isEmpty() || !QFile::exists(m_NCXFilePath)) {
m_NCXNotInManifest = m_NCXId.isEmpty() || ncx_href.isEmpty();
m_NCXId.clear();
// Things are really bad and no .ncx file was found in the manifest or
// the file does not physically exist. We need to create a new one.
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % NCX_FILE_NAME;
// Create a new file for the NCX.
NCXResource ncx_resource(m_ExtractedFolderPath, m_NCXFilePath, m_Book->GetFolderKeeper());
// We are relying on an identifier being set from the metadata.
// It might not have one if the book does not have the urn:uuid: format.
if (!m_UuidIdentifierValue.isEmpty()) {
ncx_resource.SetMainID(m_UuidIdentifierValue);
}
ncx_resource.SaveToDisk();
if (m_PackageVersion.startsWith('3')) {
load_warning = QObject::tr("Sigil has created a template NCX") + "\n" +
QObject::tr("to support epub2 backwards compatibility.");
} else {
if (ncx_href.isEmpty()) {
load_warning = QObject::tr("The OPF file does not contain an NCX file.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
} else {
load_warning = QObject::tr("The NCX file is not present in this EPUB.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
}
}
}
if (!load_warning.isEmpty()) {
AddLoadWarning(load_warning);
}
}
void ImportEPUB::LoadInfrastructureFiles()
{
// always SetEpubVersion before SetText in OPF as SetText will validate with it
m_Book->GetOPF()->SetEpubVersion(m_PackageVersion);
m_Book->GetOPF()->SetText(CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE));
QString OPFBookRelPath = m_OPFFilePath;
OPFBookRelPath = OPFBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetOPF()->SetCurrentBookRelPath(OPFBookRelPath);
m_Book->GetNCX()->SetText(CleanSource::ProcessXML(Utility::ReadUnicodeTextFile(m_NCXFilePath),"application/x-dtbncx+xml"));
m_Book->GetNCX()->SetEpubVersion(m_PackageVersion);
QString NCXBookRelPath = m_NCXFilePath;
NCXBookRelPath = NCXBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetNCX()->SetCurrentBookRelPath(NCXBookRelPath);
}
QHash<QString, QString> ImportEPUB::LoadFolderStructure()
{
QList<QString> keys = m_Files.keys();
int num_files = keys.count();
QFutureSynchronizer<std::tuple<QString, QString>> sync;
for (int i = 0; i < num_files; ++i) {
QString id = keys.at(i);
sync.addFuture(QtConcurrent::run(
this,
&ImportEPUB::LoadOneFile,
m_Files.value(id),
m_FileMimetypes.value(id)));
}
sync.waitForFinished();
QList<QFuture<std::tuple<QString, QString>>> futures = sync.futures();
int num_futures = futures.count();
QHash<QString, QString> updates;
for (int i = 0; i < num_futures; ++i) {
std::tuple<QString, QString> result = futures.at(i).result();
updates[std::get<0>(result)] = std::get<1>(result);
}
updates.remove(UPDATE_ERROR_STRING);
return updates;
}
std::tuple<QString, QString> ImportEPUB::LoadOneFile(const QString &path, const QString &mimetype)
{
QString fullfilepath = QDir::cleanPath(QFileInfo(m_OPFFilePath).absolutePath() + "/" + path);
QString currentpath = fullfilepath;
currentpath = currentpath.remove(0,m_ExtractedFolderPath.length()+1);
try {
Resource *resource = m_Book->GetFolderKeeper()->AddContentFileToFolder(fullfilepath, false, mimetype);
if (path == m_NavHref) {
m_NavResource = resource;
}
resource->SetCurrentBookRelPath(currentpath);
QString newpath = "../" + resource->GetRelativePathToOEBPS();
return std::make_tuple(currentpath, newpath);
} catch (FileDoesNotExist) {
return std::make_tuple(UPDATE_ERROR_STRING, UPDATE_ERROR_STRING);
}
}
QString ImportEPUB::PrepareOPFForReading(const QString &source)
{
QString source_copy(source);
QString prefix = source_copy.left(XML_DECLARATION_SEARCH_PREFIX_SIZE);
QRegularExpression version(VERSION_ATTRIBUTE);
QRegularExpressionMatch mo = version.match(prefix);
if (mo.hasMatch()) {
// MASSIVE hack for XML 1.1 "support";
// this is only for people who specify
// XML 1.1 when they actually only use XML 1.0
source_copy.replace(mo.capturedStart(1), mo.capturedLength(1), "1.0");
}
return source_copy;
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_973_0 |
crossvul-cpp_data_good_74_1 | /*
Copyright (C) 2010 Roberto Pompermaier
Copyright (C) 2005-2014 Sergey A. Tachenov
This file is part of QuaZIP.
QuaZIP 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.
QuaZIP 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 QuaZIP. If not, see <http://www.gnu.org/licenses/>.
See COPYING file for the full LGPL text.
Original ZIP package is copyrighted by Gilles Vollant and contributors,
see quazip/(un)zip.h files for details. Basically it's the zlib license.
*/
#include "JlCompress.h"
#include <QDebug>
static bool copyData(QIODevice &inFile, QIODevice &outFile)
{
while (!inFile.atEnd()) {
char buf[4096];
qint64 readLen = inFile.read(buf, 4096);
if (readLen <= 0)
return false;
if (outFile.write(buf, readLen) != readLen)
return false;
}
return true;
}
bool JlCompress::compressFile(QuaZip* zip, QString fileName, QString fileDest) {
// zip: oggetto dove aggiungere il file
// fileName: nome del file reale
// fileDest: nome del file all'interno del file compresso
// Controllo l'apertura dello zip
if (!zip) return false;
if (zip->getMode()!=QuaZip::mdCreate &&
zip->getMode()!=QuaZip::mdAppend &&
zip->getMode()!=QuaZip::mdAdd) return false;
// Apro il file originale
QFile inFile;
inFile.setFileName(fileName);
if(!inFile.open(QIODevice::ReadOnly)) return false;
// Apro il file risulato
QuaZipFile outFile(zip);
if(!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(fileDest, inFile.fileName()))) return false;
// Copio i dati
if (!copyData(inFile, outFile) || outFile.getZipError()!=UNZ_OK) {
return false;
}
// Chiudo i file
outFile.close();
if (outFile.getZipError()!=UNZ_OK) return false;
inFile.close();
return true;
}
bool JlCompress::compressSubDir(QuaZip* zip, QString dir, QString origDir, bool recursive, QDir::Filters filters) {
// zip: oggetto dove aggiungere il file
// dir: cartella reale corrente
// origDir: cartella reale originale
// (path(dir)-path(origDir)) = path interno all'oggetto zip
// Controllo l'apertura dello zip
if (!zip) return false;
if (zip->getMode()!=QuaZip::mdCreate &&
zip->getMode()!=QuaZip::mdAppend &&
zip->getMode()!=QuaZip::mdAdd) return false;
// Controllo la cartella
QDir directory(dir);
if (!directory.exists()) return false;
QDir origDirectory(origDir);
if (dir != origDir) {
QuaZipFile dirZipFile(zip);
if (!dirZipFile.open(QIODevice::WriteOnly,
QuaZipNewInfo(origDirectory.relativeFilePath(dir) + "/", dir), 0, 0, 0)) {
return false;
}
dirZipFile.close();
}
// Se comprimo anche le sotto cartelle
if (recursive) {
// Per ogni sotto cartella
QFileInfoList files = directory.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot|filters);
for (int index = 0; index < files.size(); ++index ) {
const QFileInfo & file( files.at( index ) );
#if QT_VERSION < QT_VERSION_CHECK(4, 7, 4)
if (!file.isDir())
continue;
#endif
// Comprimo la sotto cartella
if(!compressSubDir(zip,file.absoluteFilePath(),origDir,recursive,filters)) return false;
}
}
// Per ogni file nella cartella
QFileInfoList files = directory.entryInfoList(QDir::Files|filters);
for (int index = 0; index < files.size(); ++index ) {
const QFileInfo & file( files.at( index ) );
// Se non e un file o e il file compresso che sto creando
if(!file.isFile()||file.absoluteFilePath()==zip->getZipName()) continue;
// Creo il nome relativo da usare all'interno del file compresso
QString filename = origDirectory.relativeFilePath(file.absoluteFilePath());
// Comprimo il file
if (!compressFile(zip,file.absoluteFilePath(),filename)) return false;
}
return true;
}
bool JlCompress::extractFile(QuaZip* zip, QString fileName, QString fileDest) {
// zip: oggetto dove aggiungere il file
// filename: nome del file reale
// fileincompress: nome del file all'interno del file compresso
// Controllo l'apertura dello zip
if (!zip) return false;
if (zip->getMode()!=QuaZip::mdUnzip) return false;
// Apro il file compresso
if (!fileName.isEmpty())
zip->setCurrentFile(fileName);
QuaZipFile inFile(zip);
if(!inFile.open(QIODevice::ReadOnly) || inFile.getZipError()!=UNZ_OK) return false;
// Controllo esistenza cartella file risultato
QDir curDir;
if (fileDest.endsWith('/')) {
if (!curDir.mkpath(fileDest)) {
return false;
}
} else {
if (!curDir.mkpath(QFileInfo(fileDest).absolutePath())) {
return false;
}
}
QuaZipFileInfo64 info;
if (!zip->getCurrentFileInfo(&info))
return false;
QFile::Permissions srcPerm = info.getPermissions();
if (fileDest.endsWith('/') && QFileInfo(fileDest).isDir()) {
if (srcPerm != 0) {
QFile(fileDest).setPermissions(srcPerm);
}
return true;
}
// Apro il file risultato
QFile outFile;
outFile.setFileName(fileDest);
if(!outFile.open(QIODevice::WriteOnly)) return false;
// Copio i dati
if (!copyData(inFile, outFile) || inFile.getZipError()!=UNZ_OK) {
outFile.close();
removeFile(QStringList(fileDest));
return false;
}
outFile.close();
// Chiudo i file
inFile.close();
if (inFile.getZipError()!=UNZ_OK) {
removeFile(QStringList(fileDest));
return false;
}
if (srcPerm != 0) {
outFile.setPermissions(srcPerm);
}
return true;
}
bool JlCompress::removeFile(QStringList listFile) {
bool ret = true;
// Per ogni file
for (int i=0; i<listFile.count(); i++) {
// Lo elimino
ret = ret && QFile::remove(listFile.at(i));
}
return ret;
}
bool JlCompress::compressFile(QString fileCompressed, QString file) {
// Creo lo zip
QuaZip zip(fileCompressed);
QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
if(!zip.open(QuaZip::mdCreate)) {
QFile::remove(fileCompressed);
return false;
}
// Aggiungo il file
if (!compressFile(&zip,file,QFileInfo(file).fileName())) {
QFile::remove(fileCompressed);
return false;
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
QFile::remove(fileCompressed);
return false;
}
return true;
}
bool JlCompress::compressFiles(QString fileCompressed, QStringList files) {
// Creo lo zip
QuaZip zip(fileCompressed);
QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
if(!zip.open(QuaZip::mdCreate)) {
QFile::remove(fileCompressed);
return false;
}
// Comprimo i file
QFileInfo info;
for (int index = 0; index < files.size(); ++index ) {
const QString & file( files.at( index ) );
info.setFile(file);
if (!info.exists() || !compressFile(&zip,file,info.fileName())) {
QFile::remove(fileCompressed);
return false;
}
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
QFile::remove(fileCompressed);
return false;
}
return true;
}
bool JlCompress::compressDir(QString fileCompressed, QString dir, bool recursive) {
return compressDir(fileCompressed, dir, recursive, 0);
}
bool JlCompress::compressDir(QString fileCompressed, QString dir,
bool recursive, QDir::Filters filters)
{
// Creo lo zip
QuaZip zip(fileCompressed);
QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
if(!zip.open(QuaZip::mdCreate)) {
QFile::remove(fileCompressed);
return false;
}
// Aggiungo i file e le sotto cartelle
if (!compressSubDir(&zip,dir,dir,recursive, filters)) {
QFile::remove(fileCompressed);
return false;
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
QFile::remove(fileCompressed);
return false;
}
return true;
}
QString JlCompress::extractFile(QString fileCompressed, QString fileName, QString fileDest) {
// Apro lo zip
QuaZip zip(fileCompressed);
return extractFile(zip, fileName, fileDest);
}
QString JlCompress::extractFile(QuaZip &zip, QString fileName, QString fileDest)
{
if(!zip.open(QuaZip::mdUnzip)) {
return QString();
}
// Estraggo il file
if (fileDest.isEmpty())
fileDest = fileName;
if (!extractFile(&zip,fileName,fileDest)) {
return QString();
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
removeFile(QStringList(fileDest));
return QString();
}
return QFileInfo(fileDest).absoluteFilePath();
}
QStringList JlCompress::extractFiles(QString fileCompressed, QStringList files, QString dir) {
// Creo lo zip
QuaZip zip(fileCompressed);
return extractFiles(zip, files, dir);
}
QStringList JlCompress::extractFiles(QuaZip &zip, const QStringList &files, const QString &dir)
{
if(!zip.open(QuaZip::mdUnzip)) {
return QStringList();
}
// Estraggo i file
QStringList extracted;
for (int i=0; i<files.count(); i++) {
QString absPath = QDir(dir).absoluteFilePath(files.at(i));
if (!extractFile(&zip, files.at(i), absPath)) {
removeFile(extracted);
return QStringList();
}
extracted.append(absPath);
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
removeFile(extracted);
return QStringList();
}
return extracted;
}
QStringList JlCompress::extractDir(QString fileCompressed, QString dir) {
// Apro lo zip
QuaZip zip(fileCompressed);
return extractDir(zip, dir);
}
QStringList JlCompress::extractDir(QuaZip &zip, const QString &dir)
{
if(!zip.open(QuaZip::mdUnzip)) {
return QStringList();
}
QString cleanDir = QDir::cleanPath(dir);
QDir directory(cleanDir);
QString absCleanDir = directory.absolutePath();
QStringList extracted;
if (!zip.goToFirstFile()) {
return QStringList();
}
do {
QString name = zip.getCurrentFileName();
QString absFilePath = directory.absoluteFilePath(name);
QString absCleanPath = QDir::cleanPath(absFilePath);
if (!absCleanPath.startsWith(absCleanDir + "/"))
continue;
if (!extractFile(&zip, "", absFilePath)) {
removeFile(extracted);
return QStringList();
}
extracted.append(absFilePath);
} while (zip.goToNextFile());
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
removeFile(extracted);
return QStringList();
}
return extracted;
}
QStringList JlCompress::getFileList(QString fileCompressed) {
// Apro lo zip
QuaZip* zip = new QuaZip(QFileInfo(fileCompressed).absoluteFilePath());
return getFileList(zip);
}
QStringList JlCompress::getFileList(QuaZip *zip)
{
if(!zip->open(QuaZip::mdUnzip)) {
delete zip;
return QStringList();
}
// Estraggo i nomi dei file
QStringList lst;
QuaZipFileInfo64 info;
for(bool more=zip->goToFirstFile(); more; more=zip->goToNextFile()) {
if(!zip->getCurrentFileInfo(&info)) {
delete zip;
return QStringList();
}
lst << info.name;
//info.name.toLocal8Bit().constData()
}
// Chiudo il file zip
zip->close();
if(zip->getZipError()!=0) {
delete zip;
return QStringList();
}
delete zip;
return lst;
}
QStringList JlCompress::extractDir(QIODevice *ioDevice, QString dir)
{
QuaZip zip(ioDevice);
return extractDir(zip, dir);
}
QStringList JlCompress::getFileList(QIODevice *ioDevice)
{
QuaZip *zip = new QuaZip(ioDevice);
return getFileList(zip);
}
QString JlCompress::extractFile(QIODevice *ioDevice, QString fileName, QString fileDest)
{
QuaZip zip(ioDevice);
return extractFile(zip, fileName, fileDest);
}
QStringList JlCompress::extractFiles(QIODevice *ioDevice, QStringList files, QString dir)
{
QuaZip zip(ioDevice);
return extractFiles(zip, files, dir);
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_74_1 |
crossvul-cpp_data_bad_240_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/WebModules.h>
#include <znc/FileUtils.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/znc.h>
#include <time.h>
#include <algorithm>
#include <sstream>
using std::pair;
using std::vector;
/// @todo Do we want to make this a configure option?
#define _SKINDIR_ _DATADIR_ "/webskins"
const unsigned int CWebSock::m_uiMaxSessions = 5;
// We need this class to make sure the contained maps and their content is
// destroyed in the order that we want.
struct CSessionManager {
// Sessions are valid for a day, (24h, ...)
CSessionManager() : m_mspSessions(24 * 60 * 60 * 1000), m_mIPSessions() {}
~CSessionManager() {
// Make sure all sessions are destroyed before any of our maps
// are destroyed
m_mspSessions.Clear();
}
CWebSessionMap m_mspSessions;
std::multimap<CString, CWebSession*> m_mIPSessions;
};
typedef std::multimap<CString, CWebSession*>::iterator mIPSessionsIterator;
static CSessionManager Sessions;
class CWebAuth : public CAuthBase {
public:
CWebAuth(CWebSock* pWebSock, const CString& sUsername,
const CString& sPassword, bool bBasic);
~CWebAuth() override {}
CWebAuth(const CWebAuth&) = delete;
CWebAuth& operator=(const CWebAuth&) = delete;
void SetWebSock(CWebSock* pWebSock) { m_pWebSock = pWebSock; }
void AcceptedLogin(CUser& User) override;
void RefusedLogin(const CString& sReason) override;
void Invalidate() override;
private:
protected:
CWebSock* m_pWebSock;
bool m_bBasic;
};
void CWebSock::FinishUserSessions(const CUser& User) {
Sessions.m_mspSessions.FinishUserSessions(User);
}
CWebSession::~CWebSession() {
// Find our entry in mIPSessions
pair<mIPSessionsIterator, mIPSessionsIterator> p =
Sessions.m_mIPSessions.equal_range(m_sIP);
mIPSessionsIterator it = p.first;
mIPSessionsIterator end = p.second;
while (it != end) {
if (it->second == this) {
Sessions.m_mIPSessions.erase(it++);
} else {
++it;
}
}
}
CZNCTagHandler::CZNCTagHandler(CWebSock& WebSock)
: CTemplateTagHandler(), m_WebSock(WebSock) {}
bool CZNCTagHandler::HandleTag(CTemplate& Tmpl, const CString& sName,
const CString& sArgs, CString& sOutput) {
if (sName.Equals("URLPARAM")) {
// sOutput = CZNC::Get()
sOutput = m_WebSock.GetParam(sArgs.Token(0), false);
return true;
}
return false;
}
CWebSession::CWebSession(const CString& sId, const CString& sIP)
: m_sId(sId),
m_sIP(sIP),
m_pUser(nullptr),
m_vsErrorMsgs(),
m_vsSuccessMsgs(),
m_tmLastActive() {
Sessions.m_mIPSessions.insert(make_pair(sIP, this));
UpdateLastActive();
}
void CWebSession::UpdateLastActive() { time(&m_tmLastActive); }
bool CWebSession::IsAdmin() const { return IsLoggedIn() && m_pUser->IsAdmin(); }
CWebAuth::CWebAuth(CWebSock* pWebSock, const CString& sUsername,
const CString& sPassword, bool bBasic)
: CAuthBase(sUsername, sPassword, pWebSock),
m_pWebSock(pWebSock),
m_bBasic(bBasic) {}
void CWebSession::ClearMessageLoops() {
m_vsErrorMsgs.clear();
m_vsSuccessMsgs.clear();
}
void CWebSession::FillMessageLoops(CTemplate& Tmpl) {
for (const CString& sMessage : m_vsErrorMsgs) {
CTemplate& Row = Tmpl.AddRow("ErrorLoop");
Row["Message"] = sMessage;
}
for (const CString& sMessage : m_vsSuccessMsgs) {
CTemplate& Row = Tmpl.AddRow("SuccessLoop");
Row["Message"] = sMessage;
}
}
size_t CWebSession::AddError(const CString& sMessage) {
m_vsErrorMsgs.push_back(sMessage);
return m_vsErrorMsgs.size();
}
size_t CWebSession::AddSuccess(const CString& sMessage) {
m_vsSuccessMsgs.push_back(sMessage);
return m_vsSuccessMsgs.size();
}
void CWebSessionMap::FinishUserSessions(const CUser& User) {
iterator it = m_mItems.begin();
while (it != m_mItems.end()) {
if (it->second.second->GetUser() == &User) {
m_mItems.erase(it++);
} else {
++it;
}
}
}
void CWebAuth::AcceptedLogin(CUser& User) {
if (m_pWebSock) {
std::shared_ptr<CWebSession> spSession = m_pWebSock->GetSession();
spSession->SetUser(&User);
m_pWebSock->SetLoggedIn(true);
m_pWebSock->UnPauseRead();
if (m_bBasic) {
m_pWebSock->ReadLine("");
} else {
m_pWebSock->Redirect("/?cookie_check=true");
}
DEBUG("Successful login attempt ==> USER [" + User.GetUserName() +
"] ==> SESSION [" + spSession->GetId() + "]");
}
}
void CWebAuth::RefusedLogin(const CString& sReason) {
if (m_pWebSock) {
std::shared_ptr<CWebSession> spSession = m_pWebSock->GetSession();
spSession->AddError("Invalid login!");
spSession->SetUser(nullptr);
m_pWebSock->SetLoggedIn(false);
m_pWebSock->UnPauseRead();
if (m_bBasic) {
m_pWebSock->AddHeader("WWW-Authenticate", "Basic realm=\"ZNC\"");
m_pWebSock->CHTTPSock::PrintErrorPage(
401, "Unauthorized",
"HTTP Basic authentication attempted with invalid credentials");
// Why CWebSock makes this function protected?..
} else {
m_pWebSock->Redirect("/?cookie_check=true");
}
DEBUG("UNSUCCESSFUL login attempt ==> REASON [" + sReason +
"] ==> SESSION [" + spSession->GetId() + "]");
}
}
void CWebAuth::Invalidate() {
CAuthBase::Invalidate();
m_pWebSock = nullptr;
}
CWebSock::CWebSock(const CString& sURIPrefix)
: CHTTPSock(nullptr, sURIPrefix),
m_bPathsSet(false),
m_Template(),
m_spAuth(),
m_sModName(""),
m_sPath(""),
m_sPage(""),
m_spSession() {
m_Template.AddTagHandler(std::make_shared<CZNCTagHandler>(*this));
}
CWebSock::~CWebSock() {
if (m_spAuth) {
m_spAuth->Invalidate();
}
// we have to account for traffic here because CSocket does
// not have a valid CModule* pointer.
CUser* pUser = GetSession()->GetUser();
if (pUser) {
pUser->AddBytesWritten(GetBytesWritten());
pUser->AddBytesRead(GetBytesRead());
} else {
CZNC::Get().AddBytesWritten(GetBytesWritten());
CZNC::Get().AddBytesRead(GetBytesRead());
}
// bytes have been accounted for, so make sure they don't get again:
ResetBytesWritten();
ResetBytesRead();
}
void CWebSock::GetAvailSkins(VCString& vRet) const {
vRet.clear();
CString sRoot(GetSkinPath("_default_"));
sRoot.TrimRight("/");
sRoot.TrimRight("_default_");
sRoot.TrimRight("/");
if (!sRoot.empty()) {
sRoot += "/";
}
if (!sRoot.empty() && CFile::IsDir(sRoot)) {
CDir Dir(sRoot);
for (const CFile* pSubDir : Dir) {
if (pSubDir->IsDir() && pSubDir->GetShortName() == "_default_") {
vRet.push_back(pSubDir->GetShortName());
break;
}
}
for (const CFile* pSubDir : Dir) {
if (pSubDir->IsDir() && pSubDir->GetShortName() != "_default_" &&
pSubDir->GetShortName() != ".svn") {
vRet.push_back(pSubDir->GetShortName());
}
}
}
}
VCString CWebSock::GetDirs(CModule* pModule, bool bIsTemplate) {
CString sHomeSkinsDir(CZNC::Get().GetZNCPath() + "/webskins/");
CString sSkinName(GetSkinName());
VCString vsResult;
// Module specific paths
if (pModule) {
const CString& sModName(pModule->GetModName());
// 1. ~/.znc/webskins/<user_skin_setting>/mods/<mod_name>/
//
if (!sSkinName.empty()) {
vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName +
"/");
}
// 2. ~/.znc/webskins/_default_/mods/<mod_name>/
//
vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName +
"/");
// 3. ./modules/<mod_name>/tmpl/
//
vsResult.push_back(pModule->GetModDataDir() + "/tmpl/");
// 4. ~/.znc/webskins/<user_skin_setting>/mods/<mod_name>/
//
if (!sSkinName.empty()) {
vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName +
"/");
}
// 5. ~/.znc/webskins/_default_/mods/<mod_name>/
//
vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName +
"/");
}
// 6. ~/.znc/webskins/<user_skin_setting>/
//
if (!sSkinName.empty()) {
vsResult.push_back(GetSkinPath(sSkinName) +
CString(bIsTemplate ? "/tmpl/" : "/"));
}
// 7. ~/.znc/webskins/_default_/
//
vsResult.push_back(GetSkinPath("_default_") +
CString(bIsTemplate ? "/tmpl/" : "/"));
return vsResult;
}
CString CWebSock::FindTmpl(CModule* pModule, const CString& sName) {
VCString vsDirs = GetDirs(pModule, true);
CString sFile = pModule->GetModName() + "_" + sName;
for (const CString& sDir : vsDirs) {
if (CFile::Exists(CDir::ChangeDir(sDir, sFile))) {
m_Template.AppendPath(sDir);
return sFile;
}
}
return sName;
}
void CWebSock::SetPaths(CModule* pModule, bool bIsTemplate) {
m_Template.ClearPaths();
VCString vsDirs = GetDirs(pModule, bIsTemplate);
for (const CString& sDir : vsDirs) {
m_Template.AppendPath(sDir);
}
m_bPathsSet = true;
}
void CWebSock::SetVars() {
m_Template["SessionUser"] = GetUser();
m_Template["SessionIP"] = GetRemoteIP();
m_Template["Tag"] = CZNC::GetTag(GetSession()->GetUser() != nullptr, true);
m_Template["Version"] = CZNC::GetVersion();
m_Template["SkinName"] = GetSkinName();
m_Template["_CSRF_Check"] = GetCSRFCheck();
m_Template["URIPrefix"] = GetURIPrefix();
if (GetSession()->IsAdmin()) {
m_Template["IsAdmin"] = "true";
}
GetSession()->FillMessageLoops(m_Template);
GetSession()->ClearMessageLoops();
// Global Mods
CModules& vgMods = CZNC::Get().GetModules();
for (CModule* pgMod : vgMods) {
AddModLoop("GlobalModLoop", *pgMod);
}
// User Mods
if (IsLoggedIn()) {
CModules& vMods = GetSession()->GetUser()->GetModules();
for (CModule* pMod : vMods) {
AddModLoop("UserModLoop", *pMod);
}
vector<CIRCNetwork*> vNetworks = GetSession()->GetUser()->GetNetworks();
for (CIRCNetwork* pNetwork : vNetworks) {
CModules& vnMods = pNetwork->GetModules();
CTemplate& Row = m_Template.AddRow("NetworkModLoop");
Row["NetworkName"] = pNetwork->GetName();
for (CModule* pnMod : vnMods) {
AddModLoop("ModLoop", *pnMod, &Row);
}
}
}
if (IsLoggedIn()) {
m_Template["LoggedIn"] = "true";
}
}
bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module,
CTemplate* pTemplate) {
if (!pTemplate) {
pTemplate = &m_Template;
}
CString sTitle(Module.GetWebMenuTitle());
if (!sTitle.empty() && (IsLoggedIn() || (!Module.WebRequiresLogin() &&
!Module.WebRequiresAdmin())) &&
(GetSession()->IsAdmin() || !Module.WebRequiresAdmin())) {
CTemplate& Row = pTemplate->AddRow(sLoopName);
bool bActiveModule = false;
Row["ModName"] = Module.GetModName();
Row["ModPath"] = Module.GetWebPath();
Row["Title"] = sTitle;
if (m_sModName == Module.GetModName()) {
CString sModuleType = GetPath().Token(1, false, "/");
if (sModuleType == "global" &&
Module.GetType() == CModInfo::GlobalModule) {
bActiveModule = true;
} else if (sModuleType == "user" &&
Module.GetType() == CModInfo::UserModule) {
bActiveModule = true;
} else if (sModuleType == "network" &&
Module.GetType() == CModInfo::NetworkModule) {
CIRCNetwork* Network = Module.GetNetwork();
if (Network) {
CString sNetworkName = GetPath().Token(2, false, "/");
if (sNetworkName == Network->GetName()) {
bActiveModule = true;
}
} else {
bActiveModule = true;
}
}
}
if (bActiveModule) {
Row["Active"] = "true";
}
if (Module.GetUser()) {
Row["Username"] = Module.GetUser()->GetUserName();
}
VWebSubPages& vSubPages = Module.GetSubPages();
for (TWebSubPage& SubPage : vSubPages) {
// bActive is whether or not the current url matches this subpage
// (params will be checked below)
bool bActive = (m_sModName == Module.GetModName() &&
m_sPage == SubPage->GetName() && bActiveModule);
if (SubPage->RequiresAdmin() && !GetSession()->IsAdmin()) {
// Don't add admin-only subpages to requests from non-admin
// users
continue;
}
CTemplate& SubRow = Row.AddRow("SubPageLoop");
SubRow["ModName"] = Module.GetModName();
SubRow["ModPath"] = Module.GetWebPath();
SubRow["PageName"] = SubPage->GetName();
SubRow["Title"] = SubPage->GetTitle().empty() ? SubPage->GetName()
: SubPage->GetTitle();
CString& sParams = SubRow["Params"];
const VPair& vParams = SubPage->GetParams();
for (const pair<CString, CString>& ssNV : vParams) {
if (!sParams.empty()) {
sParams += "&";
}
if (!ssNV.first.empty()) {
if (!ssNV.second.empty()) {
sParams += ssNV.first.Escape_n(CString::EURL);
sParams += "=";
sParams += ssNV.second.Escape_n(CString::EURL);
}
if (bActive && GetParam(ssNV.first, false) != ssNV.second) {
bActive = false;
}
}
}
if (bActive) {
SubRow["Active"] = "true";
}
}
return true;
}
return false;
}
CWebSock::EPageReqResult CWebSock::PrintStaticFile(const CString& sPath,
CString& sPageRet,
CModule* pModule) {
SetPaths(pModule);
CString sFile = m_Template.ExpandFile(sPath.TrimLeft_n("/"));
DEBUG("About to print [" + sFile + "]");
// Either PrintFile() fails and sends an error page or it succeeds and
// sends a result. In both cases we don't have anything more to do.
PrintFile(sFile);
return PAGE_DONE;
}
CWebSock::EPageReqResult CWebSock::PrintTemplate(const CString& sPageName,
CString& sPageRet,
CModule* pModule) {
SetVars();
m_Template["PageName"] = sPageName;
if (pModule) {
m_Template["ModName"] = pModule->GetModName();
if (m_Template.find("Title") == m_Template.end()) {
m_Template["Title"] = pModule->GetWebMenuTitle();
}
std::vector<CTemplate*>* breadcrumbs =
m_Template.GetLoop("BreadCrumbs");
if (breadcrumbs->size() == 1 &&
m_Template["Title"] != pModule->GetModName()) {
// Module didn't add its own breadcrumbs, so add a generic one...
// But it'll be useless if it's the same as module name
CTemplate& bread = m_Template.AddRow("BreadCrumbs");
bread["Text"] = m_Template["Title"];
}
}
if (!m_bPathsSet) {
SetPaths(pModule, true);
}
if (m_Template.GetFileName().empty() &&
!m_Template.SetFile(sPageName + ".tmpl")) {
return PAGE_NOTFOUND;
}
if (m_Template.PrintString(sPageRet)) {
return PAGE_PRINT;
} else {
return PAGE_NOTFOUND;
}
}
CString CWebSock::GetSkinPath(const CString& sSkinName) {
CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkinName;
if (!CFile::IsDir(sRet)) {
sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkinName;
if (!CFile::IsDir(sRet)) {
sRet = CString(_SKINDIR_) + "/" + sSkinName;
}
}
return sRet + "/";
}
bool CWebSock::ForceLogin() {
if (GetSession()->IsLoggedIn()) {
return true;
}
GetSession()->AddError("You must login to view that page");
Redirect("/");
return false;
}
CString CWebSock::GetRequestCookie(const CString& sKey) {
const CString sPrefixedKey = CString(GetLocalPort()) + "-" + sKey;
CString sRet;
if (!m_sModName.empty()) {
sRet = CHTTPSock::GetRequestCookie("Mod-" + m_sModName + "-" +
sPrefixedKey);
}
if (sRet.empty()) {
return CHTTPSock::GetRequestCookie(sPrefixedKey);
}
return sRet;
}
bool CWebSock::SendCookie(const CString& sKey, const CString& sValue) {
const CString sPrefixedKey = CString(GetLocalPort()) + "-" + sKey;
if (!m_sModName.empty()) {
return CHTTPSock::SendCookie("Mod-" + m_sModName + "-" + sPrefixedKey,
sValue);
}
return CHTTPSock::SendCookie(sPrefixedKey, sValue);
}
void CWebSock::OnPageRequest(const CString& sURI) {
CString sPageRet;
EPageReqResult eRet = OnPageRequestInternal(sURI, sPageRet);
switch (eRet) {
case PAGE_PRINT:
PrintPage(sPageRet);
break;
case PAGE_DEFERRED:
// Something else will later call Close()
break;
case PAGE_DONE:
// Redirect or something like that, it's done, just make sure
// the connection will be closed
Close(CLT_AFTERWRITE);
break;
case PAGE_NOTFOUND:
default:
PrintNotFound();
break;
}
}
CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI,
CString& sPageRet) {
// Check that their session really belongs to their IP address. IP-based
// authentication is bad, but here it's just an extra layer that makes
// stealing cookies harder to pull off.
//
// When their IP is wrong, we give them an invalid cookie. This makes
// sure that they will get a new cookie on their next request.
if (CZNC::Get().GetProtectWebSessions() &&
GetSession()->GetIP() != GetRemoteIP()) {
DEBUG("Expected IP: " << GetSession()->GetIP());
DEBUG("Remote IP: " << GetRemoteIP());
SendCookie("SessionId", "WRONG_IP_FOR_SESSION");
PrintErrorPage(403, "Access denied",
"This session does not belong to your IP.");
return PAGE_DONE;
}
// For pages *not provided* by modules, a CSRF check is performed which involves:
// Ensure that they really POSTed from one our forms by checking if they
// know the "secret" CSRF check value. Don't do this for login since
// CSRF against the login form makes no sense and the login form does a
// cookies-enabled check which would break otherwise.
// Don't do this, if user authenticated using http-basic auth, because:
// 1. they obviously know the password,
// 2. it's easier to automate some tasks e.g. user creation, without need to
// care about cookies and CSRF
if (IsPost() && !m_bBasicAuth && !sURI.StartsWith("/mods/") &&
!ValidateCSRFCheck(sURI)) {
DEBUG("Expected _CSRF_Check: " << GetCSRFCheck());
DEBUG("Actual _CSRF_Check: " << GetParam("_CSRF_Check"));
PrintErrorPage(
403, "Access denied",
"POST requests need to send "
"a secret token to prevent cross-site request forgery attacks.");
return PAGE_DONE;
}
SendCookie("SessionId", GetSession()->GetId());
if (GetSession()->IsLoggedIn()) {
m_sUser = GetSession()->GetUser()->GetUserName();
m_bLoggedIn = true;
}
CLanguageScope user_language(
m_bLoggedIn ? GetSession()->GetUser()->GetLanguage() : "");
// Handle the static pages that don't require a login
if (sURI == "/") {
if (!m_bLoggedIn && GetParam("cookie_check", false).ToBool() &&
GetRequestCookie("SessionId").empty()) {
GetSession()->AddError(
"Your browser does not have cookies enabled for this site!");
}
return PrintTemplate("index", sPageRet);
} else if (sURI == "/favicon.ico") {
return PrintStaticFile("/pub/favicon.ico", sPageRet);
} else if (sURI == "/robots.txt") {
return PrintStaticFile("/pub/robots.txt", sPageRet);
} else if (sURI == "/logout") {
GetSession()->SetUser(nullptr);
SetLoggedIn(false);
Redirect("/");
// We already sent a reply
return PAGE_DONE;
} else if (sURI == "/login") {
if (GetParam("submitted").ToBool()) {
m_sUser = GetParam("user");
m_sPass = GetParam("pass");
m_bLoggedIn = OnLogin(m_sUser, m_sPass, false);
// AcceptedLogin()/RefusedLogin() will call Redirect()
return PAGE_DEFERRED;
}
Redirect("/"); // the login form is here
return PAGE_DONE;
} else if (sURI.StartsWith("/pub/")) {
return PrintStaticFile(sURI, sPageRet);
} else if (sURI.StartsWith("/skinfiles/")) {
CString sSkinName = sURI.substr(11);
CString::size_type uPathStart = sSkinName.find("/");
if (uPathStart != CString::npos) {
CString sFilePath = sSkinName.substr(uPathStart + 1);
sSkinName.erase(uPathStart);
m_Template.ClearPaths();
m_Template.AppendPath(GetSkinPath(sSkinName) + "pub");
if (PrintFile(m_Template.ExpandFile(sFilePath))) {
return PAGE_DONE;
} else {
return PAGE_NOTFOUND;
}
}
return PAGE_NOTFOUND;
} else if (sURI.StartsWith("/mods/") || sURI.StartsWith("/modfiles/")) {
// Make sure modules are treated as directories
if (!sURI.EndsWith("/") && !sURI.Contains(".") &&
!sURI.TrimLeft_n("/mods/").TrimLeft_n("/").Contains("/")) {
Redirect(sURI + "/");
return PAGE_DONE;
}
// The URI looks like:
// /mods/[type]/([network]/)?[module][/page][?arg1=val1&arg2=val2...]
m_sPath = GetPath().TrimLeft_n("/");
m_sPath.TrimPrefix("mods/");
m_sPath.TrimPrefix("modfiles/");
CString sType = m_sPath.Token(0, false, "/");
m_sPath = m_sPath.Token(1, true, "/");
CModInfo::EModuleType eModType;
if (sType.Equals("global")) {
eModType = CModInfo::GlobalModule;
} else if (sType.Equals("user")) {
eModType = CModInfo::UserModule;
} else if (sType.Equals("network")) {
eModType = CModInfo::NetworkModule;
} else {
PrintErrorPage(403, "Forbidden",
"Unknown module type [" + sType + "]");
return PAGE_DONE;
}
if ((eModType != CModInfo::GlobalModule) && !ForceLogin()) {
// Make sure we have a valid user
return PAGE_DONE;
}
CIRCNetwork* pNetwork = nullptr;
if (eModType == CModInfo::NetworkModule) {
CString sNetwork = m_sPath.Token(0, false, "/");
m_sPath = m_sPath.Token(1, true, "/");
pNetwork = GetSession()->GetUser()->FindNetwork(sNetwork);
if (!pNetwork) {
PrintErrorPage(404, "Not Found",
"Network [" + sNetwork + "] not found.");
return PAGE_DONE;
}
}
m_sModName = m_sPath.Token(0, false, "/");
m_sPage = m_sPath.Token(1, true, "/");
if (m_sPage.empty()) {
m_sPage = "index";
}
DEBUG("Path [" + m_sPath + "], Module [" + m_sModName + "], Page [" +
m_sPage + "]");
CModule* pModule = nullptr;
switch (eModType) {
case CModInfo::GlobalModule:
pModule = CZNC::Get().GetModules().FindModule(m_sModName);
break;
case CModInfo::UserModule:
pModule = GetSession()->GetUser()->GetModules().FindModule(
m_sModName);
break;
case CModInfo::NetworkModule:
pModule = pNetwork->GetModules().FindModule(m_sModName);
break;
}
if (!pModule) return PAGE_NOTFOUND;
// Pass CSRF check to module.
// Note that the normal CSRF checks are not applied to /mods/ URLs.
if (IsPost() && !m_bBasicAuth &&
!pModule->ValidateWebRequestCSRFCheck(*this, m_sPage)) {
DEBUG("Expected _CSRF_Check: " << GetCSRFCheck());
DEBUG("Actual _CSRF_Check: " << GetParam("_CSRF_Check"));
PrintErrorPage(
403, "Access denied",
"POST requests need to send "
"a secret token to prevent cross-site request forgery attacks.");
return PAGE_DONE;
}
m_Template["ModPath"] = pModule->GetWebPath();
m_Template["ModFilesPath"] = pModule->GetWebFilesPath();
if (pModule->WebRequiresLogin() && !ForceLogin()) {
return PAGE_PRINT;
} else if (pModule->WebRequiresAdmin() && !GetSession()->IsAdmin()) {
PrintErrorPage(403, "Forbidden",
"You need to be an admin to access this module");
return PAGE_DONE;
} else if (pModule->GetType() != CModInfo::GlobalModule &&
pModule->GetUser() != GetSession()->GetUser()) {
PrintErrorPage(403, "Forbidden",
"You must login as " +
pModule->GetUser()->GetUserName() +
" in order to view this page");
return PAGE_DONE;
} else if (pModule->OnWebPreRequest(*this, m_sPage)) {
return PAGE_DEFERRED;
}
VWebSubPages& vSubPages = pModule->GetSubPages();
for (TWebSubPage& SubPage : vSubPages) {
bool bActive = (m_sModName == pModule->GetModName() &&
m_sPage == SubPage->GetName());
if (bActive && SubPage->RequiresAdmin() &&
!GetSession()->IsAdmin()) {
PrintErrorPage(403, "Forbidden",
"You need to be an admin to access this page");
return PAGE_DONE;
}
}
if (pModule && pModule->GetType() != CModInfo::GlobalModule &&
(!IsLoggedIn() || pModule->GetUser() != GetSession()->GetUser())) {
AddModLoop("UserModLoop", *pModule);
}
if (sURI.StartsWith("/modfiles/")) {
m_Template.AppendPath(GetSkinPath(GetSkinName()) + "/mods/" +
m_sModName + "/files/");
m_Template.AppendPath(pModule->GetModDataDir() + "/files/");
if (PrintFile(m_Template.ExpandFile(m_sPage.TrimLeft_n("/")))) {
return PAGE_PRINT;
} else {
return PAGE_NOTFOUND;
}
} else {
SetPaths(pModule, true);
CTemplate& breadModule = m_Template.AddRow("BreadCrumbs");
breadModule["Text"] = pModule->GetModName();
breadModule["URL"] = pModule->GetWebPath();
/* if a module returns false from OnWebRequest, it does not
want the template to be printed, usually because it did a
redirect. */
if (pModule->OnWebRequest(*this, m_sPage, m_Template)) {
// If they already sent a reply, let's assume
// they did what they wanted to do.
if (SentHeader()) {
return PAGE_DONE;
}
return PrintTemplate(m_sPage, sPageRet, pModule);
}
if (!SentHeader()) {
PrintErrorPage(
404, "Not Implemented",
"The requested module does not acknowledge web requests");
}
return PAGE_DONE;
}
} else {
CString sPage(sURI.Trim_n("/"));
if (sPage.length() < 32) {
for (unsigned int a = 0; a < sPage.length(); a++) {
unsigned char c = sPage[a];
if ((c < '0' || c > '9') && (c < 'a' || c > 'z') &&
(c < 'A' || c > 'Z') && c != '_') {
return PAGE_NOTFOUND;
}
}
return PrintTemplate(sPage, sPageRet);
}
}
return PAGE_NOTFOUND;
}
void CWebSock::PrintErrorPage(const CString& sMessage) {
m_Template.SetFile("Error.tmpl");
m_Template["Action"] = "error";
m_Template["Title"] = "Error";
m_Template["Error"] = sMessage;
}
static inline bool compareLastActive(
const std::pair<const CString, CWebSession*>& first,
const std::pair<const CString, CWebSession*>& second) {
return first.second->GetLastActive() < second.second->GetLastActive();
}
std::shared_ptr<CWebSession> CWebSock::GetSession() {
if (m_spSession) {
return m_spSession;
}
const CString sCookieSessionId = GetRequestCookie("SessionId");
std::shared_ptr<CWebSession>* pSession =
Sessions.m_mspSessions.GetItem(sCookieSessionId);
if (pSession != nullptr) {
// Refresh the timeout
Sessions.m_mspSessions.AddItem((*pSession)->GetId(), *pSession);
(*pSession)->UpdateLastActive();
m_spSession = *pSession;
DEBUG("Found existing session from cookie: [" + sCookieSessionId +
"] IsLoggedIn(" +
CString((*pSession)->IsLoggedIn()
? "true, " + ((*pSession)->GetUser()->GetUserName())
: "false") +
")");
return *pSession;
}
if (Sessions.m_mIPSessions.count(GetRemoteIP()) > m_uiMaxSessions) {
pair<mIPSessionsIterator, mIPSessionsIterator> p =
Sessions.m_mIPSessions.equal_range(GetRemoteIP());
mIPSessionsIterator it =
std::min_element(p.first, p.second, compareLastActive);
DEBUG("Remote IP: " << GetRemoteIP() << "; discarding session ["
<< it->second->GetId() << "]");
Sessions.m_mspSessions.RemItem(it->second->GetId());
}
CString sSessionID;
do {
sSessionID = CString::RandomString(32);
sSessionID += ":" + GetRemoteIP() + ":" + CString(GetRemotePort());
sSessionID += ":" + GetLocalIP() + ":" + CString(GetLocalPort());
sSessionID += ":" + CString(time(nullptr));
sSessionID = sSessionID.SHA256();
DEBUG("Auto generated session: [" + sSessionID + "]");
} while (Sessions.m_mspSessions.HasItem(sSessionID));
std::shared_ptr<CWebSession> spSession(
new CWebSession(sSessionID, GetRemoteIP()));
Sessions.m_mspSessions.AddItem(spSession->GetId(), spSession);
m_spSession = spSession;
return spSession;
}
CString CWebSock::GetCSRFCheck() {
std::shared_ptr<CWebSession> pSession = GetSession();
return pSession->GetId().MD5();
}
bool CWebSock::ValidateCSRFCheck(const CString& sURI) {
return sURI == "/login" || GetParam("_CSRF_Check") == GetCSRFCheck();
}
bool CWebSock::OnLogin(const CString& sUser, const CString& sPass,
bool bBasic) {
DEBUG("=================== CWebSock::OnLogin(), basic auth? "
<< std::boolalpha << bBasic);
m_spAuth = std::make_shared<CWebAuth>(this, sUser, sPass, bBasic);
// Some authentication module could need some time, block this socket
// until then. CWebAuth will UnPauseRead().
PauseRead();
CZNC::Get().AuthUser(m_spAuth);
// If CWebAuth already set this, don't change it.
return IsLoggedIn();
}
Csock* CWebSock::GetSockObj(const CString& sHost, unsigned short uPort) {
// All listening is done by CListener, thus CWebSock should never have
// to listen, but since GetSockObj() is pure virtual...
DEBUG("CWebSock::GetSockObj() called - this should never happen!");
return nullptr;
}
CString CWebSock::GetSkinName() {
std::shared_ptr<CWebSession> spSession = GetSession();
if (spSession->IsLoggedIn() &&
!spSession->GetUser()->GetSkinName().empty()) {
return spSession->GetUser()->GetSkinName();
}
return CZNC::Get().GetSkinName();
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_240_0 |
crossvul-cpp_data_good_240_0 | /*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/WebModules.h>
#include <znc/FileUtils.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/znc.h>
#include <time.h>
#include <algorithm>
#include <sstream>
using std::pair;
using std::vector;
/// @todo Do we want to make this a configure option?
#define _SKINDIR_ _DATADIR_ "/webskins"
const unsigned int CWebSock::m_uiMaxSessions = 5;
// We need this class to make sure the contained maps and their content is
// destroyed in the order that we want.
struct CSessionManager {
// Sessions are valid for a day, (24h, ...)
CSessionManager() : m_mspSessions(24 * 60 * 60 * 1000), m_mIPSessions() {}
~CSessionManager() {
// Make sure all sessions are destroyed before any of our maps
// are destroyed
m_mspSessions.Clear();
}
CWebSessionMap m_mspSessions;
std::multimap<CString, CWebSession*> m_mIPSessions;
};
typedef std::multimap<CString, CWebSession*>::iterator mIPSessionsIterator;
static CSessionManager Sessions;
class CWebAuth : public CAuthBase {
public:
CWebAuth(CWebSock* pWebSock, const CString& sUsername,
const CString& sPassword, bool bBasic);
~CWebAuth() override {}
CWebAuth(const CWebAuth&) = delete;
CWebAuth& operator=(const CWebAuth&) = delete;
void SetWebSock(CWebSock* pWebSock) { m_pWebSock = pWebSock; }
void AcceptedLogin(CUser& User) override;
void RefusedLogin(const CString& sReason) override;
void Invalidate() override;
private:
protected:
CWebSock* m_pWebSock;
bool m_bBasic;
};
void CWebSock::FinishUserSessions(const CUser& User) {
Sessions.m_mspSessions.FinishUserSessions(User);
}
CWebSession::~CWebSession() {
// Find our entry in mIPSessions
pair<mIPSessionsIterator, mIPSessionsIterator> p =
Sessions.m_mIPSessions.equal_range(m_sIP);
mIPSessionsIterator it = p.first;
mIPSessionsIterator end = p.second;
while (it != end) {
if (it->second == this) {
Sessions.m_mIPSessions.erase(it++);
} else {
++it;
}
}
}
CZNCTagHandler::CZNCTagHandler(CWebSock& WebSock)
: CTemplateTagHandler(), m_WebSock(WebSock) {}
bool CZNCTagHandler::HandleTag(CTemplate& Tmpl, const CString& sName,
const CString& sArgs, CString& sOutput) {
if (sName.Equals("URLPARAM")) {
// sOutput = CZNC::Get()
sOutput = m_WebSock.GetParam(sArgs.Token(0), false);
return true;
}
return false;
}
CWebSession::CWebSession(const CString& sId, const CString& sIP)
: m_sId(sId),
m_sIP(sIP),
m_pUser(nullptr),
m_vsErrorMsgs(),
m_vsSuccessMsgs(),
m_tmLastActive() {
Sessions.m_mIPSessions.insert(make_pair(sIP, this));
UpdateLastActive();
}
void CWebSession::UpdateLastActive() { time(&m_tmLastActive); }
bool CWebSession::IsAdmin() const { return IsLoggedIn() && m_pUser->IsAdmin(); }
CWebAuth::CWebAuth(CWebSock* pWebSock, const CString& sUsername,
const CString& sPassword, bool bBasic)
: CAuthBase(sUsername, sPassword, pWebSock),
m_pWebSock(pWebSock),
m_bBasic(bBasic) {}
void CWebSession::ClearMessageLoops() {
m_vsErrorMsgs.clear();
m_vsSuccessMsgs.clear();
}
void CWebSession::FillMessageLoops(CTemplate& Tmpl) {
for (const CString& sMessage : m_vsErrorMsgs) {
CTemplate& Row = Tmpl.AddRow("ErrorLoop");
Row["Message"] = sMessage;
}
for (const CString& sMessage : m_vsSuccessMsgs) {
CTemplate& Row = Tmpl.AddRow("SuccessLoop");
Row["Message"] = sMessage;
}
}
size_t CWebSession::AddError(const CString& sMessage) {
m_vsErrorMsgs.push_back(sMessage);
return m_vsErrorMsgs.size();
}
size_t CWebSession::AddSuccess(const CString& sMessage) {
m_vsSuccessMsgs.push_back(sMessage);
return m_vsSuccessMsgs.size();
}
void CWebSessionMap::FinishUserSessions(const CUser& User) {
iterator it = m_mItems.begin();
while (it != m_mItems.end()) {
if (it->second.second->GetUser() == &User) {
m_mItems.erase(it++);
} else {
++it;
}
}
}
void CWebAuth::AcceptedLogin(CUser& User) {
if (m_pWebSock) {
std::shared_ptr<CWebSession> spSession = m_pWebSock->GetSession();
spSession->SetUser(&User);
m_pWebSock->SetLoggedIn(true);
m_pWebSock->UnPauseRead();
if (m_bBasic) {
m_pWebSock->ReadLine("");
} else {
m_pWebSock->Redirect("/?cookie_check=true");
}
DEBUG("Successful login attempt ==> USER [" + User.GetUserName() +
"] ==> SESSION [" + spSession->GetId() + "]");
}
}
void CWebAuth::RefusedLogin(const CString& sReason) {
if (m_pWebSock) {
std::shared_ptr<CWebSession> spSession = m_pWebSock->GetSession();
spSession->AddError("Invalid login!");
spSession->SetUser(nullptr);
m_pWebSock->SetLoggedIn(false);
m_pWebSock->UnPauseRead();
if (m_bBasic) {
m_pWebSock->AddHeader("WWW-Authenticate", "Basic realm=\"ZNC\"");
m_pWebSock->CHTTPSock::PrintErrorPage(
401, "Unauthorized",
"HTTP Basic authentication attempted with invalid credentials");
// Why CWebSock makes this function protected?..
} else {
m_pWebSock->Redirect("/?cookie_check=true");
}
DEBUG("UNSUCCESSFUL login attempt ==> REASON [" + sReason +
"] ==> SESSION [" + spSession->GetId() + "]");
}
}
void CWebAuth::Invalidate() {
CAuthBase::Invalidate();
m_pWebSock = nullptr;
}
CWebSock::CWebSock(const CString& sURIPrefix)
: CHTTPSock(nullptr, sURIPrefix),
m_bPathsSet(false),
m_Template(),
m_spAuth(),
m_sModName(""),
m_sPath(""),
m_sPage(""),
m_spSession() {
m_Template.AddTagHandler(std::make_shared<CZNCTagHandler>(*this));
}
CWebSock::~CWebSock() {
if (m_spAuth) {
m_spAuth->Invalidate();
}
// we have to account for traffic here because CSocket does
// not have a valid CModule* pointer.
CUser* pUser = GetSession()->GetUser();
if (pUser) {
pUser->AddBytesWritten(GetBytesWritten());
pUser->AddBytesRead(GetBytesRead());
} else {
CZNC::Get().AddBytesWritten(GetBytesWritten());
CZNC::Get().AddBytesRead(GetBytesRead());
}
// bytes have been accounted for, so make sure they don't get again:
ResetBytesWritten();
ResetBytesRead();
}
void CWebSock::GetAvailSkins(VCString& vRet) const {
vRet.clear();
CString sRoot(GetSkinPath("_default_"));
sRoot.TrimRight("/");
sRoot.TrimRight("_default_");
sRoot.TrimRight("/");
if (!sRoot.empty()) {
sRoot += "/";
}
if (!sRoot.empty() && CFile::IsDir(sRoot)) {
CDir Dir(sRoot);
for (const CFile* pSubDir : Dir) {
if (pSubDir->IsDir() && pSubDir->GetShortName() == "_default_") {
vRet.push_back(pSubDir->GetShortName());
break;
}
}
for (const CFile* pSubDir : Dir) {
if (pSubDir->IsDir() && pSubDir->GetShortName() != "_default_" &&
pSubDir->GetShortName() != ".svn") {
vRet.push_back(pSubDir->GetShortName());
}
}
}
}
VCString CWebSock::GetDirs(CModule* pModule, bool bIsTemplate) {
CString sHomeSkinsDir(CZNC::Get().GetZNCPath() + "/webskins/");
CString sSkinName(GetSkinName());
VCString vsResult;
// Module specific paths
if (pModule) {
const CString& sModName(pModule->GetModName());
// 1. ~/.znc/webskins/<user_skin_setting>/mods/<mod_name>/
//
if (!sSkinName.empty()) {
vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName +
"/");
}
// 2. ~/.znc/webskins/_default_/mods/<mod_name>/
//
vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName +
"/");
// 3. ./modules/<mod_name>/tmpl/
//
vsResult.push_back(pModule->GetModDataDir() + "/tmpl/");
// 4. ~/.znc/webskins/<user_skin_setting>/mods/<mod_name>/
//
if (!sSkinName.empty()) {
vsResult.push_back(GetSkinPath(sSkinName) + "/mods/" + sModName +
"/");
}
// 5. ~/.znc/webskins/_default_/mods/<mod_name>/
//
vsResult.push_back(GetSkinPath("_default_") + "/mods/" + sModName +
"/");
}
// 6. ~/.znc/webskins/<user_skin_setting>/
//
if (!sSkinName.empty()) {
vsResult.push_back(GetSkinPath(sSkinName) +
CString(bIsTemplate ? "/tmpl/" : "/"));
}
// 7. ~/.znc/webskins/_default_/
//
vsResult.push_back(GetSkinPath("_default_") +
CString(bIsTemplate ? "/tmpl/" : "/"));
return vsResult;
}
CString CWebSock::FindTmpl(CModule* pModule, const CString& sName) {
VCString vsDirs = GetDirs(pModule, true);
CString sFile = pModule->GetModName() + "_" + sName;
for (const CString& sDir : vsDirs) {
if (CFile::Exists(CDir::ChangeDir(sDir, sFile))) {
m_Template.AppendPath(sDir);
return sFile;
}
}
return sName;
}
void CWebSock::SetPaths(CModule* pModule, bool bIsTemplate) {
m_Template.ClearPaths();
VCString vsDirs = GetDirs(pModule, bIsTemplate);
for (const CString& sDir : vsDirs) {
m_Template.AppendPath(sDir);
}
m_bPathsSet = true;
}
void CWebSock::SetVars() {
m_Template["SessionUser"] = GetUser();
m_Template["SessionIP"] = GetRemoteIP();
m_Template["Tag"] = CZNC::GetTag(GetSession()->GetUser() != nullptr, true);
m_Template["Version"] = CZNC::GetVersion();
m_Template["SkinName"] = GetSkinName();
m_Template["_CSRF_Check"] = GetCSRFCheck();
m_Template["URIPrefix"] = GetURIPrefix();
if (GetSession()->IsAdmin()) {
m_Template["IsAdmin"] = "true";
}
GetSession()->FillMessageLoops(m_Template);
GetSession()->ClearMessageLoops();
// Global Mods
CModules& vgMods = CZNC::Get().GetModules();
for (CModule* pgMod : vgMods) {
AddModLoop("GlobalModLoop", *pgMod);
}
// User Mods
if (IsLoggedIn()) {
CModules& vMods = GetSession()->GetUser()->GetModules();
for (CModule* pMod : vMods) {
AddModLoop("UserModLoop", *pMod);
}
vector<CIRCNetwork*> vNetworks = GetSession()->GetUser()->GetNetworks();
for (CIRCNetwork* pNetwork : vNetworks) {
CModules& vnMods = pNetwork->GetModules();
CTemplate& Row = m_Template.AddRow("NetworkModLoop");
Row["NetworkName"] = pNetwork->GetName();
for (CModule* pnMod : vnMods) {
AddModLoop("ModLoop", *pnMod, &Row);
}
}
}
if (IsLoggedIn()) {
m_Template["LoggedIn"] = "true";
}
}
bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module,
CTemplate* pTemplate) {
if (!pTemplate) {
pTemplate = &m_Template;
}
CString sTitle(Module.GetWebMenuTitle());
if (!sTitle.empty() && (IsLoggedIn() || (!Module.WebRequiresLogin() &&
!Module.WebRequiresAdmin())) &&
(GetSession()->IsAdmin() || !Module.WebRequiresAdmin())) {
CTemplate& Row = pTemplate->AddRow(sLoopName);
bool bActiveModule = false;
Row["ModName"] = Module.GetModName();
Row["ModPath"] = Module.GetWebPath();
Row["Title"] = sTitle;
if (m_sModName == Module.GetModName()) {
CString sModuleType = GetPath().Token(1, false, "/");
if (sModuleType == "global" &&
Module.GetType() == CModInfo::GlobalModule) {
bActiveModule = true;
} else if (sModuleType == "user" &&
Module.GetType() == CModInfo::UserModule) {
bActiveModule = true;
} else if (sModuleType == "network" &&
Module.GetType() == CModInfo::NetworkModule) {
CIRCNetwork* Network = Module.GetNetwork();
if (Network) {
CString sNetworkName = GetPath().Token(2, false, "/");
if (sNetworkName == Network->GetName()) {
bActiveModule = true;
}
} else {
bActiveModule = true;
}
}
}
if (bActiveModule) {
Row["Active"] = "true";
}
if (Module.GetUser()) {
Row["Username"] = Module.GetUser()->GetUserName();
}
VWebSubPages& vSubPages = Module.GetSubPages();
for (TWebSubPage& SubPage : vSubPages) {
// bActive is whether or not the current url matches this subpage
// (params will be checked below)
bool bActive = (m_sModName == Module.GetModName() &&
m_sPage == SubPage->GetName() && bActiveModule);
if (SubPage->RequiresAdmin() && !GetSession()->IsAdmin()) {
// Don't add admin-only subpages to requests from non-admin
// users
continue;
}
CTemplate& SubRow = Row.AddRow("SubPageLoop");
SubRow["ModName"] = Module.GetModName();
SubRow["ModPath"] = Module.GetWebPath();
SubRow["PageName"] = SubPage->GetName();
SubRow["Title"] = SubPage->GetTitle().empty() ? SubPage->GetName()
: SubPage->GetTitle();
CString& sParams = SubRow["Params"];
const VPair& vParams = SubPage->GetParams();
for (const pair<CString, CString>& ssNV : vParams) {
if (!sParams.empty()) {
sParams += "&";
}
if (!ssNV.first.empty()) {
if (!ssNV.second.empty()) {
sParams += ssNV.first.Escape_n(CString::EURL);
sParams += "=";
sParams += ssNV.second.Escape_n(CString::EURL);
}
if (bActive && GetParam(ssNV.first, false) != ssNV.second) {
bActive = false;
}
}
}
if (bActive) {
SubRow["Active"] = "true";
}
}
return true;
}
return false;
}
CWebSock::EPageReqResult CWebSock::PrintStaticFile(const CString& sPath,
CString& sPageRet,
CModule* pModule) {
SetPaths(pModule);
CString sFile = m_Template.ExpandFile(sPath.TrimLeft_n("/"));
DEBUG("About to print [" + sFile + "]");
// Either PrintFile() fails and sends an error page or it succeeds and
// sends a result. In both cases we don't have anything more to do.
PrintFile(sFile);
return PAGE_DONE;
}
CWebSock::EPageReqResult CWebSock::PrintTemplate(const CString& sPageName,
CString& sPageRet,
CModule* pModule) {
SetVars();
m_Template["PageName"] = sPageName;
if (pModule) {
m_Template["ModName"] = pModule->GetModName();
if (m_Template.find("Title") == m_Template.end()) {
m_Template["Title"] = pModule->GetWebMenuTitle();
}
std::vector<CTemplate*>* breadcrumbs =
m_Template.GetLoop("BreadCrumbs");
if (breadcrumbs->size() == 1 &&
m_Template["Title"] != pModule->GetModName()) {
// Module didn't add its own breadcrumbs, so add a generic one...
// But it'll be useless if it's the same as module name
CTemplate& bread = m_Template.AddRow("BreadCrumbs");
bread["Text"] = m_Template["Title"];
}
}
if (!m_bPathsSet) {
SetPaths(pModule, true);
}
if (m_Template.GetFileName().empty() &&
!m_Template.SetFile(sPageName + ".tmpl")) {
return PAGE_NOTFOUND;
}
if (m_Template.PrintString(sPageRet)) {
return PAGE_PRINT;
} else {
return PAGE_NOTFOUND;
}
}
CString CWebSock::GetSkinPath(const CString& sSkinName) {
const CString sSkin = sSkinName.Replace_n("/", "_").Replace_n(".", "_");
CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkin;
if (!CFile::IsDir(sRet)) {
sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkin;
if (!CFile::IsDir(sRet)) {
sRet = CString(_SKINDIR_) + "/" + sSkin;
}
}
return sRet + "/";
}
bool CWebSock::ForceLogin() {
if (GetSession()->IsLoggedIn()) {
return true;
}
GetSession()->AddError("You must login to view that page");
Redirect("/");
return false;
}
CString CWebSock::GetRequestCookie(const CString& sKey) {
const CString sPrefixedKey = CString(GetLocalPort()) + "-" + sKey;
CString sRet;
if (!m_sModName.empty()) {
sRet = CHTTPSock::GetRequestCookie("Mod-" + m_sModName + "-" +
sPrefixedKey);
}
if (sRet.empty()) {
return CHTTPSock::GetRequestCookie(sPrefixedKey);
}
return sRet;
}
bool CWebSock::SendCookie(const CString& sKey, const CString& sValue) {
const CString sPrefixedKey = CString(GetLocalPort()) + "-" + sKey;
if (!m_sModName.empty()) {
return CHTTPSock::SendCookie("Mod-" + m_sModName + "-" + sPrefixedKey,
sValue);
}
return CHTTPSock::SendCookie(sPrefixedKey, sValue);
}
void CWebSock::OnPageRequest(const CString& sURI) {
CString sPageRet;
EPageReqResult eRet = OnPageRequestInternal(sURI, sPageRet);
switch (eRet) {
case PAGE_PRINT:
PrintPage(sPageRet);
break;
case PAGE_DEFERRED:
// Something else will later call Close()
break;
case PAGE_DONE:
// Redirect or something like that, it's done, just make sure
// the connection will be closed
Close(CLT_AFTERWRITE);
break;
case PAGE_NOTFOUND:
default:
PrintNotFound();
break;
}
}
CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI,
CString& sPageRet) {
// Check that their session really belongs to their IP address. IP-based
// authentication is bad, but here it's just an extra layer that makes
// stealing cookies harder to pull off.
//
// When their IP is wrong, we give them an invalid cookie. This makes
// sure that they will get a new cookie on their next request.
if (CZNC::Get().GetProtectWebSessions() &&
GetSession()->GetIP() != GetRemoteIP()) {
DEBUG("Expected IP: " << GetSession()->GetIP());
DEBUG("Remote IP: " << GetRemoteIP());
SendCookie("SessionId", "WRONG_IP_FOR_SESSION");
PrintErrorPage(403, "Access denied",
"This session does not belong to your IP.");
return PAGE_DONE;
}
// For pages *not provided* by modules, a CSRF check is performed which involves:
// Ensure that they really POSTed from one our forms by checking if they
// know the "secret" CSRF check value. Don't do this for login since
// CSRF against the login form makes no sense and the login form does a
// cookies-enabled check which would break otherwise.
// Don't do this, if user authenticated using http-basic auth, because:
// 1. they obviously know the password,
// 2. it's easier to automate some tasks e.g. user creation, without need to
// care about cookies and CSRF
if (IsPost() && !m_bBasicAuth && !sURI.StartsWith("/mods/") &&
!ValidateCSRFCheck(sURI)) {
DEBUG("Expected _CSRF_Check: " << GetCSRFCheck());
DEBUG("Actual _CSRF_Check: " << GetParam("_CSRF_Check"));
PrintErrorPage(
403, "Access denied",
"POST requests need to send "
"a secret token to prevent cross-site request forgery attacks.");
return PAGE_DONE;
}
SendCookie("SessionId", GetSession()->GetId());
if (GetSession()->IsLoggedIn()) {
m_sUser = GetSession()->GetUser()->GetUserName();
m_bLoggedIn = true;
}
CLanguageScope user_language(
m_bLoggedIn ? GetSession()->GetUser()->GetLanguage() : "");
// Handle the static pages that don't require a login
if (sURI == "/") {
if (!m_bLoggedIn && GetParam("cookie_check", false).ToBool() &&
GetRequestCookie("SessionId").empty()) {
GetSession()->AddError(
"Your browser does not have cookies enabled for this site!");
}
return PrintTemplate("index", sPageRet);
} else if (sURI == "/favicon.ico") {
return PrintStaticFile("/pub/favicon.ico", sPageRet);
} else if (sURI == "/robots.txt") {
return PrintStaticFile("/pub/robots.txt", sPageRet);
} else if (sURI == "/logout") {
GetSession()->SetUser(nullptr);
SetLoggedIn(false);
Redirect("/");
// We already sent a reply
return PAGE_DONE;
} else if (sURI == "/login") {
if (GetParam("submitted").ToBool()) {
m_sUser = GetParam("user");
m_sPass = GetParam("pass");
m_bLoggedIn = OnLogin(m_sUser, m_sPass, false);
// AcceptedLogin()/RefusedLogin() will call Redirect()
return PAGE_DEFERRED;
}
Redirect("/"); // the login form is here
return PAGE_DONE;
} else if (sURI.StartsWith("/pub/")) {
return PrintStaticFile(sURI, sPageRet);
} else if (sURI.StartsWith("/skinfiles/")) {
CString sSkinName = sURI.substr(11);
CString::size_type uPathStart = sSkinName.find("/");
if (uPathStart != CString::npos) {
CString sFilePath = sSkinName.substr(uPathStart + 1);
sSkinName.erase(uPathStart);
m_Template.ClearPaths();
m_Template.AppendPath(GetSkinPath(sSkinName) + "pub");
if (PrintFile(m_Template.ExpandFile(sFilePath))) {
return PAGE_DONE;
} else {
return PAGE_NOTFOUND;
}
}
return PAGE_NOTFOUND;
} else if (sURI.StartsWith("/mods/") || sURI.StartsWith("/modfiles/")) {
// Make sure modules are treated as directories
if (!sURI.EndsWith("/") && !sURI.Contains(".") &&
!sURI.TrimLeft_n("/mods/").TrimLeft_n("/").Contains("/")) {
Redirect(sURI + "/");
return PAGE_DONE;
}
// The URI looks like:
// /mods/[type]/([network]/)?[module][/page][?arg1=val1&arg2=val2...]
m_sPath = GetPath().TrimLeft_n("/");
m_sPath.TrimPrefix("mods/");
m_sPath.TrimPrefix("modfiles/");
CString sType = m_sPath.Token(0, false, "/");
m_sPath = m_sPath.Token(1, true, "/");
CModInfo::EModuleType eModType;
if (sType.Equals("global")) {
eModType = CModInfo::GlobalModule;
} else if (sType.Equals("user")) {
eModType = CModInfo::UserModule;
} else if (sType.Equals("network")) {
eModType = CModInfo::NetworkModule;
} else {
PrintErrorPage(403, "Forbidden",
"Unknown module type [" + sType + "]");
return PAGE_DONE;
}
if ((eModType != CModInfo::GlobalModule) && !ForceLogin()) {
// Make sure we have a valid user
return PAGE_DONE;
}
CIRCNetwork* pNetwork = nullptr;
if (eModType == CModInfo::NetworkModule) {
CString sNetwork = m_sPath.Token(0, false, "/");
m_sPath = m_sPath.Token(1, true, "/");
pNetwork = GetSession()->GetUser()->FindNetwork(sNetwork);
if (!pNetwork) {
PrintErrorPage(404, "Not Found",
"Network [" + sNetwork + "] not found.");
return PAGE_DONE;
}
}
m_sModName = m_sPath.Token(0, false, "/");
m_sPage = m_sPath.Token(1, true, "/");
if (m_sPage.empty()) {
m_sPage = "index";
}
DEBUG("Path [" + m_sPath + "], Module [" + m_sModName + "], Page [" +
m_sPage + "]");
CModule* pModule = nullptr;
switch (eModType) {
case CModInfo::GlobalModule:
pModule = CZNC::Get().GetModules().FindModule(m_sModName);
break;
case CModInfo::UserModule:
pModule = GetSession()->GetUser()->GetModules().FindModule(
m_sModName);
break;
case CModInfo::NetworkModule:
pModule = pNetwork->GetModules().FindModule(m_sModName);
break;
}
if (!pModule) return PAGE_NOTFOUND;
// Pass CSRF check to module.
// Note that the normal CSRF checks are not applied to /mods/ URLs.
if (IsPost() && !m_bBasicAuth &&
!pModule->ValidateWebRequestCSRFCheck(*this, m_sPage)) {
DEBUG("Expected _CSRF_Check: " << GetCSRFCheck());
DEBUG("Actual _CSRF_Check: " << GetParam("_CSRF_Check"));
PrintErrorPage(
403, "Access denied",
"POST requests need to send "
"a secret token to prevent cross-site request forgery attacks.");
return PAGE_DONE;
}
m_Template["ModPath"] = pModule->GetWebPath();
m_Template["ModFilesPath"] = pModule->GetWebFilesPath();
if (pModule->WebRequiresLogin() && !ForceLogin()) {
return PAGE_PRINT;
} else if (pModule->WebRequiresAdmin() && !GetSession()->IsAdmin()) {
PrintErrorPage(403, "Forbidden",
"You need to be an admin to access this module");
return PAGE_DONE;
} else if (pModule->GetType() != CModInfo::GlobalModule &&
pModule->GetUser() != GetSession()->GetUser()) {
PrintErrorPage(403, "Forbidden",
"You must login as " +
pModule->GetUser()->GetUserName() +
" in order to view this page");
return PAGE_DONE;
} else if (pModule->OnWebPreRequest(*this, m_sPage)) {
return PAGE_DEFERRED;
}
VWebSubPages& vSubPages = pModule->GetSubPages();
for (TWebSubPage& SubPage : vSubPages) {
bool bActive = (m_sModName == pModule->GetModName() &&
m_sPage == SubPage->GetName());
if (bActive && SubPage->RequiresAdmin() &&
!GetSession()->IsAdmin()) {
PrintErrorPage(403, "Forbidden",
"You need to be an admin to access this page");
return PAGE_DONE;
}
}
if (pModule && pModule->GetType() != CModInfo::GlobalModule &&
(!IsLoggedIn() || pModule->GetUser() != GetSession()->GetUser())) {
AddModLoop("UserModLoop", *pModule);
}
if (sURI.StartsWith("/modfiles/")) {
m_Template.AppendPath(GetSkinPath(GetSkinName()) + "/mods/" +
m_sModName + "/files/");
m_Template.AppendPath(pModule->GetModDataDir() + "/files/");
if (PrintFile(m_Template.ExpandFile(m_sPage.TrimLeft_n("/")))) {
return PAGE_PRINT;
} else {
return PAGE_NOTFOUND;
}
} else {
SetPaths(pModule, true);
CTemplate& breadModule = m_Template.AddRow("BreadCrumbs");
breadModule["Text"] = pModule->GetModName();
breadModule["URL"] = pModule->GetWebPath();
/* if a module returns false from OnWebRequest, it does not
want the template to be printed, usually because it did a
redirect. */
if (pModule->OnWebRequest(*this, m_sPage, m_Template)) {
// If they already sent a reply, let's assume
// they did what they wanted to do.
if (SentHeader()) {
return PAGE_DONE;
}
return PrintTemplate(m_sPage, sPageRet, pModule);
}
if (!SentHeader()) {
PrintErrorPage(
404, "Not Implemented",
"The requested module does not acknowledge web requests");
}
return PAGE_DONE;
}
} else {
CString sPage(sURI.Trim_n("/"));
if (sPage.length() < 32) {
for (unsigned int a = 0; a < sPage.length(); a++) {
unsigned char c = sPage[a];
if ((c < '0' || c > '9') && (c < 'a' || c > 'z') &&
(c < 'A' || c > 'Z') && c != '_') {
return PAGE_NOTFOUND;
}
}
return PrintTemplate(sPage, sPageRet);
}
}
return PAGE_NOTFOUND;
}
void CWebSock::PrintErrorPage(const CString& sMessage) {
m_Template.SetFile("Error.tmpl");
m_Template["Action"] = "error";
m_Template["Title"] = "Error";
m_Template["Error"] = sMessage;
}
static inline bool compareLastActive(
const std::pair<const CString, CWebSession*>& first,
const std::pair<const CString, CWebSession*>& second) {
return first.second->GetLastActive() < second.second->GetLastActive();
}
std::shared_ptr<CWebSession> CWebSock::GetSession() {
if (m_spSession) {
return m_spSession;
}
const CString sCookieSessionId = GetRequestCookie("SessionId");
std::shared_ptr<CWebSession>* pSession =
Sessions.m_mspSessions.GetItem(sCookieSessionId);
if (pSession != nullptr) {
// Refresh the timeout
Sessions.m_mspSessions.AddItem((*pSession)->GetId(), *pSession);
(*pSession)->UpdateLastActive();
m_spSession = *pSession;
DEBUG("Found existing session from cookie: [" + sCookieSessionId +
"] IsLoggedIn(" +
CString((*pSession)->IsLoggedIn()
? "true, " + ((*pSession)->GetUser()->GetUserName())
: "false") +
")");
return *pSession;
}
if (Sessions.m_mIPSessions.count(GetRemoteIP()) > m_uiMaxSessions) {
pair<mIPSessionsIterator, mIPSessionsIterator> p =
Sessions.m_mIPSessions.equal_range(GetRemoteIP());
mIPSessionsIterator it =
std::min_element(p.first, p.second, compareLastActive);
DEBUG("Remote IP: " << GetRemoteIP() << "; discarding session ["
<< it->second->GetId() << "]");
Sessions.m_mspSessions.RemItem(it->second->GetId());
}
CString sSessionID;
do {
sSessionID = CString::RandomString(32);
sSessionID += ":" + GetRemoteIP() + ":" + CString(GetRemotePort());
sSessionID += ":" + GetLocalIP() + ":" + CString(GetLocalPort());
sSessionID += ":" + CString(time(nullptr));
sSessionID = sSessionID.SHA256();
DEBUG("Auto generated session: [" + sSessionID + "]");
} while (Sessions.m_mspSessions.HasItem(sSessionID));
std::shared_ptr<CWebSession> spSession(
new CWebSession(sSessionID, GetRemoteIP()));
Sessions.m_mspSessions.AddItem(spSession->GetId(), spSession);
m_spSession = spSession;
return spSession;
}
CString CWebSock::GetCSRFCheck() {
std::shared_ptr<CWebSession> pSession = GetSession();
return pSession->GetId().MD5();
}
bool CWebSock::ValidateCSRFCheck(const CString& sURI) {
return sURI == "/login" || GetParam("_CSRF_Check") == GetCSRFCheck();
}
bool CWebSock::OnLogin(const CString& sUser, const CString& sPass,
bool bBasic) {
DEBUG("=================== CWebSock::OnLogin(), basic auth? "
<< std::boolalpha << bBasic);
m_spAuth = std::make_shared<CWebAuth>(this, sUser, sPass, bBasic);
// Some authentication module could need some time, block this socket
// until then. CWebAuth will UnPauseRead().
PauseRead();
CZNC::Get().AuthUser(m_spAuth);
// If CWebAuth already set this, don't change it.
return IsLoggedIn();
}
Csock* CWebSock::GetSockObj(const CString& sHost, unsigned short uPort) {
// All listening is done by CListener, thus CWebSock should never have
// to listen, but since GetSockObj() is pure virtual...
DEBUG("CWebSock::GetSockObj() called - this should never happen!");
return nullptr;
}
CString CWebSock::GetSkinName() {
std::shared_ptr<CWebSession> spSession = GetSession();
if (spSession->IsLoggedIn() &&
!spSession->GetUser()->GetSkinName().empty()) {
return spSession->GetUser()->GetSkinName();
}
return CZNC::Get().GetSkinName();
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_240_0 |
crossvul-cpp_data_good_973_0 | /************************************************************************
**
** Copyright (C) 2016 - 2019 Kevin B. Hendricks, Stratford, Ontario, Canada
** Copyright (C) 2012 John Schember <john@nachtimwald.com>
** Copyright (C) 2009, 2010, 2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil 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.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#ifdef _WIN32
#define NOMINMAX
#endif
#include "unzip.h"
#ifdef _WIN32
#include "iowin32.h"
#endif
#include <string>
#include <QApplication>
#include <QtCore/QtCore>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QFutureSynchronizer>
#include <QtConcurrent/QtConcurrent>
#include <QtCore/QXmlStreamReader>
#include <QDirIterator>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QStringList>
#include <QMessageBox>
#include <QUrl>
#include "BookManipulation/FolderKeeper.h"
#include "BookManipulation/CleanSource.h"
#include "Importers/ImportEPUB.h"
#include "Misc/FontObfuscation.h"
#include "Misc/HTMLEncodingResolver.h"
#include "Misc/QCodePage437Codec.h"
#include "Misc/SettingsStore.h"
#include "Misc/Utility.h"
#include "ResourceObjects/CSSResource.h"
#include "ResourceObjects/HTMLResource.h"
#include "ResourceObjects/OPFResource.h"
#include "ResourceObjects/NCXResource.h"
#include "ResourceObjects/Resource.h"
#include "ResourceObjects/OPFParser.h"
#include "SourceUpdates/UniversalUpdates.h"
#include "sigil_constants.h"
#include "sigil_exception.h"
#ifndef MAX_PATH
// Set Max length to 256 because that's the max path size on many systems.
#define MAX_PATH 256
#endif
// This is the same read buffer size used by Java and Perl.
#define BUFF_SIZE 8192
const QString DUBLIN_CORE_NS = "http://purl.org/dc/elements/1.1/";
static const QString OEBPS_MIMETYPE = "application/oebps-package+xml";
static const QString UPDATE_ERROR_STRING = "SG_ERROR";
const QString NCX_MIMETYPE = "application/x-dtbncx+xml";
static const QString NCX_EXTENSION = "ncx";
const QString ADOBE_FONT_ALGO_ID = "http://ns.adobe.com/pdf/enc#RC";
const QString IDPF_FONT_ALGO_ID = "http://www.idpf.org/2008/embedding";
static const QString CONTAINER_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n"
" <rootfiles>\n"
" <rootfile full-path=\"%1\" media-type=\"application/oebps-package+xml\"/>\n"
" </rootfiles>\n"
"</container>\n";
static QCodePage437Codec *cp437 = 0;
// Constructor;
// The parameter is the file to be imported
ImportEPUB::ImportEPUB(const QString &fullfilepath)
: Importer(fullfilepath),
m_ExtractedFolderPath(m_TempFolder.GetPath()),
m_HasSpineItems(false),
m_NCXNotInManifest(false),
m_NavResource(NULL)
{
}
// Reads and parses the file
// and returns the created Book
QSharedPointer<Book> ImportEPUB::GetBook(bool extract_metadata)
{
QList<XMLResource *> non_well_formed;
SettingsStore ss;
if (!Utility::IsFileReadable(m_FullFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot read EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
// These read the EPUB file
ExtractContainer();
QHash<QString, QString> encrypted_files = ParseEncryptionXml();
if (BookContentEncrypted(encrypted_files)) {
throw (FileEncryptedWithDrm(""));
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// These mutate the m_Book object
LocateOPF();
m_opfDir = QFileInfo(m_OPFFilePath).dir();
// These mutate the m_Book object
ReadOPF();
AddObfuscatedButUndeclaredFonts(encrypted_files);
AddNonStandardAppleXML();
LoadInfrastructureFiles();
// Check for files missing in the Manifest and create warning
QStringList notInManifest;
foreach(QString file_path, m_ZipFilePaths) {
// skip mimetype and anything in META-INF and the opf itself
if (file_path == "mimetype") continue;
if (file_path.startsWith("META-INF")) continue;
if (m_OPFFilePath.contains(file_path)) continue;
if (!m_ManifestFilePaths.contains(file_path)) {
notInManifest << file_path;
}
}
if (!notInManifest.isEmpty()) {
Utility::DisplayStdWarningDialog(tr("Files exist in epub that are not listed in the manifest, they will be ignored"), notInManifest.join("\n"));
}
const QHash<QString, QString> updates = LoadFolderStructure();
const QList<Resource *> resources = m_Book->GetFolderKeeper()->GetResourceList();
// We're going to check all html files until we find one that isn't well formed then we'll prompt
// the user if they want to auto fix or not.
//
// If we have non-well formed content and they shouldn't be auto fixed we'll pass that on to
// the universal update function so it knows to skip them. Otherwise we won't include them and
// let it modify the file.
for (int i=0; i<resources.count(); ++i) {
if (resources.at(i)->Type() == Resource::HTMLResourceType) {
HTMLResource *hresource = dynamic_cast<HTMLResource *>(resources.at(i));
if (!hresource) {
continue;
}
// Load the content into the HTMLResource so we can perform a well formed check.
try {
hresource->SetText(HTMLEncodingResolver::ReadHTMLFile(hresource->GetFullPath()));
} catch (...) {
if (ss.cleanOn() & CLEANON_OPEN) {
non_well_formed << hresource;
continue;
}
}
if (ss.cleanOn() & CLEANON_OPEN) {
if (!XhtmlDoc::IsDataWellFormed(hresource->GetText(),hresource->GetEpubVersion())) {
non_well_formed << hresource;
}
}
}
}
if (!non_well_formed.isEmpty()) {
QApplication::restoreOverrideCursor();
if (QMessageBox::Yes == QMessageBox::warning(QApplication::activeWindow(),
tr("Sigil"),
tr("This EPUB has HTML files that are not well formed. "
"Sigil can attempt to automatically fix these files, although this "
"can result in data loss.\n\n"
"Do you want to automatically fix the files?"),
QMessageBox::Yes|QMessageBox::No)
) {
non_well_formed.clear();
}
QApplication::setOverrideCursor(Qt::WaitCursor);
}
const QStringList load_errors = UniversalUpdates::PerformUniversalUpdates(false, resources, updates, non_well_formed);
Q_FOREACH (QString err, load_errors) {
AddLoadWarning(QString("%1").arg(err));
}
ProcessFontFiles(resources, updates, encrypted_files);
if (m_PackageVersion.startsWith('3')) {
HTMLResource * nav_resource = NULL;
if (m_NavResource) {
if (m_NavResource->Type() == Resource::HTMLResourceType) {
nav_resource = dynamic_cast<HTMLResource*>(m_NavResource);
}
}
if (!nav_resource) {
// we need to create a nav file here because one was not found
// it will automatically be added to the content.opf
nav_resource = m_Book->CreateEmptyNavFile(true);
Resource * res = dynamic_cast<Resource *>(nav_resource);
m_Book->GetOPF()->SetItemRefLinear(res, false);
}
m_Book->GetOPF()->SetNavResource(nav_resource);
}
if (m_NCXNotInManifest) {
// We manually created an NCX file because there wasn't one in the manifest.
// Need to create a new manifest id for it.
m_NCXId = m_Book->GetOPF()->AddNCXItem(m_NCXFilePath);
}
// Ensure that our spine has a <spine toc="ncx"> element on it now in case it was missing.
m_Book->GetOPF()->UpdateNCXOnSpine(m_NCXId);
// Make sure the <item> for the NCX in the manifest reflects correct href path
m_Book->GetOPF()->UpdateNCXLocationInManifest(m_Book->GetNCX());
// If spine was not present or did not contain any items, recreate the OPF from scratch
// preserving any important metadata elements and making a new reading order.
if (!m_HasSpineItems) {
QList<MetaEntry> originalMetadata = m_Book->GetOPF()->GetDCMetadata();
m_Book->GetOPF()->AutoFixWellFormedErrors();
if (extract_metadata) {
m_Book->GetOPF()->SetDCMetadata(originalMetadata);
}
AddLoadWarning(QObject::tr("The OPF file does not contain a valid spine.") % "\n" %
QObject::tr("Sigil has created a new one for you."));
}
// If we have modified the book to add spine attribute, manifest item or NCX mark as changed.
m_Book->SetModified(GetLoadWarnings().count() > 0);
QApplication::restoreOverrideCursor();
return m_Book;
}
QHash<QString, QString> ImportEPUB::ParseEncryptionXml()
{
QString encrpytion_xml_path = m_ExtractedFolderPath + "/META-INF/encryption.xml";
if (!QFileInfo(encrpytion_xml_path).exists()) {
return QHash<QString, QString>();
}
QXmlStreamReader encryption(Utility::ReadUnicodeTextFile(encrpytion_xml_path));
QHash<QString, QString> encrypted_files;
QString encryption_algo;
QString uri;
while (!encryption.atEnd()) {
encryption.readNext();
if (encryption.isStartElement()) {
if (encryption.name() == "EncryptionMethod") {
encryption_algo = encryption.attributes().value("", "Algorithm").toString();
} else if (encryption.name() == "CipherReference") {
uri = Utility::URLDecodePath(encryption.attributes().value("", "URI").toString());
encrypted_files[ uri ] = encryption_algo;
}
}
}
if (encryption.hasError()) {
const QString error = QString(QObject::tr("Error parsing encryption xml.\nLine: %1 Column %2 - %3"))
.arg(encryption.lineNumber())
.arg(encryption.columnNumber())
.arg(encryption.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
return encrypted_files;
}
bool ImportEPUB::BookContentEncrypted(const QHash<QString, QString> &encrypted_files)
{
foreach(QString algorithm, encrypted_files.values()) {
if (algorithm != ADOBE_FONT_ALGO_ID &&
algorithm != IDPF_FONT_ALGO_ID) {
return true;
}
}
return false;
}
// This is basically a workaround for old versions of InDesign not listing the fonts it
// embedded in the OPF manifest, even though the specs say it has to.
// It does list them in the encryption.xml, so we use that.
void ImportEPUB::AddObfuscatedButUndeclaredFonts(const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
foreach(QString filepath, encrypted_files.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(filepath).suffix().toLower())) {
continue;
}
// Only add the path to the manifest if it is not already included.
QMapIterator<QString, QString> valueSearch(m_Files);
if (!valueSearch.findNext(opf_dir.relativeFilePath(filepath))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(filepath);
}
}
}
// Another workaround for non-standard Apple files
// At present it only handles com.apple.ibooks.display-options.xml, but any
// further iBooks aberrations should be handled here as well.
void ImportEPUB::AddNonStandardAppleXML()
{
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QStringList aberrant_Apple_filenames;
aberrant_Apple_filenames.append(m_ExtractedFolderPath + "/META-INF/com.apple.ibooks.display-options.xml");
for (int i = 0; i < aberrant_Apple_filenames.size(); ++i) {
if (QFile::exists(aberrant_Apple_filenames.at(i))) {
m_Files[ Utility::CreateUUID() ] = opf_dir.relativeFilePath(aberrant_Apple_filenames.at(i));
}
}
}
// Each resource can provide us with its new path. encrypted_files provides
// a mapping from old resource paths to the obfuscation algorithms.
// So we use the updates hash which provides a mapping from old paths to new
// paths to match the resources to their algorithms.
void ImportEPUB::ProcessFontFiles(const QList<Resource *> &resources,
const QHash<QString, QString> &updates,
const QHash<QString, QString> &encrypted_files)
{
if (encrypted_files.empty()) {
return;
}
QList<FontResource *> font_resources = m_Book->GetFolderKeeper()->GetResourceTypeList<FontResource>();
if (font_resources.empty()) {
return;
}
QHash<QString, QString> new_font_paths_to_algorithms;
foreach(QString old_update_path, updates.keys()) {
if (!FONT_EXTENSIONS.contains(QFileInfo(old_update_path).suffix().toLower())) {
continue;
}
QString new_update_path = updates[ old_update_path ];
foreach(QString old_encrypted_path, encrypted_files.keys()) {
if (old_update_path == old_encrypted_path) {
new_font_paths_to_algorithms[ new_update_path ] = encrypted_files[ old_encrypted_path ];
}
}
}
foreach(FontResource * font_resource, font_resources) {
QString match_path = "../" + font_resource->GetRelativePathToOEBPS();
QString algorithm = new_font_paths_to_algorithms.value(match_path);
if (algorithm.isEmpty()) {
continue;
}
font_resource->SetObfuscationAlgorithm(algorithm);
// Actually we are de-obfuscating, but the inverse operations of the obfuscation methods
// are the obfuscation methods themselves. For the math oriented, the obfuscation methods
// are involutary [ f( f( x ) ) = x ].
if (algorithm == ADOBE_FONT_ALGO_ID) {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UuidIdentifierValue);
} else {
FontObfuscation::ObfuscateFile(font_resource->GetFullPath(), algorithm, m_UniqueIdentifierValue);
}
}
}
void ImportEPUB::ExtractContainer()
{
int res = 0;
if (!cp437) {
cp437 = new QCodePage437Codec();
}
#ifdef Q_OS_WIN32
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc);
#else
unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData());
#endif
if (zfile == NULL) {
throw (EPUBLoadParseError(QString(QObject::tr("Cannot unzip EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
res = unzGoToFirstFile(zfile);
if (res == UNZ_OK) {
do {
// Get the name of the file in the archive.
char file_name[MAX_PATH] = {0};
unz_file_info64 file_info;
unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);
QString qfile_name;
QString cp437_file_name;
qfile_name = QString::fromUtf8(file_name);
if (!(file_info.flag & (1<<11))) {
// General purpose bit 11 says the filename is utf-8 encoded. If not set then
// IBM 437 encoding might be used.
cp437_file_name = cp437->toUnicode(file_name);
}
// If there is no file name then we can't do anything with it.
if (!qfile_name.isEmpty()) {
// for security reasons against maliciously crafted zip archives
// we need the file path to always be inside the target folder
// and not outside, so we will remove all illegal backslashes
// and all relative upward paths segments "/../" from the zip's local
// file name/path before prepending the target folder to create
// the final path
QString original_path = qfile_name;
bool evil_or_corrupt_epub = false;
if (qfile_name.contains("\\")) evil_or_corrupt_epub = true;
qfile_name = "/" + qfile_name.replace("\\","");
if (qfile_name.contains("/../")) evil_or_corrupt_epub = true;
qfile_name = qfile_name.replace("/../","/");
while(qfile_name.startsWith("/")) {
qfile_name = qfile_name.remove(0,1);
}
if (cp437_file_name.contains("\\")) evil_or_corrupt_epub = true;
cp437_file_name = "/" + cp437_file_name.replace("\\","");
if (cp437_file_name.contains("/../")) evil_or_corrupt_epub = true;
cp437_file_name = cp437_file_name.replace("/../","/");
while(cp437_file_name.startsWith("/")) {
cp437_file_name = cp437_file_name.remove(0,1);
}
if (evil_or_corrupt_epub) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Possible evil or corrupt epub file name: %1")).arg(original_path).toStdString()));
}
// We use the dir object to create the path in the temporary directory.
// Unfortunately, we need a dir ojbect to do this as it's not a static function.
QDir dir(m_ExtractedFolderPath);
// Full file path in the temporary directory.
QString file_path = m_ExtractedFolderPath + "/" + qfile_name;
QFileInfo qfile_info(file_path);
// Is this entry a directory?
if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {
dir.mkpath(qfile_name);
continue;
} else {
dir.mkpath(qfile_info.path());
// add it to the list of files found inside the zip
if (cp437_file_name.isEmpty()) {
m_ZipFilePaths << qfile_name;
} else {
m_ZipFilePaths << cp437_file_name;
}
}
// Open the file entry in the archive for reading.
if (unzOpenCurrentFile(zfile) != UNZ_OK) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Open the file on disk to write the entry in the archive to.
QFile entry(file_path);
if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// Buffered reading and writing.
char buff[BUFF_SIZE] = {0};
int read = 0;
while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {
entry.write(buff, read);
}
entry.close();
// Read errors are marked by a negative read amount.
if (read < 0) {
unzCloseCurrentFile(zfile);
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
// The file was read but the CRC did not match.
// We don't check the read file size vs the uncompressed file size
// because if they're different there should be a CRC error.
if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot extract file: %1")).arg(qfile_name).toStdString()));
}
if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {
QString cp437_file_path = m_ExtractedFolderPath + "/" + cp437_file_name;
QFile::copy(file_path, cp437_file_path);
}
}
} while ((res = unzGoToNextFile(zfile)) == UNZ_OK);
}
if (res != UNZ_END_OF_LIST_OF_FILE) {
unzClose(zfile);
throw (EPUBLoadParseError(QString(QObject::tr("Cannot open EPUB: %1")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));
}
unzClose(zfile);
}
void ImportEPUB::LocateOPF()
{
QString fullpath = m_ExtractedFolderPath + "/META-INF/container.xml";
QXmlStreamReader container;
try {
container.addData(Utility::ReadUnicodeTextFile(fullpath));
} catch (CannotOpenFile) {
// Find the first OPF file.
QString OPFfile;
QDirIterator files(m_ExtractedFolderPath, QStringList() << "*.opf", QDir::NoFilter, QDirIterator::Subdirectories);
while (files.hasNext()) {
OPFfile = QDir(m_ExtractedFolderPath).relativeFilePath(files.next());
break;
}
if (OPFfile.isEmpty()) {
std::string msg = fullpath.toStdString() + ": " + tr("Epub has missing or improperly specified OPF.").toStdString();
throw (CannotOpenFile(msg));
}
// Create a default container.xml.
QDir folder(m_ExtractedFolderPath);
folder.mkdir("META-INF");
Utility::WriteUnicodeTextFile(CONTAINER_XML.arg(OPFfile), fullpath);
container.addData(Utility::ReadUnicodeTextFile(fullpath));
}
while (!container.atEnd()) {
container.readNext();
if (container.isStartElement() &&
container.name() == "rootfile"
) {
if (container.attributes().hasAttribute("media-type") &&
container.attributes().value("", "media-type") == OEBPS_MIMETYPE
) {
m_OPFFilePath = m_ExtractedFolderPath + "/" + container.attributes().value("", "full-path").toString();
// As per OCF spec, the first rootfile element
// with the OEBPS mimetype is considered the "main" one.
break;
}
}
}
if (container.hasError()) {
const QString error = QString(
QObject::tr("Unable to parse container.xml file.\nLine: %1 Column %2 - %3"))
.arg(container.lineNumber())
.arg(container.columnNumber())
.arg(container.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
if (m_OPFFilePath.isEmpty() || !QFile::exists(m_OPFFilePath)) {
throw (EPUBLoadParseError(QString(QObject::tr("No appropriate OPF file found")).toStdString()));
}
}
void ImportEPUB::ReadOPF()
{
QString opf_text = CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE);
QXmlStreamReader opf_reader(opf_text);
QString ncx_id_on_spine;
while (!opf_reader.atEnd()) {
opf_reader.readNext();
if (!opf_reader.isStartElement()) {
continue;
}
if (opf_reader.name() == "package") {
m_UniqueIdentifierId = opf_reader.attributes().value("", "unique-identifier").toString();
m_PackageVersion = opf_reader.attributes().value("", "version").toString();
if (m_PackageVersion == "1.0") m_PackageVersion = "2.0";
}
else if (opf_reader.name() == "identifier") {
ReadIdentifierElement(&opf_reader);
}
// epub3 look for linked metadata resources that are included inside the epub
// but that are not and must not be included in the manifest
else if (opf_reader.name() == "link") {
ReadMetadataLinkElement(&opf_reader);
}
// Get the list of content files that
// make up the publication
else if (opf_reader.name() == "item") {
ReadManifestItemElement(&opf_reader);
}
// We read this just to get the NCX id
else if (opf_reader.name() == "spine") {
ncx_id_on_spine = opf_reader.attributes().value("", "toc").toString();
}
else if (opf_reader.name() == "itemref") {
m_HasSpineItems = true;
}
}
if (opf_reader.hasError()) {
const QString error = QString(QObject::tr("Unable to read OPF file.\nLine: %1 Column %2 - %3"))
.arg(opf_reader.lineNumber())
.arg(opf_reader.columnNumber())
.arg(opf_reader.errorString());
throw (EPUBLoadParseError(error.toStdString()));
}
// Ensure we have an NCX available
LocateOrCreateNCX(ncx_id_on_spine);
}
void ImportEPUB::ReadIdentifierElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString scheme = opf_reader->attributes().value("", "scheme").toString();
QString value = opf_reader->readElementText();
if (id == m_UniqueIdentifierId) {
m_UniqueIdentifierValue = value;
}
if (m_UuidIdentifierValue.isEmpty() &&
(value.contains("urn:uuid:") || scheme.toLower() == "uuid")) {
m_UuidIdentifierValue = value;
}
}
void ImportEPUB::ReadMetadataLinkElement(QXmlStreamReader *opf_reader)
{
QString relation = opf_reader->attributes().value("", "rel").toString();
QString mtype = opf_reader->attributes().value("", "media-type").toString();
QString props = opf_reader->attributes().value("", "properties").toString();
QString href = opf_reader->attributes().value("", "href").toString();
if (!href.isEmpty()) {
QUrl url = QUrl(href);
if (url.isRelative()) {
// we have a local unmanifested metadata file to handle
// attempt to map deprecated record types into proper media-types
if (relation == "marc21xml-record") {
mtype = "application/marcxml+xml";
}
else if (relation == "mods-record") {
mtype = "application/mods+xml";
}
else if (relation == "onix-record") {
mtype = "application/xml;onix";
}
else if (relation == "xmp-record") {
mtype = "application/xml;xmp";
}
else if (relation == "record") {
if (props == "onix") mtype = "application/xml;onix";
if (props == "xmp") mtype = "application/xml;xmp";
}
QDir opf_dir = QFileInfo(m_OPFFilePath).dir();
QString path = opf_dir.absolutePath() + "/" + url.path();
if (QFile::exists(path)) {
QString id = Utility::CreateUUID();
m_Files[ id ] = opf_dir.relativeFilePath(path);
m_FileMimetypes[ id ] = mtype;
}
}
}
}
void ImportEPUB::ReadManifestItemElement(QXmlStreamReader *opf_reader)
{
QString id = opf_reader->attributes().value("", "id").toString();
QString href = opf_reader->attributes().value("", "href").toString();
QString type = opf_reader->attributes().value("", "media-type").toString();
QString properties = opf_reader->attributes().value("", "properties").toString();
// Paths are percent encoded in the OPF, we use "normal" paths internally.
href = Utility::URLDecodePath(href);
QString extension = QFileInfo(href).suffix().toLower();
// find the epub root relative file path from the opf location and the item href
QString file_path = m_opfDir.absolutePath() + "/" + href;
file_path = file_path.remove(0, m_ExtractedFolderPath.length() + 1);
if (type != NCX_MIMETYPE && extension != NCX_EXTENSION) {
if (!m_ManifestFilePaths.contains(file_path)) {
if (m_Files.contains(id)) {
// We have an error situation with a duplicate id in the epub.
// We must warn the user, but attempt to use another id so the epub can still be loaded.
QString base_id = QFileInfo(href).fileName();
QString new_id(base_id);
int duplicate_index = 0;
while (m_Files.contains(new_id)) {
duplicate_index++;
new_id = QString("%1%2").arg(base_id).arg(duplicate_index);
}
const QString load_warning = QObject::tr("The OPF manifest contains duplicate ids for: %1").arg(id) +
" - " + QObject::tr("A temporary id has been assigned to load this EPUB. You should edit your OPF file to remove the duplication.");
id = new_id;
AddLoadWarning(load_warning);
}
m_Files[ id ] = href;
m_FileMimetypes[ id ] = type;
m_ManifestFilePaths << file_path;
// store information about any nav document
if (properties.contains("nav")) {
m_NavId = id;
m_NavHref = href;
}
}
} else {
m_NcxCandidates[ id ] = href;
m_ManifestFilePaths << file_path;
}
}
void ImportEPUB::LocateOrCreateNCX(const QString &ncx_id_on_spine)
{
QString load_warning;
QString ncx_href = "not_found";
m_NCXId = ncx_id_on_spine;
// Handle various failure conditions, such as:
// - ncx not specified in the spine (search for a matching manifest item by extension)
// - ncx specified in spine, but no matching manifest item entry (create a new one)
// - ncx file not physically present (create a new one)
// - ncx not in spine or manifest item (create a new one)
if (!m_NCXId.isEmpty()) {
ncx_href = m_NcxCandidates[ m_NCXId ];
} else {
// Search for the ncx in the manifest by looking for files with
// a .ncx extension.
QHashIterator<QString, QString> ncxSearch(m_NcxCandidates);
while (ncxSearch.hasNext()) {
ncxSearch.next();
if (QFileInfo(ncxSearch.value()).suffix().toLower() == NCX_EXTENSION) {
m_NCXId = ncxSearch.key();
load_warning = QObject::tr("The OPF file did not identify the NCX file correctly.") + "\n" +
" - " + QObject::tr("Sigil has used the following file as the NCX:") +
QString(" %1").arg(m_NcxCandidates[ m_NCXId ]);
ncx_href = m_NcxCandidates[ m_NCXId ];
break;
}
}
}
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % ncx_href;
if (ncx_href.isEmpty() || !QFile::exists(m_NCXFilePath)) {
m_NCXNotInManifest = m_NCXId.isEmpty() || ncx_href.isEmpty();
m_NCXId.clear();
// Things are really bad and no .ncx file was found in the manifest or
// the file does not physically exist. We need to create a new one.
m_NCXFilePath = QFileInfo(m_OPFFilePath).absolutePath() % "/" % NCX_FILE_NAME;
// Create a new file for the NCX.
NCXResource ncx_resource(m_ExtractedFolderPath, m_NCXFilePath, m_Book->GetFolderKeeper());
// We are relying on an identifier being set from the metadata.
// It might not have one if the book does not have the urn:uuid: format.
if (!m_UuidIdentifierValue.isEmpty()) {
ncx_resource.SetMainID(m_UuidIdentifierValue);
}
ncx_resource.SaveToDisk();
if (m_PackageVersion.startsWith('3')) {
load_warning = QObject::tr("Sigil has created a template NCX") + "\n" +
QObject::tr("to support epub2 backwards compatibility.");
} else {
if (ncx_href.isEmpty()) {
load_warning = QObject::tr("The OPF file does not contain an NCX file.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
} else {
load_warning = QObject::tr("The NCX file is not present in this EPUB.") + "\n" +
" - " + QObject::tr("Sigil has created a new one for you.");
}
}
}
if (!load_warning.isEmpty()) {
AddLoadWarning(load_warning);
}
}
void ImportEPUB::LoadInfrastructureFiles()
{
// always SetEpubVersion before SetText in OPF as SetText will validate with it
m_Book->GetOPF()->SetEpubVersion(m_PackageVersion);
m_Book->GetOPF()->SetText(CleanSource::ProcessXML(PrepareOPFForReading(Utility::ReadUnicodeTextFile(m_OPFFilePath)),OEBPS_MIMETYPE));
QString OPFBookRelPath = m_OPFFilePath;
OPFBookRelPath = OPFBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetOPF()->SetCurrentBookRelPath(OPFBookRelPath);
m_Book->GetNCX()->SetText(CleanSource::ProcessXML(Utility::ReadUnicodeTextFile(m_NCXFilePath),"application/x-dtbncx+xml"));
m_Book->GetNCX()->SetEpubVersion(m_PackageVersion);
QString NCXBookRelPath = m_NCXFilePath;
NCXBookRelPath = NCXBookRelPath.remove(0,m_ExtractedFolderPath.length()+1);
m_Book->GetNCX()->SetCurrentBookRelPath(NCXBookRelPath);
}
QHash<QString, QString> ImportEPUB::LoadFolderStructure()
{
QList<QString> keys = m_Files.keys();
int num_files = keys.count();
QFutureSynchronizer<std::tuple<QString, QString>> sync;
for (int i = 0; i < num_files; ++i) {
QString id = keys.at(i);
sync.addFuture(QtConcurrent::run(
this,
&ImportEPUB::LoadOneFile,
m_Files.value(id),
m_FileMimetypes.value(id)));
}
sync.waitForFinished();
QList<QFuture<std::tuple<QString, QString>>> futures = sync.futures();
int num_futures = futures.count();
QHash<QString, QString> updates;
for (int i = 0; i < num_futures; ++i) {
std::tuple<QString, QString> result = futures.at(i).result();
updates[std::get<0>(result)] = std::get<1>(result);
}
updates.remove(UPDATE_ERROR_STRING);
return updates;
}
std::tuple<QString, QString> ImportEPUB::LoadOneFile(const QString &path, const QString &mimetype)
{
QString fullfilepath = QDir::cleanPath(QFileInfo(m_OPFFilePath).absolutePath() + "/" + path);
QString currentpath = fullfilepath;
currentpath = currentpath.remove(0,m_ExtractedFolderPath.length()+1);
try {
Resource *resource = m_Book->GetFolderKeeper()->AddContentFileToFolder(fullfilepath, false, mimetype);
if (path == m_NavHref) {
m_NavResource = resource;
}
resource->SetCurrentBookRelPath(currentpath);
QString newpath = "../" + resource->GetRelativePathToOEBPS();
return std::make_tuple(currentpath, newpath);
} catch (FileDoesNotExist) {
return std::make_tuple(UPDATE_ERROR_STRING, UPDATE_ERROR_STRING);
}
}
QString ImportEPUB::PrepareOPFForReading(const QString &source)
{
QString source_copy(source);
QString prefix = source_copy.left(XML_DECLARATION_SEARCH_PREFIX_SIZE);
QRegularExpression version(VERSION_ATTRIBUTE);
QRegularExpressionMatch mo = version.match(prefix);
if (mo.hasMatch()) {
// MASSIVE hack for XML 1.1 "support";
// this is only for people who specify
// XML 1.1 when they actually only use XML 1.0
source_copy.replace(mo.capturedStart(1), mo.capturedLength(1), "1.0");
}
return source_copy;
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/good_973_0 |
crossvul-cpp_data_bad_74_1 | /*
Copyright (C) 2010 Roberto Pompermaier
Copyright (C) 2005-2014 Sergey A. Tachenov
This file is part of QuaZIP.
QuaZIP 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.
QuaZIP 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 QuaZIP. If not, see <http://www.gnu.org/licenses/>.
See COPYING file for the full LGPL text.
Original ZIP package is copyrighted by Gilles Vollant and contributors,
see quazip/(un)zip.h files for details. Basically it's the zlib license.
*/
#include "JlCompress.h"
#include <QDebug>
static bool copyData(QIODevice &inFile, QIODevice &outFile)
{
while (!inFile.atEnd()) {
char buf[4096];
qint64 readLen = inFile.read(buf, 4096);
if (readLen <= 0)
return false;
if (outFile.write(buf, readLen) != readLen)
return false;
}
return true;
}
bool JlCompress::compressFile(QuaZip* zip, QString fileName, QString fileDest) {
// zip: oggetto dove aggiungere il file
// fileName: nome del file reale
// fileDest: nome del file all'interno del file compresso
// Controllo l'apertura dello zip
if (!zip) return false;
if (zip->getMode()!=QuaZip::mdCreate &&
zip->getMode()!=QuaZip::mdAppend &&
zip->getMode()!=QuaZip::mdAdd) return false;
// Apro il file originale
QFile inFile;
inFile.setFileName(fileName);
if(!inFile.open(QIODevice::ReadOnly)) return false;
// Apro il file risulato
QuaZipFile outFile(zip);
if(!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(fileDest, inFile.fileName()))) return false;
// Copio i dati
if (!copyData(inFile, outFile) || outFile.getZipError()!=UNZ_OK) {
return false;
}
// Chiudo i file
outFile.close();
if (outFile.getZipError()!=UNZ_OK) return false;
inFile.close();
return true;
}
bool JlCompress::compressSubDir(QuaZip* zip, QString dir, QString origDir, bool recursive, QDir::Filters filters) {
// zip: oggetto dove aggiungere il file
// dir: cartella reale corrente
// origDir: cartella reale originale
// (path(dir)-path(origDir)) = path interno all'oggetto zip
// Controllo l'apertura dello zip
if (!zip) return false;
if (zip->getMode()!=QuaZip::mdCreate &&
zip->getMode()!=QuaZip::mdAppend &&
zip->getMode()!=QuaZip::mdAdd) return false;
// Controllo la cartella
QDir directory(dir);
if (!directory.exists()) return false;
QDir origDirectory(origDir);
if (dir != origDir) {
QuaZipFile dirZipFile(zip);
if (!dirZipFile.open(QIODevice::WriteOnly,
QuaZipNewInfo(origDirectory.relativeFilePath(dir) + "/", dir), 0, 0, 0)) {
return false;
}
dirZipFile.close();
}
// Se comprimo anche le sotto cartelle
if (recursive) {
// Per ogni sotto cartella
QFileInfoList files = directory.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot|filters);
for (int index = 0; index < files.size(); ++index ) {
const QFileInfo & file( files.at( index ) );
#if QT_VERSION < QT_VERSION_CHECK(4, 7, 4)
if (!file.isDir())
continue;
#endif
// Comprimo la sotto cartella
if(!compressSubDir(zip,file.absoluteFilePath(),origDir,recursive,filters)) return false;
}
}
// Per ogni file nella cartella
QFileInfoList files = directory.entryInfoList(QDir::Files|filters);
for (int index = 0; index < files.size(); ++index ) {
const QFileInfo & file( files.at( index ) );
// Se non e un file o e il file compresso che sto creando
if(!file.isFile()||file.absoluteFilePath()==zip->getZipName()) continue;
// Creo il nome relativo da usare all'interno del file compresso
QString filename = origDirectory.relativeFilePath(file.absoluteFilePath());
// Comprimo il file
if (!compressFile(zip,file.absoluteFilePath(),filename)) return false;
}
return true;
}
bool JlCompress::extractFile(QuaZip* zip, QString fileName, QString fileDest) {
// zip: oggetto dove aggiungere il file
// filename: nome del file reale
// fileincompress: nome del file all'interno del file compresso
// Controllo l'apertura dello zip
if (!zip) return false;
if (zip->getMode()!=QuaZip::mdUnzip) return false;
// Apro il file compresso
if (!fileName.isEmpty())
zip->setCurrentFile(fileName);
QuaZipFile inFile(zip);
if(!inFile.open(QIODevice::ReadOnly) || inFile.getZipError()!=UNZ_OK) return false;
// Controllo esistenza cartella file risultato
QDir curDir;
if (fileDest.endsWith('/')) {
if (!curDir.mkpath(fileDest)) {
return false;
}
} else {
if (!curDir.mkpath(QFileInfo(fileDest).absolutePath())) {
return false;
}
}
QuaZipFileInfo64 info;
if (!zip->getCurrentFileInfo(&info))
return false;
QFile::Permissions srcPerm = info.getPermissions();
if (fileDest.endsWith('/') && QFileInfo(fileDest).isDir()) {
if (srcPerm != 0) {
QFile(fileDest).setPermissions(srcPerm);
}
return true;
}
// Apro il file risultato
QFile outFile;
outFile.setFileName(fileDest);
if(!outFile.open(QIODevice::WriteOnly)) return false;
// Copio i dati
if (!copyData(inFile, outFile) || inFile.getZipError()!=UNZ_OK) {
outFile.close();
removeFile(QStringList(fileDest));
return false;
}
outFile.close();
// Chiudo i file
inFile.close();
if (inFile.getZipError()!=UNZ_OK) {
removeFile(QStringList(fileDest));
return false;
}
if (srcPerm != 0) {
outFile.setPermissions(srcPerm);
}
return true;
}
bool JlCompress::removeFile(QStringList listFile) {
bool ret = true;
// Per ogni file
for (int i=0; i<listFile.count(); i++) {
// Lo elimino
ret = ret && QFile::remove(listFile.at(i));
}
return ret;
}
bool JlCompress::compressFile(QString fileCompressed, QString file) {
// Creo lo zip
QuaZip zip(fileCompressed);
QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
if(!zip.open(QuaZip::mdCreate)) {
QFile::remove(fileCompressed);
return false;
}
// Aggiungo il file
if (!compressFile(&zip,file,QFileInfo(file).fileName())) {
QFile::remove(fileCompressed);
return false;
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
QFile::remove(fileCompressed);
return false;
}
return true;
}
bool JlCompress::compressFiles(QString fileCompressed, QStringList files) {
// Creo lo zip
QuaZip zip(fileCompressed);
QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
if(!zip.open(QuaZip::mdCreate)) {
QFile::remove(fileCompressed);
return false;
}
// Comprimo i file
QFileInfo info;
for (int index = 0; index < files.size(); ++index ) {
const QString & file( files.at( index ) );
info.setFile(file);
if (!info.exists() || !compressFile(&zip,file,info.fileName())) {
QFile::remove(fileCompressed);
return false;
}
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
QFile::remove(fileCompressed);
return false;
}
return true;
}
bool JlCompress::compressDir(QString fileCompressed, QString dir, bool recursive) {
return compressDir(fileCompressed, dir, recursive, 0);
}
bool JlCompress::compressDir(QString fileCompressed, QString dir,
bool recursive, QDir::Filters filters)
{
// Creo lo zip
QuaZip zip(fileCompressed);
QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
if(!zip.open(QuaZip::mdCreate)) {
QFile::remove(fileCompressed);
return false;
}
// Aggiungo i file e le sotto cartelle
if (!compressSubDir(&zip,dir,dir,recursive, filters)) {
QFile::remove(fileCompressed);
return false;
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
QFile::remove(fileCompressed);
return false;
}
return true;
}
QString JlCompress::extractFile(QString fileCompressed, QString fileName, QString fileDest) {
// Apro lo zip
QuaZip zip(fileCompressed);
return extractFile(zip, fileName, fileDest);
}
QString JlCompress::extractFile(QuaZip &zip, QString fileName, QString fileDest)
{
if(!zip.open(QuaZip::mdUnzip)) {
return QString();
}
// Estraggo il file
if (fileDest.isEmpty())
fileDest = fileName;
if (!extractFile(&zip,fileName,fileDest)) {
return QString();
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
removeFile(QStringList(fileDest));
return QString();
}
return QFileInfo(fileDest).absoluteFilePath();
}
QStringList JlCompress::extractFiles(QString fileCompressed, QStringList files, QString dir) {
// Creo lo zip
QuaZip zip(fileCompressed);
return extractFiles(zip, files, dir);
}
QStringList JlCompress::extractFiles(QuaZip &zip, const QStringList &files, const QString &dir)
{
if(!zip.open(QuaZip::mdUnzip)) {
return QStringList();
}
// Estraggo i file
QStringList extracted;
for (int i=0; i<files.count(); i++) {
QString absPath = QDir(dir).absoluteFilePath(files.at(i));
if (!extractFile(&zip, files.at(i), absPath)) {
removeFile(extracted);
return QStringList();
}
extracted.append(absPath);
}
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
removeFile(extracted);
return QStringList();
}
return extracted;
}
QStringList JlCompress::extractDir(QString fileCompressed, QString dir) {
// Apro lo zip
QuaZip zip(fileCompressed);
return extractDir(zip, dir);
}
QStringList JlCompress::extractDir(QuaZip &zip, const QString &dir)
{
if(!zip.open(QuaZip::mdUnzip)) {
return QStringList();
}
QDir directory(dir);
QStringList extracted;
if (!zip.goToFirstFile()) {
return QStringList();
}
do {
QString name = zip.getCurrentFileName();
QString absFilePath = directory.absoluteFilePath(name);
if (!extractFile(&zip, "", absFilePath)) {
removeFile(extracted);
return QStringList();
}
extracted.append(absFilePath);
} while (zip.goToNextFile());
// Chiudo il file zip
zip.close();
if(zip.getZipError()!=0) {
removeFile(extracted);
return QStringList();
}
return extracted;
}
QStringList JlCompress::getFileList(QString fileCompressed) {
// Apro lo zip
QuaZip* zip = new QuaZip(QFileInfo(fileCompressed).absoluteFilePath());
return getFileList(zip);
}
QStringList JlCompress::getFileList(QuaZip *zip)
{
if(!zip->open(QuaZip::mdUnzip)) {
delete zip;
return QStringList();
}
// Estraggo i nomi dei file
QStringList lst;
QuaZipFileInfo64 info;
for(bool more=zip->goToFirstFile(); more; more=zip->goToNextFile()) {
if(!zip->getCurrentFileInfo(&info)) {
delete zip;
return QStringList();
}
lst << info.name;
//info.name.toLocal8Bit().constData()
}
// Chiudo il file zip
zip->close();
if(zip->getZipError()!=0) {
delete zip;
return QStringList();
}
delete zip;
return lst;
}
QStringList JlCompress::extractDir(QIODevice *ioDevice, QString dir)
{
QuaZip zip(ioDevice);
return extractDir(zip, dir);
}
QStringList JlCompress::getFileList(QIODevice *ioDevice)
{
QuaZip *zip = new QuaZip(ioDevice);
return getFileList(zip);
}
QString JlCompress::extractFile(QIODevice *ioDevice, QString fileName, QString fileDest)
{
QuaZip zip(ioDevice);
return extractFile(zip, fileName, fileDest);
}
QStringList JlCompress::extractFiles(QIODevice *ioDevice, QStringList files, QString dir)
{
QuaZip zip(ioDevice);
return extractFiles(zip, files, dir);
}
| ./CrossVul/dataset_final_sorted/CWE-22/cpp/bad_74_1 |
crossvul-cpp_data_bad_1520_4 | /*-
* Copyright (c) 2003-2010 Tim Kientzle
* Copyright (c) 2012 Michihiro NAKAJIMA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "archive_platform.h"
__FBSDID("$FreeBSD$");
#if !defined(_WIN32) || defined(__CYGWIN__)
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_ACL_H
#include <sys/acl.h>
#endif
#ifdef HAVE_SYS_EXTATTR_H
#include <sys/extattr.h>
#endif
#if defined(HAVE_SYS_XATTR_H)
#include <sys/xattr.h>
#elif defined(HAVE_ATTR_XATTR_H)
#include <attr/xattr.h>
#endif
#ifdef HAVE_SYS_EA_H
#include <sys/ea.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_UTIME_H
#include <sys/utime.h>
#endif
#ifdef HAVE_COPYFILE_H
#include <copyfile.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#ifdef HAVE_LINUX_FS_H
#include <linux/fs.h> /* for Linux file flags */
#endif
/*
* Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
* As the include guards don't agree, the order of include is important.
*/
#ifdef HAVE_LINUX_EXT2_FS_H
#include <linux/ext2_fs.h> /* for Linux file flags */
#endif
#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
#include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#include <stdio.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_UTIME_H
#include <utime.h>
#endif
#ifdef F_GETTIMES /* Tru64 specific */
#include <sys/fcntl1.h>
#endif
#if __APPLE__
#include <TargetConditionals.h>
#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
#include <quarantine.h>
#define HAVE_QUARANTINE 1
#endif
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
/* TODO: Support Mac OS 'quarantine' feature. This is really just a
* standard tag to mark files that have been downloaded as "tainted".
* On Mac OS, we should mark the extracted files as tainted if the
* archive being read was tainted. Windows has a similar feature; we
* should investigate ways to support this generically. */
#include "archive.h"
#include "archive_acl_private.h"
#include "archive_string.h"
#include "archive_endian.h"
#include "archive_entry.h"
#include "archive_private.h"
#include "archive_write_disk_private.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
struct fixup_entry {
struct fixup_entry *next;
struct archive_acl acl;
mode_t mode;
int64_t atime;
int64_t birthtime;
int64_t mtime;
int64_t ctime;
unsigned long atime_nanos;
unsigned long birthtime_nanos;
unsigned long mtime_nanos;
unsigned long ctime_nanos;
unsigned long fflags_set;
size_t mac_metadata_size;
void *mac_metadata;
int fixup; /* bitmask of what needs fixing */
char *name;
};
/*
* We use a bitmask to track which operations remain to be done for
* this file. In particular, this helps us avoid unnecessary
* operations when it's possible to take care of one step as a
* side-effect of another. For example, mkdir() can specify the mode
* for the newly-created object but symlink() cannot. This means we
* can skip chmod() if mkdir() succeeded, but we must explicitly
* chmod() if we're trying to create a directory that already exists
* (mkdir() failed) or if we're restoring a symlink. Similarly, we
* need to verify UID/GID before trying to restore SUID/SGID bits;
* that verification can occur explicitly through a stat() call or
* implicitly because of a successful chown() call.
*/
#define TODO_MODE_FORCE 0x40000000
#define TODO_MODE_BASE 0x20000000
#define TODO_SUID 0x10000000
#define TODO_SUID_CHECK 0x08000000
#define TODO_SGID 0x04000000
#define TODO_SGID_CHECK 0x02000000
#define TODO_APPLEDOUBLE 0x01000000
#define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
#define TODO_TIMES ARCHIVE_EXTRACT_TIME
#define TODO_OWNER ARCHIVE_EXTRACT_OWNER
#define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
#define TODO_ACLS ARCHIVE_EXTRACT_ACL
#define TODO_XATTR ARCHIVE_EXTRACT_XATTR
#define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA
#define TODO_HFS_COMPRESSION ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED
struct archive_write_disk {
struct archive archive;
mode_t user_umask;
struct fixup_entry *fixup_list;
struct fixup_entry *current_fixup;
int64_t user_uid;
int skip_file_set;
int64_t skip_file_dev;
int64_t skip_file_ino;
time_t start_time;
int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid);
void (*cleanup_gid)(void *private);
void *lookup_gid_data;
int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid);
void (*cleanup_uid)(void *private);
void *lookup_uid_data;
/*
* Full path of last file to satisfy symlink checks.
*/
struct archive_string path_safe;
/*
* Cached stat data from disk for the current entry.
* If this is valid, pst points to st. Otherwise,
* pst is null.
*/
struct stat st;
struct stat *pst;
/* Information about the object being restored right now. */
struct archive_entry *entry; /* Entry being extracted. */
char *name; /* Name of entry, possibly edited. */
struct archive_string _name_data; /* backing store for 'name' */
/* Tasks remaining for this object. */
int todo;
/* Tasks deferred until end-of-archive. */
int deferred;
/* Options requested by the client. */
int flags;
/* Handle for the file we're restoring. */
int fd;
/* Current offset for writing data to the file. */
int64_t offset;
/* Last offset actually written to disk. */
int64_t fd_offset;
/* Total bytes actually written to files. */
int64_t total_bytes_written;
/* Maximum size of file, -1 if unknown. */
int64_t filesize;
/* Dir we were in before this restore; only for deep paths. */
int restore_pwd;
/* Mode we should use for this entry; affected by _PERM and umask. */
mode_t mode;
/* UID/GID to use in restoring this entry. */
int64_t uid;
int64_t gid;
/*
* HFS+ Compression.
*/
/* Xattr "com.apple.decmpfs". */
uint32_t decmpfs_attr_size;
unsigned char *decmpfs_header_p;
/* ResourceFork set options used for fsetxattr. */
int rsrc_xattr_options;
/* Xattr "com.apple.ResourceFork". */
unsigned char *resource_fork;
size_t resource_fork_allocated_size;
unsigned int decmpfs_block_count;
uint32_t *decmpfs_block_info;
/* Buffer for compressed data. */
unsigned char *compressed_buffer;
size_t compressed_buffer_size;
size_t compressed_buffer_remaining;
/* The offset of the ResourceFork where compressed data will
* be placed. */
uint32_t compressed_rsrc_position;
uint32_t compressed_rsrc_position_v;
/* Buffer for uncompressed data. */
char *uncompressed_buffer;
size_t block_remaining_bytes;
size_t file_remaining_bytes;
#ifdef HAVE_ZLIB_H
z_stream stream;
int stream_valid;
int decmpfs_compression_level;
#endif
};
/*
* Default mode for dirs created automatically (will be modified by umask).
* Note that POSIX specifies 0777 for implicitly-created dirs, "modified
* by the process' file creation mask."
*/
#define DEFAULT_DIR_MODE 0777
/*
* Dir modes are restored in two steps: During the extraction, the permissions
* in the archive are modified to match the following limits. During
* the post-extract fixup pass, the permissions from the archive are
* applied.
*/
#define MINIMUM_DIR_MODE 0700
#define MAXIMUM_DIR_MODE 0775
/*
* Maxinum uncompressed size of a decmpfs block.
*/
#define MAX_DECMPFS_BLOCK_SIZE (64 * 1024)
/*
* HFS+ compression type.
*/
#define CMP_XATTR 3/* Compressed data in xattr. */
#define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */
/*
* HFS+ compression resource fork.
*/
#define RSRC_H_SIZE 260 /* Base size of Resource fork header. */
#define RSRC_F_SIZE 50 /* Size of Resource fork footer. */
/* Size to write compressed data to resource fork. */
#define COMPRESSED_W_SIZE (64 * 1024)
/* decmpfs difinitions. */
#define MAX_DECMPFS_XATTR_SIZE 3802
#ifndef DECMPFS_XATTR_NAME
#define DECMPFS_XATTR_NAME "com.apple.decmpfs"
#endif
#define DECMPFS_MAGIC 0x636d7066
#define DECMPFS_COMPRESSION_MAGIC 0
#define DECMPFS_COMPRESSION_TYPE 4
#define DECMPFS_UNCOMPRESSED_SIZE 8
#define DECMPFS_HEADER_SIZE 16
#define HFS_BLOCKS(s) ((s) >> 12)
static int check_symlinks(struct archive_write_disk *);
static int create_filesystem_object(struct archive_write_disk *);
static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
static void edit_deep_directories(struct archive_write_disk *ad);
#endif
static int cleanup_pathname(struct archive_write_disk *);
static int create_dir(struct archive_write_disk *, char *);
static int create_parent_dir(struct archive_write_disk *, char *);
static ssize_t hfs_write_data_block(struct archive_write_disk *,
const char *, size_t);
static int fixup_appledouble(struct archive_write_disk *, const char *);
static int older(struct stat *, struct archive_entry *);
static int restore_entry(struct archive_write_disk *);
static int set_mac_metadata(struct archive_write_disk *, const char *,
const void *, size_t);
static int set_xattrs(struct archive_write_disk *);
static int set_fflags(struct archive_write_disk *);
static int set_fflags_platform(struct archive_write_disk *, int fd,
const char *name, mode_t mode,
unsigned long fflags_set, unsigned long fflags_clear);
static int set_ownership(struct archive_write_disk *);
static int set_mode(struct archive_write_disk *, int mode);
static int set_time(int, int, const char *, time_t, long, time_t, long);
static int set_times(struct archive_write_disk *, int, int, const char *,
time_t, long, time_t, long, time_t, long, time_t, long);
static int set_times_from_entry(struct archive_write_disk *);
static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
static ssize_t write_data_block(struct archive_write_disk *,
const char *, size_t);
static struct archive_vtable *archive_write_disk_vtable(void);
static int _archive_write_disk_close(struct archive *);
static int _archive_write_disk_free(struct archive *);
static int _archive_write_disk_header(struct archive *, struct archive_entry *);
static int64_t _archive_write_disk_filter_bytes(struct archive *, int);
static int _archive_write_disk_finish_entry(struct archive *);
static ssize_t _archive_write_disk_data(struct archive *, const void *, size_t);
static ssize_t _archive_write_disk_data_block(struct archive *, const void *, size_t, int64_t);
static int
lazy_stat(struct archive_write_disk *a)
{
if (a->pst != NULL) {
/* Already have stat() data available. */
return (ARCHIVE_OK);
}
#ifdef HAVE_FSTAT
if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
a->pst = &a->st;
return (ARCHIVE_OK);
}
#endif
/*
* XXX At this point, symlinks should not be hit, otherwise
* XXX a race occurred. Do we want to check explicitly for that?
*/
if (lstat(a->name, &a->st) == 0) {
a->pst = &a->st;
return (ARCHIVE_OK);
}
archive_set_error(&a->archive, errno, "Couldn't stat file");
return (ARCHIVE_WARN);
}
static struct archive_vtable *
archive_write_disk_vtable(void)
{
static struct archive_vtable av;
static int inited = 0;
if (!inited) {
av.archive_close = _archive_write_disk_close;
av.archive_filter_bytes = _archive_write_disk_filter_bytes;
av.archive_free = _archive_write_disk_free;
av.archive_write_header = _archive_write_disk_header;
av.archive_write_finish_entry
= _archive_write_disk_finish_entry;
av.archive_write_data = _archive_write_disk_data;
av.archive_write_data_block = _archive_write_disk_data_block;
inited = 1;
}
return (&av);
}
static int64_t
_archive_write_disk_filter_bytes(struct archive *_a, int n)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
(void)n; /* UNUSED */
if (n == -1 || n == 0)
return (a->total_bytes_written);
return (-1);
}
int
archive_write_disk_set_options(struct archive *_a, int flags)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
a->flags = flags;
return (ARCHIVE_OK);
}
/*
* Extract this entry to disk.
*
* TODO: Validate hardlinks. According to the standards, we're
* supposed to check each extracted hardlink and squawk if it refers
* to a file that we didn't restore. I'm not entirely convinced this
* is a good idea, but more importantly: Is there any way to validate
* hardlinks without keeping a complete list of filenames from the
* entire archive?? Ugh.
*
*/
static int
_archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
struct fixup_entry *fe;
int ret, r;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
"archive_write_disk_header");
archive_clear_error(&a->archive);
if (a->archive.state & ARCHIVE_STATE_DATA) {
r = _archive_write_disk_finish_entry(&a->archive);
if (r == ARCHIVE_FATAL)
return (r);
}
/* Set up for this particular entry. */
a->pst = NULL;
a->current_fixup = NULL;
a->deferred = 0;
if (a->entry) {
archive_entry_free(a->entry);
a->entry = NULL;
}
a->entry = archive_entry_clone(entry);
a->fd = -1;
a->fd_offset = 0;
a->offset = 0;
a->restore_pwd = -1;
a->uid = a->user_uid;
a->mode = archive_entry_mode(a->entry);
if (archive_entry_size_is_set(a->entry))
a->filesize = archive_entry_size(a->entry);
else
a->filesize = -1;
archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
a->name = a->_name_data.s;
archive_clear_error(&a->archive);
/*
* Clean up the requested path. This is necessary for correct
* dir restores; the dir restore logic otherwise gets messed
* up by nonsense like "dir/.".
*/
ret = cleanup_pathname(a);
if (ret != ARCHIVE_OK)
return (ret);
/*
* Query the umask so we get predictable mode settings.
* This gets done on every call to _write_header in case the
* user edits their umask during the extraction for some
* reason.
*/
umask(a->user_umask = umask(0));
/* Figure out what we need to do for this entry. */
a->todo = TODO_MODE_BASE;
if (a->flags & ARCHIVE_EXTRACT_PERM) {
a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
/*
* SGID requires an extra "check" step because we
* cannot easily predict the GID that the system will
* assign. (Different systems assign GIDs to files
* based on a variety of criteria, including process
* credentials and the gid of the enclosing
* directory.) We can only restore the SGID bit if
* the file has the right GID, and we only know the
* GID if we either set it (see set_ownership) or if
* we've actually called stat() on the file after it
* was restored. Since there are several places at
* which we might verify the GID, we need a TODO bit
* to keep track.
*/
if (a->mode & S_ISGID)
a->todo |= TODO_SGID | TODO_SGID_CHECK;
/*
* Verifying the SUID is simpler, but can still be
* done in multiple ways, hence the separate "check" bit.
*/
if (a->mode & S_ISUID)
a->todo |= TODO_SUID | TODO_SUID_CHECK;
} else {
/*
* User didn't request full permissions, so don't
* restore SUID, SGID bits and obey umask.
*/
a->mode &= ~S_ISUID;
a->mode &= ~S_ISGID;
a->mode &= ~S_ISVTX;
a->mode &= ~a->user_umask;
}
if (a->flags & ARCHIVE_EXTRACT_OWNER)
a->todo |= TODO_OWNER;
if (a->flags & ARCHIVE_EXTRACT_TIME)
a->todo |= TODO_TIMES;
if (a->flags & ARCHIVE_EXTRACT_ACL) {
if (archive_entry_filetype(a->entry) == AE_IFDIR)
a->deferred |= TODO_ACLS;
else
a->todo |= TODO_ACLS;
}
if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
if (archive_entry_filetype(a->entry) == AE_IFDIR)
a->deferred |= TODO_MAC_METADATA;
else
a->todo |= TODO_MAC_METADATA;
}
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
unsigned long set, clear;
archive_entry_fflags(a->entry, &set, &clear);
if ((set & ~clear) & UF_COMPRESSED) {
a->todo |= TODO_HFS_COMPRESSION;
a->decmpfs_block_count = (unsigned)-1;
}
}
if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
(a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
a->todo |= TODO_HFS_COMPRESSION;
a->decmpfs_block_count = (unsigned)-1;
}
{
const char *p;
/* Check if the current file name is a type of the
* resource fork file. */
p = strrchr(a->name, '/');
if (p == NULL)
p = a->name;
else
p++;
if (p[0] == '.' && p[1] == '_') {
/* Do not compress "._XXX" files. */
a->todo &= ~TODO_HFS_COMPRESSION;
if (a->filesize > 0)
a->todo |= TODO_APPLEDOUBLE;
}
}
#endif
if (a->flags & ARCHIVE_EXTRACT_XATTR)
a->todo |= TODO_XATTR;
if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
a->todo |= TODO_FFLAGS;
if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
ret = check_symlinks(a);
if (ret != ARCHIVE_OK)
return (ret);
}
#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
/* If path exceeds PATH_MAX, shorten the path. */
edit_deep_directories(a);
#endif
ret = restore_entry(a);
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
/*
* Check if the filesystem the file is restoring on supports
* HFS+ Compression. If not, cancel HFS+ Compression.
*/
if (a->todo | TODO_HFS_COMPRESSION) {
/*
* NOTE: UF_COMPRESSED is ignored even if the filesystem
* supports HFS+ Compression because the file should
* have at least an extended attriute "com.apple.decmpfs"
* before the flag is set to indicate that the file have
* been compressed. If hte filesystem does not support
* HFS+ Compression the system call will fail.
*/
if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
a->todo &= ~TODO_HFS_COMPRESSION;
}
#endif
/*
* TODO: There are rumours that some extended attributes must
* be restored before file data is written. If this is true,
* then we either need to write all extended attributes both
* before and after restoring the data, or find some rule for
* determining which must go first and which last. Due to the
* many ways people are using xattrs, this may prove to be an
* intractable problem.
*/
#ifdef HAVE_FCHDIR
/* If we changed directory above, restore it here. */
if (a->restore_pwd >= 0) {
r = fchdir(a->restore_pwd);
if (r != 0) {
archive_set_error(&a->archive, errno, "chdir() failure");
ret = ARCHIVE_FATAL;
}
close(a->restore_pwd);
a->restore_pwd = -1;
}
#endif
/*
* Fixup uses the unedited pathname from archive_entry_pathname(),
* because it is relative to the base dir and the edited path
* might be relative to some intermediate dir as a result of the
* deep restore logic.
*/
if (a->deferred & TODO_MODE) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->fixup |= TODO_MODE_BASE;
fe->mode = a->mode;
}
if ((a->deferred & TODO_TIMES)
&& (archive_entry_mtime_is_set(entry)
|| archive_entry_atime_is_set(entry))) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->mode = a->mode;
fe->fixup |= TODO_TIMES;
if (archive_entry_atime_is_set(entry)) {
fe->atime = archive_entry_atime(entry);
fe->atime_nanos = archive_entry_atime_nsec(entry);
} else {
/* If atime is unset, use start time. */
fe->atime = a->start_time;
fe->atime_nanos = 0;
}
if (archive_entry_mtime_is_set(entry)) {
fe->mtime = archive_entry_mtime(entry);
fe->mtime_nanos = archive_entry_mtime_nsec(entry);
} else {
/* If mtime is unset, use start time. */
fe->mtime = a->start_time;
fe->mtime_nanos = 0;
}
if (archive_entry_birthtime_is_set(entry)) {
fe->birthtime = archive_entry_birthtime(entry);
fe->birthtime_nanos = archive_entry_birthtime_nsec(entry);
} else {
/* If birthtime is unset, use mtime. */
fe->birthtime = fe->mtime;
fe->birthtime_nanos = fe->mtime_nanos;
}
}
if (a->deferred & TODO_ACLS) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->fixup |= TODO_ACLS;
archive_acl_copy(&fe->acl, archive_entry_acl(entry));
}
if (a->deferred & TODO_MAC_METADATA) {
const void *metadata;
size_t metadata_size;
metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
if (metadata != NULL && metadata_size > 0) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->mac_metadata = malloc(metadata_size);
if (fe->mac_metadata != NULL) {
memcpy(fe->mac_metadata, metadata, metadata_size);
fe->mac_metadata_size = metadata_size;
fe->fixup |= TODO_MAC_METADATA;
}
}
}
if (a->deferred & TODO_FFLAGS) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->fixup |= TODO_FFLAGS;
/* TODO: Complete this.. defer fflags from below. */
}
/* We've created the object and are ready to pour data into it. */
if (ret >= ARCHIVE_WARN)
a->archive.state = ARCHIVE_STATE_DATA;
/*
* If it's not open, tell our client not to try writing.
* In particular, dirs, links, etc, don't get written to.
*/
if (a->fd < 0) {
archive_entry_set_size(entry, 0);
a->filesize = 0;
}
return (ret);
}
int
archive_write_disk_set_skip_file(struct archive *_a, int64_t d, int64_t i)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
a->skip_file_set = 1;
a->skip_file_dev = d;
a->skip_file_ino = i;
return (ARCHIVE_OK);
}
static ssize_t
write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
{
uint64_t start_size = size;
ssize_t bytes_written = 0;
ssize_t block_size = 0, bytes_to_write;
if (size == 0)
return (ARCHIVE_OK);
if (a->filesize == 0 || a->fd < 0) {
archive_set_error(&a->archive, 0,
"Attempt to write to an empty file");
return (ARCHIVE_WARN);
}
if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
#if HAVE_STRUCT_STAT_ST_BLKSIZE
int r;
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
block_size = a->pst->st_blksize;
#else
/* XXX TODO XXX Is there a more appropriate choice here ? */
/* This needn't match the filesystem allocation size. */
block_size = 16*1024;
#endif
}
/* If this write would run beyond the file size, truncate it. */
if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
start_size = size = (size_t)(a->filesize - a->offset);
/* Write the data. */
while (size > 0) {
if (block_size == 0) {
bytes_to_write = size;
} else {
/* We're sparsifying the file. */
const char *p, *end;
int64_t block_end;
/* Skip leading zero bytes. */
for (p = buff, end = buff + size; p < end; ++p) {
if (*p != '\0')
break;
}
a->offset += p - buff;
size -= p - buff;
buff = p;
if (size == 0)
break;
/* Calculate next block boundary after offset. */
block_end
= (a->offset / block_size + 1) * block_size;
/* If the adjusted write would cross block boundary,
* truncate it to the block boundary. */
bytes_to_write = size;
if (a->offset + bytes_to_write > block_end)
bytes_to_write = block_end - a->offset;
}
/* Seek if necessary to the specified offset. */
if (a->offset != a->fd_offset) {
if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
archive_set_error(&a->archive, errno,
"Seek failed");
return (ARCHIVE_FATAL);
}
a->fd_offset = a->offset;
}
bytes_written = write(a->fd, buff, bytes_to_write);
if (bytes_written < 0) {
archive_set_error(&a->archive, errno, "Write failed");
return (ARCHIVE_WARN);
}
buff += bytes_written;
size -= bytes_written;
a->total_bytes_written += bytes_written;
a->offset += bytes_written;
a->fd_offset = a->offset;
}
return (start_size - size);
}
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
&& defined(HAVE_ZLIB_H)
/*
* Set UF_COMPRESSED file flag.
* This have to be called after hfs_write_decmpfs() because if the
* file does not have "com.apple.decmpfs" xattr the flag is ignored.
*/
static int
hfs_set_compressed_fflag(struct archive_write_disk *a)
{
int r;
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
a->st.st_flags |= UF_COMPRESSED;
if (fchflags(a->fd, a->st.st_flags) != 0) {
archive_set_error(&a->archive, errno,
"Failed to set UF_COMPRESSED file flag");
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
/*
* HFS+ Compression decmpfs
*
* +------------------------------+ +0
* | Magic(LE 4 bytes) |
* +------------------------------+
* | Type(LE 4 bytes) |
* +------------------------------+
* | Uncompressed size(LE 8 bytes)|
* +------------------------------+ +16
* | |
* | Compressed data |
* | (Placed only if Type == 3) |
* | |
* +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE
*
* Type is 3: decmpfs has compressed data.
* Type is 4: Resource Fork has compressed data.
*/
/*
* Write "com.apple.decmpfs"
*/
static int
hfs_write_decmpfs(struct archive_write_disk *a)
{
int r;
uint32_t compression_type;
r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
a->decmpfs_attr_size, 0, 0);
if (r < 0) {
archive_set_error(&a->archive, errno,
"Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
compression_type = archive_le32dec(
&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
if (compression_type == CMP_RESOURCE_FORK)
fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
XATTR_SHOWCOMPRESSION);
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
/*
* HFS+ Compression Resource Fork
*
* +-----------------------------+
* | Header(260 bytes) |
* +-----------------------------+
* | Block count(LE 4 bytes) |
* +-----------------------------+ --+
* +-- | Offset (LE 4 bytes) | |
* | | [distance from Block count] | | Block 0
* | +-----------------------------+ |
* | | Compressed size(LE 4 bytes) | |
* | +-----------------------------+ --+
* | | |
* | | .................. |
* | | |
* | +-----------------------------+ --+
* | | Offset (LE 4 bytes) | |
* | +-----------------------------+ | Block (Block count -1)
* | | Compressed size(LE 4 bytes) | |
* +-> +-----------------------------+ --+
* | Compressed data(n bytes) | Block 0
* +-----------------------------+
* | |
* | .................. |
* | |
* +-----------------------------+
* | Compressed data(n bytes) | Block (Block count -1)
* +-----------------------------+
* | Footer(50 bytes) |
* +-----------------------------+
*
*/
/*
* Write the header of "com.apple.ResourceFork"
*/
static int
hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
size_t bytes, uint32_t position)
{
int ret;
ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
position, a->rsrc_xattr_options);
if (ret < 0) {
archive_set_error(&a->archive, errno,
"Cannot restore xattr: %s at %u pos %u bytes",
XATTR_RESOURCEFORK_NAME,
(unsigned)position,
(unsigned)bytes);
return (ARCHIVE_WARN);
}
a->rsrc_xattr_options &= ~XATTR_CREATE;
return (ARCHIVE_OK);
}
static int
hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
{
int ret;
ret = hfs_write_resource_fork(a, a->compressed_buffer,
bytes_compressed, a->compressed_rsrc_position);
if (ret == ARCHIVE_OK)
a->compressed_rsrc_position += bytes_compressed;
return (ret);
}
static int
hfs_write_resource_fork_header(struct archive_write_disk *a)
{
unsigned char *buff;
uint32_t rsrc_bytes;
uint32_t rsrc_header_bytes;
/*
* Write resource fork header + block info.
*/
buff = a->resource_fork;
rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
rsrc_header_bytes =
RSRC_H_SIZE + /* Header base size. */
4 + /* Block count. */
(a->decmpfs_block_count * 8);/* Block info */
archive_be32enc(buff, 0x100);
archive_be32enc(buff + 4, rsrc_bytes);
archive_be32enc(buff + 8, rsrc_bytes - 256);
archive_be32enc(buff + 12, 0x32);
memset(buff + 16, 0, 240);
archive_be32enc(buff + 256, rsrc_bytes - 260);
return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
}
static size_t
hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
{
static const char rsrc_footer[RSRC_F_SIZE] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm',
'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00
};
if (buff_size < sizeof(rsrc_footer))
return (0);
memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
return (sizeof(rsrc_footer));
}
static int
hfs_reset_compressor(struct archive_write_disk *a)
{
int ret;
if (a->stream_valid)
ret = deflateReset(&a->stream);
else
ret = deflateInit(&a->stream, a->decmpfs_compression_level);
if (ret != Z_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to initialize compressor");
return (ARCHIVE_FATAL);
} else
a->stream_valid = 1;
return (ARCHIVE_OK);
}
static int
hfs_decompress(struct archive_write_disk *a)
{
uint32_t *block_info;
unsigned int block_count;
uint32_t data_pos, data_size;
ssize_t r;
ssize_t bytes_written, bytes_to_write;
unsigned char *b;
block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
block_count = archive_le32dec(block_info++);
while (block_count--) {
data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
data_size = archive_le32dec(block_info++);
r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
a->compressed_buffer, data_size, data_pos, 0);
if (r != data_size) {
archive_set_error(&a->archive,
(r < 0)?errno:ARCHIVE_ERRNO_MISC,
"Failed to read resource fork");
return (ARCHIVE_WARN);
}
if (a->compressed_buffer[0] == 0xff) {
bytes_to_write = data_size -1;
b = a->compressed_buffer + 1;
} else {
uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
int zr;
zr = uncompress((Bytef *)a->uncompressed_buffer,
&dest_len, a->compressed_buffer, data_size);
if (zr != Z_OK) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Failed to decompress resource fork");
return (ARCHIVE_WARN);
}
bytes_to_write = dest_len;
b = (unsigned char *)a->uncompressed_buffer;
}
do {
bytes_written = write(a->fd, b, bytes_to_write);
if (bytes_written < 0) {
archive_set_error(&a->archive, errno,
"Write failed");
return (ARCHIVE_WARN);
}
bytes_to_write -= bytes_written;
b += bytes_written;
} while (bytes_to_write > 0);
}
r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
if (r == -1) {
archive_set_error(&a->archive, errno,
"Failed to remove resource fork");
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
static int
hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
size_t size)
{
unsigned char *buffer_compressed;
size_t bytes_compressed;
size_t bytes_used;
int ret;
ret = hfs_reset_compressor(a);
if (ret != ARCHIVE_OK)
return (ret);
if (a->compressed_buffer == NULL) {
size_t block_size;
block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
+ compressBound(MAX_DECMPFS_BLOCK_SIZE);
a->compressed_buffer = malloc(block_size);
if (a->compressed_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Resource Fork");
return (ARCHIVE_FATAL);
}
a->compressed_buffer_size = block_size;
a->compressed_buffer_remaining = block_size;
}
buffer_compressed = a->compressed_buffer +
a->compressed_buffer_size - a->compressed_buffer_remaining;
a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
a->stream.avail_in = size;
a->stream.next_out = buffer_compressed;
a->stream.avail_out = a->compressed_buffer_remaining;
do {
ret = deflate(&a->stream, Z_FINISH);
switch (ret) {
case Z_OK:
case Z_STREAM_END:
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to compress data");
return (ARCHIVE_FAILED);
}
} while (ret == Z_OK);
bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
/*
* If the compressed size is larger than the original size,
* throw away compressed data, use uncompressed data instead.
*/
if (bytes_compressed > size) {
buffer_compressed[0] = 0xFF;/* uncompressed marker. */
memcpy(buffer_compressed + 1, buff, size);
bytes_compressed = size + 1;
}
a->compressed_buffer_remaining -= bytes_compressed;
/*
* If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
* and the block count in the file is only one, store compressed
* data to decmpfs xattr instead of the resource fork.
*/
if (a->decmpfs_block_count == 1 &&
(a->decmpfs_attr_size + bytes_compressed)
<= MAX_DECMPFS_XATTR_SIZE) {
archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
CMP_XATTR);
memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
buffer_compressed, bytes_compressed);
a->decmpfs_attr_size += bytes_compressed;
a->compressed_buffer_remaining = a->compressed_buffer_size;
/*
* Finish HFS+ Compression.
* - Write the decmpfs xattr.
* - Set the UF_COMPRESSED file flag.
*/
ret = hfs_write_decmpfs(a);
if (ret == ARCHIVE_OK)
ret = hfs_set_compressed_fflag(a);
return (ret);
}
/* Update block info. */
archive_le32enc(a->decmpfs_block_info++,
a->compressed_rsrc_position_v - RSRC_H_SIZE);
archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
a->compressed_rsrc_position_v += bytes_compressed;
/*
* Write the compressed data to the resource fork.
*/
bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
while (bytes_used >= COMPRESSED_W_SIZE) {
ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
if (ret != ARCHIVE_OK)
return (ret);
bytes_used -= COMPRESSED_W_SIZE;
if (bytes_used > COMPRESSED_W_SIZE)
memmove(a->compressed_buffer,
a->compressed_buffer + COMPRESSED_W_SIZE,
bytes_used);
else
memcpy(a->compressed_buffer,
a->compressed_buffer + COMPRESSED_W_SIZE,
bytes_used);
}
a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
/*
* If the current block is the last block, write the remaining
* compressed data and the resource fork footer.
*/
if (a->file_remaining_bytes == 0) {
size_t rsrc_size;
int64_t bk;
/* Append the resource footer. */
rsrc_size = hfs_set_resource_fork_footer(
a->compressed_buffer + bytes_used,
a->compressed_buffer_remaining);
ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
a->compressed_buffer_remaining = a->compressed_buffer_size;
/* If the compressed size is not enouph smaller than
* the uncompressed size. cancel HFS+ compression.
* TODO: study a behavior of ditto utility and improve
* the condition to fall back into no HFS+ compression. */
bk = HFS_BLOCKS(a->compressed_rsrc_position);
bk += bk >> 7;
if (bk > HFS_BLOCKS(a->filesize))
return hfs_decompress(a);
/*
* Write the resourcefork header.
*/
if (ret == ARCHIVE_OK)
ret = hfs_write_resource_fork_header(a);
/*
* Finish HFS+ Compression.
* - Write the decmpfs xattr.
* - Set the UF_COMPRESSED file flag.
*/
if (ret == ARCHIVE_OK)
ret = hfs_write_decmpfs(a);
if (ret == ARCHIVE_OK)
ret = hfs_set_compressed_fflag(a);
}
return (ret);
}
static ssize_t
hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
size_t size)
{
const char *buffer_to_write;
size_t bytes_to_write;
int ret;
if (a->decmpfs_block_count == (unsigned)-1) {
void *new_block;
size_t new_size;
unsigned int block_count;
if (a->decmpfs_header_p == NULL) {
new_block = malloc(MAX_DECMPFS_XATTR_SIZE
+ sizeof(uint32_t));
if (new_block == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for decmpfs");
return (ARCHIVE_FATAL);
}
a->decmpfs_header_p = new_block;
}
a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
DECMPFS_MAGIC);
archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
CMP_RESOURCE_FORK);
archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
a->filesize);
/* Calculate a block count of the file. */
block_count =
(a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
MAX_DECMPFS_BLOCK_SIZE;
/*
* Allocate buffer for resource fork.
* Set up related pointers;
*/
new_size =
RSRC_H_SIZE + /* header */
4 + /* Block count */
(block_count * sizeof(uint32_t) * 2) +
RSRC_F_SIZE; /* footer */
if (new_size > a->resource_fork_allocated_size) {
new_block = realloc(a->resource_fork, new_size);
if (new_block == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for ResourceFork");
return (ARCHIVE_FATAL);
}
a->resource_fork_allocated_size = new_size;
a->resource_fork = new_block;
}
/* Allocate uncompressed buffer */
if (a->uncompressed_buffer == NULL) {
new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
if (new_block == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for decmpfs");
return (ARCHIVE_FATAL);
}
a->uncompressed_buffer = new_block;
}
a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
a->file_remaining_bytes = a->filesize;
a->compressed_buffer_remaining = a->compressed_buffer_size;
/*
* Set up a resource fork.
*/
a->rsrc_xattr_options = XATTR_CREATE;
/* Get the position where we are going to set a bunch
* of block info. */
a->decmpfs_block_info =
(uint32_t *)(a->resource_fork + RSRC_H_SIZE);
/* Set the block count to the resource fork. */
archive_le32enc(a->decmpfs_block_info++, block_count);
/* Get the position where we are goint to set compressed
* data. */
a->compressed_rsrc_position =
RSRC_H_SIZE + 4 + (block_count * 8);
a->compressed_rsrc_position_v = a->compressed_rsrc_position;
a->decmpfs_block_count = block_count;
}
/* Ignore redundant bytes. */
if (a->file_remaining_bytes == 0)
return ((ssize_t)size);
/* Do not overrun a block size. */
if (size > a->block_remaining_bytes)
bytes_to_write = a->block_remaining_bytes;
else
bytes_to_write = size;
/* Do not overrun the file size. */
if (bytes_to_write > a->file_remaining_bytes)
bytes_to_write = a->file_remaining_bytes;
/* For efficiency, if a copy length is full of the uncompressed
* buffer size, do not copy writing data to it. */
if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
buffer_to_write = buff;
else {
memcpy(a->uncompressed_buffer +
MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
buff, bytes_to_write);
buffer_to_write = a->uncompressed_buffer;
}
a->block_remaining_bytes -= bytes_to_write;
a->file_remaining_bytes -= bytes_to_write;
if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
ret = hfs_drive_compressor(a, buffer_to_write,
MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
if (ret < 0)
return (ret);
a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
}
/* Ignore redundant bytes. */
if (a->file_remaining_bytes == 0)
return ((ssize_t)size);
return (bytes_to_write);
}
static ssize_t
hfs_write_data_block(struct archive_write_disk *a, const char *buff,
size_t size)
{
uint64_t start_size = size;
ssize_t bytes_written = 0;
ssize_t bytes_to_write;
if (size == 0)
return (ARCHIVE_OK);
if (a->filesize == 0 || a->fd < 0) {
archive_set_error(&a->archive, 0,
"Attempt to write to an empty file");
return (ARCHIVE_WARN);
}
/* If this write would run beyond the file size, truncate it. */
if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
start_size = size = (size_t)(a->filesize - a->offset);
/* Write the data. */
while (size > 0) {
bytes_to_write = size;
/* Seek if necessary to the specified offset. */
if (a->offset < a->fd_offset) {
/* Can't support backword move. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Seek failed");
return (ARCHIVE_FATAL);
} else if (a->offset > a->fd_offset) {
int64_t skip = a->offset - a->fd_offset;
char nullblock[1024];
memset(nullblock, 0, sizeof(nullblock));
while (skip > 0) {
if (skip > (int64_t)sizeof(nullblock))
bytes_written = hfs_write_decmpfs_block(
a, nullblock, sizeof(nullblock));
else
bytes_written = hfs_write_decmpfs_block(
a, nullblock, skip);
if (bytes_written < 0) {
archive_set_error(&a->archive, errno,
"Write failed");
return (ARCHIVE_WARN);
}
skip -= bytes_written;
}
a->fd_offset = a->offset;
}
bytes_written =
hfs_write_decmpfs_block(a, buff, bytes_to_write);
if (bytes_written < 0)
return (bytes_written);
buff += bytes_written;
size -= bytes_written;
a->total_bytes_written += bytes_written;
a->offset += bytes_written;
a->fd_offset = a->offset;
}
return (start_size - size);
}
#else
static ssize_t
hfs_write_data_block(struct archive_write_disk *a, const char *buff,
size_t size)
{
return (write_data_block(a, buff, size));
}
#endif
static ssize_t
_archive_write_disk_data_block(struct archive *_a,
const void *buff, size_t size, int64_t offset)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
ssize_t r;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_DATA, "archive_write_data_block");
a->offset = offset;
if (a->todo & TODO_HFS_COMPRESSION)
r = hfs_write_data_block(a, buff, size);
else
r = write_data_block(a, buff, size);
if (r < ARCHIVE_OK)
return (r);
if ((size_t)r < size) {
archive_set_error(&a->archive, 0,
"Write request too large");
return (ARCHIVE_WARN);
}
#if ARCHIVE_VERSION_NUMBER < 3999000
return (ARCHIVE_OK);
#else
return (size);
#endif
}
static ssize_t
_archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_DATA, "archive_write_data");
if (a->todo & TODO_HFS_COMPRESSION)
return (hfs_write_data_block(a, buff, size));
return (write_data_block(a, buff, size));
}
static int
_archive_write_disk_finish_entry(struct archive *_a)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
int ret = ARCHIVE_OK;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
"archive_write_finish_entry");
if (a->archive.state & ARCHIVE_STATE_HEADER)
return (ARCHIVE_OK);
archive_clear_error(&a->archive);
/* Pad or truncate file to the right size. */
if (a->fd < 0) {
/* There's no file. */
} else if (a->filesize < 0) {
/* File size is unknown, so we can't set the size. */
} else if (a->fd_offset == a->filesize) {
/* Last write ended at exactly the filesize; we're done. */
/* Hopefully, this is the common case. */
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
} else if (a->todo & TODO_HFS_COMPRESSION) {
char null_d[1024];
ssize_t r;
if (a->file_remaining_bytes)
memset(null_d, 0, sizeof(null_d));
while (a->file_remaining_bytes) {
if (a->file_remaining_bytes > sizeof(null_d))
r = hfs_write_data_block(
a, null_d, sizeof(null_d));
else
r = hfs_write_data_block(
a, null_d, a->file_remaining_bytes);
if (r < 0)
return ((int)r);
}
#endif
} else {
#if HAVE_FTRUNCATE
if (ftruncate(a->fd, a->filesize) == -1 &&
a->filesize == 0) {
archive_set_error(&a->archive, errno,
"File size could not be restored");
return (ARCHIVE_FAILED);
}
#endif
/*
* Not all platforms implement the XSI option to
* extend files via ftruncate. Stat() the file again
* to see what happened.
*/
a->pst = NULL;
if ((ret = lazy_stat(a)) != ARCHIVE_OK)
return (ret);
/* We can use lseek()/write() to extend the file if
* ftruncate didn't work or isn't available. */
if (a->st.st_size < a->filesize) {
const char nul = '\0';
if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
archive_set_error(&a->archive, errno,
"Seek failed");
return (ARCHIVE_FATAL);
}
if (write(a->fd, &nul, 1) < 0) {
archive_set_error(&a->archive, errno,
"Write to restore size failed");
return (ARCHIVE_FATAL);
}
a->pst = NULL;
}
}
/* Restore metadata. */
/*
* This is specific to Mac OS X.
* If the current file is an AppleDouble file, it should be
* linked with the data fork file and remove it.
*/
if (a->todo & TODO_APPLEDOUBLE) {
int r2 = fixup_appledouble(a, a->name);
if (r2 == ARCHIVE_EOF) {
/* The current file has been successfully linked
* with the data fork file and removed. So there
* is nothing to do on the current file. */
goto finish_metadata;
}
if (r2 < ret) ret = r2;
}
/*
* Look up the "real" UID only if we're going to need it.
* TODO: the TODO_SGID condition can be dropped here, can't it?
*/
if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
a->uid = archive_write_disk_uid(&a->archive,
archive_entry_uname(a->entry),
archive_entry_uid(a->entry));
}
/* Look up the "real" GID only if we're going to need it. */
/* TODO: the TODO_SUID condition can be dropped here, can't it? */
if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
a->gid = archive_write_disk_gid(&a->archive,
archive_entry_gname(a->entry),
archive_entry_gid(a->entry));
}
/*
* Restore ownership before set_mode tries to restore suid/sgid
* bits. If we set the owner, we know what it is and can skip
* a stat() call to examine the ownership of the file on disk.
*/
if (a->todo & TODO_OWNER) {
int r2 = set_ownership(a);
if (r2 < ret) ret = r2;
}
/*
* set_mode must precede ACLs on systems such as Solaris and
* FreeBSD where setting the mode implicitly clears extended ACLs
*/
if (a->todo & TODO_MODE) {
int r2 = set_mode(a, a->mode);
if (r2 < ret) ret = r2;
}
/*
* Security-related extended attributes (such as
* security.capability on Linux) have to be restored last,
* since they're implicitly removed by other file changes.
*/
if (a->todo & TODO_XATTR) {
int r2 = set_xattrs(a);
if (r2 < ret) ret = r2;
}
/*
* Some flags prevent file modification; they must be restored after
* file contents are written.
*/
if (a->todo & TODO_FFLAGS) {
int r2 = set_fflags(a);
if (r2 < ret) ret = r2;
}
/*
* Time must follow most other metadata;
* otherwise atime will get changed.
*/
if (a->todo & TODO_TIMES) {
int r2 = set_times_from_entry(a);
if (r2 < ret) ret = r2;
}
/*
* Mac extended metadata includes ACLs.
*/
if (a->todo & TODO_MAC_METADATA) {
const void *metadata;
size_t metadata_size;
metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
if (metadata != NULL && metadata_size > 0) {
int r2 = set_mac_metadata(a, archive_entry_pathname(
a->entry), metadata, metadata_size);
if (r2 < ret) ret = r2;
}
}
/*
* ACLs must be restored after timestamps because there are
* ACLs that prevent attribute changes (including time).
*/
if (a->todo & TODO_ACLS) {
int r2 = archive_write_disk_set_acls(&a->archive, a->fd,
archive_entry_pathname(a->entry),
archive_entry_acl(a->entry));
if (r2 < ret) ret = r2;
}
finish_metadata:
/* If there's an fd, we can close it now. */
if (a->fd >= 0) {
close(a->fd);
a->fd = -1;
}
/* If there's an entry, we can release it now. */
if (a->entry) {
archive_entry_free(a->entry);
a->entry = NULL;
}
a->archive.state = ARCHIVE_STATE_HEADER;
return (ret);
}
int
archive_write_disk_set_group_lookup(struct archive *_a,
void *private_data,
int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid),
void (*cleanup_gid)(void *private))
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
(a->cleanup_gid)(a->lookup_gid_data);
a->lookup_gid = lookup_gid;
a->cleanup_gid = cleanup_gid;
a->lookup_gid_data = private_data;
return (ARCHIVE_OK);
}
int
archive_write_disk_set_user_lookup(struct archive *_a,
void *private_data,
int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
void (*cleanup_uid)(void *private))
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
(a->cleanup_uid)(a->lookup_uid_data);
a->lookup_uid = lookup_uid;
a->cleanup_uid = cleanup_uid;
a->lookup_uid_data = private_data;
return (ARCHIVE_OK);
}
int64_t
archive_write_disk_gid(struct archive *_a, const char *name, int64_t id)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_gid");
if (a->lookup_gid)
return (a->lookup_gid)(a->lookup_gid_data, name, id);
return (id);
}
int64_t
archive_write_disk_uid(struct archive *_a, const char *name, int64_t id)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_uid");
if (a->lookup_uid)
return (a->lookup_uid)(a->lookup_uid_data, name, id);
return (id);
}
/*
* Create a new archive_write_disk object and initialize it with global state.
*/
struct archive *
archive_write_disk_new(void)
{
struct archive_write_disk *a;
a = (struct archive_write_disk *)malloc(sizeof(*a));
if (a == NULL)
return (NULL);
memset(a, 0, sizeof(*a));
a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
/* We're ready to write a header immediately. */
a->archive.state = ARCHIVE_STATE_HEADER;
a->archive.vtable = archive_write_disk_vtable();
a->start_time = time(NULL);
/* Query and restore the umask. */
umask(a->user_umask = umask(0));
#ifdef HAVE_GETEUID
a->user_uid = geteuid();
#endif /* HAVE_GETEUID */
if (archive_string_ensure(&a->path_safe, 512) == NULL) {
free(a);
return (NULL);
}
#ifdef HAVE_ZLIB_H
a->decmpfs_compression_level = 5;
#endif
return (&a->archive);
}
/*
* If pathname is longer than PATH_MAX, chdir to a suitable
* intermediate dir and edit the path down to a shorter suffix. Note
* that this routine never returns an error; if the chdir() attempt
* fails for any reason, we just go ahead with the long pathname. The
* object creation is likely to fail, but any error will get handled
* at that time.
*/
#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
static void
edit_deep_directories(struct archive_write_disk *a)
{
int ret;
char *tail = a->name;
/* If path is short, avoid the open() below. */
if (strlen(tail) <= PATH_MAX)
return;
/* Try to record our starting dir. */
a->restore_pwd = open(".", O_RDONLY | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(a->restore_pwd);
if (a->restore_pwd < 0)
return;
/* As long as the path is too long... */
while (strlen(tail) > PATH_MAX) {
/* Locate a dir prefix shorter than PATH_MAX. */
tail += PATH_MAX - 8;
while (tail > a->name && *tail != '/')
tail--;
/* Exit if we find a too-long path component. */
if (tail <= a->name)
return;
/* Create the intermediate dir and chdir to it. */
*tail = '\0'; /* Terminate dir portion */
ret = create_dir(a, a->name);
if (ret == ARCHIVE_OK && chdir(a->name) != 0)
ret = ARCHIVE_FAILED;
*tail = '/'; /* Restore the / we removed. */
if (ret != ARCHIVE_OK)
return;
tail++;
/* The chdir() succeeded; we've now shortened the path. */
a->name = tail;
}
return;
}
#endif
/*
* The main restore function.
*/
static int
restore_entry(struct archive_write_disk *a)
{
int ret = ARCHIVE_OK, en;
if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
/*
* TODO: Fix this. Apparently, there are platforms
* that still allow root to hose the entire filesystem
* by unlinking a dir. The S_ISDIR() test above
* prevents us from using unlink() here if the new
* object is a dir, but that doesn't mean the old
* object isn't a dir.
*/
if (unlink(a->name) == 0) {
/* We removed it, reset cached stat. */
a->pst = NULL;
} else if (errno == ENOENT) {
/* File didn't exist, that's just as good. */
} else if (rmdir(a->name) == 0) {
/* It was a dir, but now it's gone. */
a->pst = NULL;
} else {
/* We tried, but couldn't get rid of it. */
archive_set_error(&a->archive, errno,
"Could not unlink");
return(ARCHIVE_FAILED);
}
}
/* Try creating it first; if this fails, we'll try to recover. */
en = create_filesystem_object(a);
if ((en == ENOTDIR || en == ENOENT)
&& !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
/* If the parent dir doesn't exist, try creating it. */
create_parent_dir(a, a->name);
/* Now try to create the object again. */
en = create_filesystem_object(a);
}
if ((en == EISDIR || en == EEXIST)
&& (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
/* If we're not overwriting, we're done. */
archive_entry_unset_size(a->entry);
return (ARCHIVE_OK);
}
/*
* Some platforms return EISDIR if you call
* open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
* return EEXIST. POSIX is ambiguous, requiring EISDIR
* for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
* on an existing item.
*/
if (en == EISDIR) {
/* A dir is in the way of a non-dir, rmdir it. */
if (rmdir(a->name) != 0) {
archive_set_error(&a->archive, errno,
"Can't remove already-existing dir");
return (ARCHIVE_FAILED);
}
a->pst = NULL;
/* Try again. */
en = create_filesystem_object(a);
} else if (en == EEXIST) {
/*
* We know something is in the way, but we don't know what;
* we need to find out before we go any further.
*/
int r = 0;
/*
* The SECURE_SYMLINKS logic has already removed a
* symlink to a dir if the client wants that. So
* follow the symlink if we're creating a dir.
*/
if (S_ISDIR(a->mode))
r = stat(a->name, &a->st);
/*
* If it's not a dir (or it's a broken symlink),
* then don't follow it.
*/
if (r != 0 || !S_ISDIR(a->mode))
r = lstat(a->name, &a->st);
if (r != 0) {
archive_set_error(&a->archive, errno,
"Can't stat existing object");
return (ARCHIVE_FAILED);
}
/*
* NO_OVERWRITE_NEWER doesn't apply to directories.
*/
if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
&& !S_ISDIR(a->st.st_mode)) {
if (!older(&(a->st), a->entry)) {
archive_entry_unset_size(a->entry);
return (ARCHIVE_OK);
}
}
/* If it's our archive, we're done. */
if (a->skip_file_set &&
a->st.st_dev == (dev_t)a->skip_file_dev &&
a->st.st_ino == (ino_t)a->skip_file_ino) {
archive_set_error(&a->archive, 0,
"Refusing to overwrite archive");
return (ARCHIVE_FAILED);
}
if (!S_ISDIR(a->st.st_mode)) {
/* A non-dir is in the way, unlink it. */
if (unlink(a->name) != 0) {
archive_set_error(&a->archive, errno,
"Can't unlink already-existing object");
return (ARCHIVE_FAILED);
}
a->pst = NULL;
/* Try again. */
en = create_filesystem_object(a);
} else if (!S_ISDIR(a->mode)) {
/* A dir is in the way of a non-dir, rmdir it. */
if (rmdir(a->name) != 0) {
archive_set_error(&a->archive, errno,
"Can't replace existing directory with non-directory");
return (ARCHIVE_FAILED);
}
/* Try again. */
en = create_filesystem_object(a);
} else {
/*
* There's a dir in the way of a dir. Don't
* waste time with rmdir()/mkdir(), just fix
* up the permissions on the existing dir.
* Note that we don't change perms on existing
* dirs unless _EXTRACT_PERM is specified.
*/
if ((a->mode != a->st.st_mode)
&& (a->todo & TODO_MODE_FORCE))
a->deferred |= (a->todo & TODO_MODE);
/* Ownership doesn't need deferred fixup. */
en = 0; /* Forget the EEXIST. */
}
}
if (en) {
/* Everything failed; give up here. */
archive_set_error(&a->archive, en, "Can't create '%s'",
a->name);
return (ARCHIVE_FAILED);
}
a->pst = NULL; /* Cached stat data no longer valid. */
return (ret);
}
/*
* Returns 0 if creation succeeds, or else returns errno value from
* the failed system call. Note: This function should only ever perform
* a single system call.
*/
static int
create_filesystem_object(struct archive_write_disk *a)
{
/* Create the entry. */
const char *linkname;
mode_t final_mode, mode;
int r;
/* We identify hard/symlinks according to the link names. */
/* Since link(2) and symlink(2) don't handle modes, we're done here. */
linkname = archive_entry_hardlink(a->entry);
if (linkname != NULL) {
#if !HAVE_LINK
return (EPERM);
#else
r = link(linkname, a->name) ? errno : 0;
/*
* New cpio and pax formats allow hardlink entries
* to carry data, so we may have to open the file
* for hardlink entries.
*
* If the hardlink was successfully created and
* the archive doesn't have carry data for it,
* consider it to be non-authoritative for meta data.
* This is consistent with GNU tar and BSD pax.
* If the hardlink does carry data, let the last
* archive entry decide ownership.
*/
if (r == 0 && a->filesize <= 0) {
a->todo = 0;
a->deferred = 0;
} else if (r == 0 && a->filesize > 0) {
a->fd = open(a->name,
O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(a->fd);
if (a->fd < 0)
r = errno;
}
return (r);
#endif
}
linkname = archive_entry_symlink(a->entry);
if (linkname != NULL) {
#if HAVE_SYMLINK
return symlink(linkname, a->name) ? errno : 0;
#else
return (EPERM);
#endif
}
/*
* The remaining system calls all set permissions, so let's
* try to take advantage of that to avoid an extra chmod()
* call. (Recall that umask is set to zero right now!)
*/
/* Mode we want for the final restored object (w/o file type bits). */
final_mode = a->mode & 07777;
/*
* The mode that will actually be restored in this step. Note
* that SUID, SGID, etc, require additional work to ensure
* security, so we never restore them at this point.
*/
mode = final_mode & 0777 & ~a->user_umask;
switch (a->mode & AE_IFMT) {
default:
/* POSIX requires that we fall through here. */
/* FALLTHROUGH */
case AE_IFREG:
a->fd = open(a->name,
O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
__archive_ensure_cloexec_flag(a->fd);
r = (a->fd < 0);
break;
case AE_IFCHR:
#ifdef HAVE_MKNOD
/* Note: we use AE_IFCHR for the case label, and
* S_IFCHR for the mknod() call. This is correct. */
r = mknod(a->name, mode | S_IFCHR,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a char device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFBLK:
#ifdef HAVE_MKNOD
r = mknod(a->name, mode | S_IFBLK,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a block device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFDIR:
mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
r = mkdir(a->name, mode);
if (r == 0) {
/* Defer setting dir times. */
a->deferred |= (a->todo & TODO_TIMES);
a->todo &= ~TODO_TIMES;
/* Never use an immediate chmod(). */
/* We can't avoid the chmod() entirely if EXTRACT_PERM
* because of SysV SGID inheritance. */
if ((mode != final_mode)
|| (a->flags & ARCHIVE_EXTRACT_PERM))
a->deferred |= (a->todo & TODO_MODE);
a->todo &= ~TODO_MODE;
}
break;
case AE_IFIFO:
#ifdef HAVE_MKFIFO
r = mkfifo(a->name, mode);
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a fifo. */
return (EINVAL);
#endif /* HAVE_MKFIFO */
}
/* All the system calls above set errno on failure. */
if (r)
return (errno);
/* If we managed to set the final mode, we've avoided a chmod(). */
if (mode == final_mode)
a->todo &= ~TODO_MODE;
return (0);
}
/*
* Cleanup function for archive_extract. Mostly, this involves processing
* the fixup list, which is used to address a number of problems:
* * Dir permissions might prevent us from restoring a file in that
* dir, so we restore the dir with minimum 0700 permissions first,
* then correct the mode at the end.
* * Similarly, the act of restoring a file touches the directory
* and changes the timestamp on the dir, so we have to touch-up dir
* timestamps at the end as well.
* * Some file flags can interfere with the restore by, for example,
* preventing the creation of hardlinks to those files.
* * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
*
* Note that tar/cpio do not require that archives be in a particular
* order; there is no way to know when the last file has been restored
* within a directory, so there's no way to optimize the memory usage
* here by fixing up the directory any earlier than the
* end-of-archive.
*
* XXX TODO: Directory ACLs should be restored here, for the same
* reason we set directory perms here. XXX
*/
static int
_archive_write_disk_close(struct archive *_a)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
struct fixup_entry *next, *p;
int ret;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
"archive_write_disk_close");
ret = _archive_write_disk_finish_entry(&a->archive);
/* Sort dir list so directories are fixed up in depth-first order. */
p = sort_dir_list(a->fixup_list);
while (p != NULL) {
a->pst = NULL; /* Mark stat cache as out-of-date. */
if (p->fixup & TODO_TIMES) {
set_times(a, -1, p->mode, p->name,
p->atime, p->atime_nanos,
p->birthtime, p->birthtime_nanos,
p->mtime, p->mtime_nanos,
p->ctime, p->ctime_nanos);
}
if (p->fixup & TODO_MODE_BASE)
chmod(p->name, p->mode);
if (p->fixup & TODO_ACLS)
archive_write_disk_set_acls(&a->archive,
-1, p->name, &p->acl);
if (p->fixup & TODO_FFLAGS)
set_fflags_platform(a, -1, p->name,
p->mode, p->fflags_set, 0);
if (p->fixup & TODO_MAC_METADATA)
set_mac_metadata(a, p->name, p->mac_metadata,
p->mac_metadata_size);
next = p->next;
archive_acl_clear(&p->acl);
free(p->mac_metadata);
free(p->name);
free(p);
p = next;
}
a->fixup_list = NULL;
return (ret);
}
static int
_archive_write_disk_free(struct archive *_a)
{
struct archive_write_disk *a;
int ret;
if (_a == NULL)
return (ARCHIVE_OK);
archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
a = (struct archive_write_disk *)_a;
ret = _archive_write_disk_close(&a->archive);
archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
if (a->entry)
archive_entry_free(a->entry);
archive_string_free(&a->_name_data);
archive_string_free(&a->archive.error_string);
archive_string_free(&a->path_safe);
a->archive.magic = 0;
__archive_clean(&a->archive);
free(a->decmpfs_header_p);
free(a->resource_fork);
free(a->compressed_buffer);
free(a->uncompressed_buffer);
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
&& defined(HAVE_ZLIB_H)
if (a->stream_valid) {
switch (deflateEnd(&a->stream)) {
case Z_OK:
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to clean up compressor");
ret = ARCHIVE_FATAL;
break;
}
}
#endif
free(a);
return (ret);
}
/*
* Simple O(n log n) merge sort to order the fixup list. In
* particular, we want to restore dir timestamps depth-first.
*/
static struct fixup_entry *
sort_dir_list(struct fixup_entry *p)
{
struct fixup_entry *a, *b, *t;
if (p == NULL)
return (NULL);
/* A one-item list is already sorted. */
if (p->next == NULL)
return (p);
/* Step 1: split the list. */
t = p;
a = p->next->next;
while (a != NULL) {
/* Step a twice, t once. */
a = a->next;
if (a != NULL)
a = a->next;
t = t->next;
}
/* Now, t is at the mid-point, so break the list here. */
b = t->next;
t->next = NULL;
a = p;
/* Step 2: Recursively sort the two sub-lists. */
a = sort_dir_list(a);
b = sort_dir_list(b);
/* Step 3: Merge the returned lists. */
/* Pick the first element for the merged list. */
if (strcmp(a->name, b->name) > 0) {
t = p = a;
a = a->next;
} else {
t = p = b;
b = b->next;
}
/* Always put the later element on the list first. */
while (a != NULL && b != NULL) {
if (strcmp(a->name, b->name) > 0) {
t->next = a;
a = a->next;
} else {
t->next = b;
b = b->next;
}
t = t->next;
}
/* Only one list is non-empty, so just splice it on. */
if (a != NULL)
t->next = a;
if (b != NULL)
t->next = b;
return (p);
}
/*
* Returns a new, initialized fixup entry.
*
* TODO: Reduce the memory requirements for this list by using a tree
* structure rather than a simple list of names.
*/
static struct fixup_entry *
new_fixup(struct archive_write_disk *a, const char *pathname)
{
struct fixup_entry *fe;
fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
if (fe == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for a fixup");
return (NULL);
}
fe->next = a->fixup_list;
a->fixup_list = fe;
fe->fixup = 0;
fe->name = strdup(pathname);
return (fe);
}
/*
* Returns a fixup structure for the current entry.
*/
static struct fixup_entry *
current_fixup(struct archive_write_disk *a, const char *pathname)
{
if (a->current_fixup == NULL)
a->current_fixup = new_fixup(a, pathname);
return (a->current_fixup);
}
/* TODO: Make this work. */
/*
* TODO: The deep-directory support bypasses this; disable deep directory
* support if we're doing symlink checks.
*/
/*
* TODO: Someday, integrate this with the deep dir support; they both
* scan the path and both can be optimized by comparing against other
* recent paths.
*/
/* TODO: Extend this to support symlinks on Windows Vista and later. */
static int
check_symlinks(struct archive_write_disk *a)
{
#if !defined(HAVE_LSTAT)
/* Platform doesn't have lstat, so we can't look for symlinks. */
(void)a; /* UNUSED */
return (ARCHIVE_OK);
#else
char *pn;
char c;
int r;
struct stat st;
/*
* Guard against symlink tricks. Reject any archive entry whose
* destination would be altered by a symlink.
*/
/* Whatever we checked last time doesn't need to be re-checked. */
pn = a->name;
if (archive_strlen(&(a->path_safe)) > 0) {
char *p = a->path_safe.s;
while ((*pn != '\0') && (*p == *pn))
++p, ++pn;
}
c = pn[0];
/* Keep going until we've checked the entire name. */
while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
/* Skip the next path element. */
while (*pn != '\0' && *pn != '/')
++pn;
c = pn[0];
pn[0] = '\0';
/* Check that we haven't hit a symlink. */
r = lstat(a->name, &st);
if (r != 0) {
/* We've hit a dir that doesn't exist; stop now. */
if (errno == ENOENT)
break;
} else if (S_ISLNK(st.st_mode)) {
if (c == '\0') {
/*
* Last element is symlink; remove it
* so we can overwrite it with the
* item being extracted.
*/
if (unlink(a->name)) {
archive_set_error(&a->archive, errno,
"Could not remove symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
a->pst = NULL;
/*
* Even if we did remove it, a warning
* is in order. The warning is silly,
* though, if we're just replacing one
* symlink with another symlink.
*/
if (!S_ISLNK(a->mode)) {
archive_set_error(&a->archive, 0,
"Removing symlink %s",
a->name);
}
/* Symlink gone. No more problem! */
pn[0] = c;
return (0);
} else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
/* User asked us to remove problems. */
if (unlink(a->name) != 0) {
archive_set_error(&a->archive, 0,
"Cannot remove intervening symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
a->pst = NULL;
} else {
archive_set_error(&a->archive, 0,
"Cannot extract through symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
}
}
pn[0] = c;
/* We've checked and/or cleaned the whole path, so remember it. */
archive_strcpy(&a->path_safe, a->name);
return (ARCHIVE_OK);
#endif
}
#if defined(__CYGWIN__)
/*
* 1. Convert a path separator from '\' to '/' .
* We shouldn't check multibyte character directly because some
* character-set have been using the '\' character for a part of
* its multibyte character code.
* 2. Replace unusable characters in Windows with underscore('_').
* See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
*/
static void
cleanup_pathname_win(struct archive_write_disk *a)
{
wchar_t wc;
char *p;
size_t alen, l;
int mb, complete, utf8;
alen = 0;
mb = 0;
complete = 1;
utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
for (p = a->name; *p != '\0'; p++) {
++alen;
if (*p == '\\') {
/* If previous byte is smaller than 128,
* this is not second byte of multibyte characters,
* so we can replace '\' with '/'. */
if (utf8 || !mb)
*p = '/';
else
complete = 0;/* uncompleted. */
} else if (*(unsigned char *)p > 127)
mb = 1;
else
mb = 0;
/* Rewrite the path name if its next character is unusable. */
if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
*p == '<' || *p == '>' || *p == '|')
*p = '_';
}
if (complete)
return;
/*
* Convert path separator in wide-character.
*/
p = a->name;
while (*p != '\0' && alen) {
l = mbtowc(&wc, p, alen);
if (l == (size_t)-1) {
while (*p != '\0') {
if (*p == '\\')
*p = '/';
++p;
}
break;
}
if (l == 1 && wc == L'\\')
*p = '/';
p += l;
alen -= l;
}
}
#endif
/*
* Canonicalize the pathname. In particular, this strips duplicate
* '/' characters, '.' elements, and trailing '/'. It also raises an
* error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
* set) any '..' in the path.
*/
static int
cleanup_pathname(struct archive_write_disk *a)
{
char *dest, *src;
char separator = '\0';
dest = src = a->name;
if (*src == '\0') {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/')
separator = *src++;
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == a->name) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
/*
* Create the parent directory of the specified path, assuming path
* is already in mutable storage.
*/
static int
create_parent_dir(struct archive_write_disk *a, char *path)
{
char *slash;
int r;
/* Remove tail element to obtain parent name. */
slash = strrchr(path, '/');
if (slash == NULL)
return (ARCHIVE_OK);
*slash = '\0';
r = create_dir(a, path);
*slash = '/';
return (r);
}
/*
* Create the specified dir, recursing to create parents as necessary.
*
* Returns ARCHIVE_OK if the path exists when we're done here.
* Otherwise, returns ARCHIVE_FAILED.
* Assumes path is in mutable storage; path is unchanged on exit.
*/
static int
create_dir(struct archive_write_disk *a, char *path)
{
struct stat st;
struct fixup_entry *le;
char *slash, *base;
mode_t mode_final, mode;
int r;
/* Check for special names and just skip them. */
slash = strrchr(path, '/');
if (slash == NULL)
base = path;
else
base = slash + 1;
if (base[0] == '\0' ||
(base[0] == '.' && base[1] == '\0') ||
(base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
/* Don't bother trying to create null path, '.', or '..'. */
if (slash != NULL) {
*slash = '\0';
r = create_dir(a, path);
*slash = '/';
return (r);
}
return (ARCHIVE_OK);
}
/*
* Yes, this should be stat() and not lstat(). Using lstat()
* here loses the ability to extract through symlinks. Also note
* that this should not use the a->st cache.
*/
if (stat(path, &st) == 0) {
if (S_ISDIR(st.st_mode))
return (ARCHIVE_OK);
if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
archive_set_error(&a->archive, EEXIST,
"Can't create directory '%s'", path);
return (ARCHIVE_FAILED);
}
if (unlink(path) != 0) {
archive_set_error(&a->archive, errno,
"Can't create directory '%s': "
"Conflicting file cannot be removed",
path);
return (ARCHIVE_FAILED);
}
} else if (errno != ENOENT && errno != ENOTDIR) {
/* Stat failed? */
archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
return (ARCHIVE_FAILED);
} else if (slash != NULL) {
*slash = '\0';
r = create_dir(a, path);
*slash = '/';
if (r != ARCHIVE_OK)
return (r);
}
/*
* Mode we want for the final restored directory. Per POSIX,
* implicitly-created dirs must be created obeying the umask.
* There's no mention whether this is different for privileged
* restores (which the rest of this code handles by pretending
* umask=0). I've chosen here to always obey the user's umask for
* implicit dirs, even if _EXTRACT_PERM was specified.
*/
mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
/* Mode we want on disk during the restore process. */
mode = mode_final;
mode |= MINIMUM_DIR_MODE;
mode &= MAXIMUM_DIR_MODE;
if (mkdir(path, mode) == 0) {
if (mode != mode_final) {
le = new_fixup(a, path);
if (le == NULL)
return (ARCHIVE_FATAL);
le->fixup |=TODO_MODE_BASE;
le->mode = mode_final;
}
return (ARCHIVE_OK);
}
/*
* Without the following check, a/b/../b/c/d fails at the
* second visit to 'b', so 'd' can't be created. Note that we
* don't add it to the fixup list here, as it's already been
* added.
*/
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
return (ARCHIVE_OK);
archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
path);
return (ARCHIVE_FAILED);
}
/*
* Note: Although we can skip setting the user id if the desired user
* id matches the current user, we cannot skip setting the group, as
* many systems set the gid based on the containing directory. So
* we have to perform a chown syscall if we want to set the SGID
* bit. (The alternative is to stat() and then possibly chown(); it's
* more efficient to skip the stat() and just always chown().) Note
* that a successful chown() here clears the TODO_SGID_CHECK bit, which
* allows set_mode to skip the stat() check for the GID.
*/
static int
set_ownership(struct archive_write_disk *a)
{
#ifndef __CYGWIN__
/* unfortunately, on win32 there is no 'root' user with uid 0,
so we just have to try the chown and see if it works */
/* If we know we can't change it, don't bother trying. */
if (a->user_uid != 0 && a->user_uid != a->uid) {
archive_set_error(&a->archive, errno,
"Can't set UID=%jd", (intmax_t)a->uid);
return (ARCHIVE_WARN);
}
#endif
#ifdef HAVE_FCHOWN
/* If we have an fd, we can avoid a race. */
if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
/* We've set owner and know uid/gid are correct. */
a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
return (ARCHIVE_OK);
}
#endif
/* We prefer lchown() but will use chown() if that's all we have. */
/* Of course, if we have neither, this will always fail. */
#ifdef HAVE_LCHOWN
if (lchown(a->name, a->uid, a->gid) == 0) {
/* We've set owner and know uid/gid are correct. */
a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
return (ARCHIVE_OK);
}
#elif HAVE_CHOWN
if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
/* We've set owner and know uid/gid are correct. */
a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
return (ARCHIVE_OK);
}
#endif
archive_set_error(&a->archive, errno,
"Can't set user=%jd/group=%jd for %s",
(intmax_t)a->uid, (intmax_t)a->gid, a->name);
return (ARCHIVE_WARN);
}
/*
* Note: Returns 0 on success, non-zero on failure.
*/
static int
set_time(int fd, int mode, const char *name,
time_t atime, long atime_nsec,
time_t mtime, long mtime_nsec)
{
/* Select the best implementation for this platform. */
#if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
/*
* utimensat() and futimens() are defined in
* POSIX.1-2008. They support ns resolution and setting times
* on fds and symlinks.
*/
struct timespec ts[2];
(void)mode; /* UNUSED */
ts[0].tv_sec = atime;
ts[0].tv_nsec = atime_nsec;
ts[1].tv_sec = mtime;
ts[1].tv_nsec = mtime_nsec;
if (fd >= 0)
return futimens(fd, ts);
return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
#elif HAVE_UTIMES
/*
* The utimes()-family functions support µs-resolution and
* setting times fds and symlinks. utimes() is documented as
* LEGACY by POSIX, futimes() and lutimes() are not described
* in POSIX.
*/
struct timeval times[2];
times[0].tv_sec = atime;
times[0].tv_usec = atime_nsec / 1000;
times[1].tv_sec = mtime;
times[1].tv_usec = mtime_nsec / 1000;
#ifdef HAVE_FUTIMES
if (fd >= 0)
return (futimes(fd, times));
#else
(void)fd; /* UNUSED */
#endif
#ifdef HAVE_LUTIMES
(void)mode; /* UNUSED */
return (lutimes(name, times));
#else
if (S_ISLNK(mode))
return (0);
return (utimes(name, times));
#endif
#elif defined(HAVE_UTIME)
/*
* utime() is POSIX-standard but only supports 1s resolution and
* does not support fds or symlinks.
*/
struct utimbuf times;
(void)fd; /* UNUSED */
(void)name; /* UNUSED */
(void)atime_nsec; /* UNUSED */
(void)mtime_nsec; /* UNUSED */
times.actime = atime;
times.modtime = mtime;
if (S_ISLNK(mode))
return (ARCHIVE_OK);
return (utime(name, ×));
#else
/*
* We don't know how to set the time on this platform.
*/
(void)fd; /* UNUSED */
(void)mode; /* UNUSED */
(void)name; /* UNUSED */
(void)atime_nsec; /* UNUSED */
(void)mtime_nsec; /* UNUSED */
return (ARCHIVE_WARN);
#endif
}
#ifdef F_SETTIMES
static int
set_time_tru64(int fd, int mode, const char *name,
time_t atime, long atime_nsec,
time_t mtime, long mtime_nsec,
time_t ctime, long ctime_nsec)
{
struct attr_timbuf tstamp;
tstamp.atime.tv_sec = atime;
tstamp.mtime.tv_sec = mtime;
tstamp.ctime.tv_sec = ctime;
#if defined (__hpux) && defined (__ia64)
tstamp.atime.tv_nsec = atime_nsec;
tstamp.mtime.tv_nsec = mtime_nsec;
tstamp.ctime.tv_nsec = ctime_nsec;
#else
tstamp.atime.tv_usec = atime_nsec / 1000;
tstamp.mtime.tv_usec = mtime_nsec / 1000;
tstamp.ctime.tv_usec = ctime_nsec / 1000;
#endif
return (fcntl(fd,F_SETTIMES,&tstamp));
}
#endif /* F_SETTIMES */
static int
set_times(struct archive_write_disk *a,
int fd, int mode, const char *name,
time_t atime, long atime_nanos,
time_t birthtime, long birthtime_nanos,
time_t mtime, long mtime_nanos,
time_t cctime, long ctime_nanos)
{
/* Note: set_time doesn't use libarchive return conventions!
* It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */
int r1 = 0, r2 = 0;
#ifdef F_SETTIMES
/*
* on Tru64 try own fcntl first which can restore even the
* ctime, fall back to default code path below if it fails
* or if we are not running as root
*/
if (a->user_uid == 0 &&
set_time_tru64(fd, mode, name,
atime, atime_nanos, mtime,
mtime_nanos, cctime, ctime_nanos) == 0) {
return (ARCHIVE_OK);
}
#else /* Tru64 */
(void)cctime; /* UNUSED */
(void)ctime_nanos; /* UNUSED */
#endif /* Tru64 */
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
/*
* If you have struct stat.st_birthtime, we assume BSD
* birthtime semantics, in which {f,l,}utimes() updates
* birthtime to earliest mtime. So we set the time twice,
* first using the birthtime, then using the mtime. If
* birthtime == mtime, this isn't necessary, so we skip it.
* If birthtime > mtime, then this won't work, so we skip it.
*/
if (birthtime < mtime
|| (birthtime == mtime && birthtime_nanos < mtime_nanos))
r1 = set_time(fd, mode, name,
atime, atime_nanos,
birthtime, birthtime_nanos);
#else
(void)birthtime; /* UNUSED */
(void)birthtime_nanos; /* UNUSED */
#endif
r2 = set_time(fd, mode, name,
atime, atime_nanos,
mtime, mtime_nanos);
if (r1 != 0 || r2 != 0) {
archive_set_error(&a->archive, errno,
"Can't restore time");
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
static int
set_times_from_entry(struct archive_write_disk *a)
{
time_t atime, birthtime, mtime, cctime;
long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
/* Suitable defaults. */
atime = birthtime = mtime = cctime = a->start_time;
atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
/* If no time was provided, we're done. */
if (!archive_entry_atime_is_set(a->entry)
#if HAVE_STRUCT_STAT_ST_BIRTHTIME
&& !archive_entry_birthtime_is_set(a->entry)
#endif
&& !archive_entry_mtime_is_set(a->entry))
return (ARCHIVE_OK);
if (archive_entry_atime_is_set(a->entry)) {
atime = archive_entry_atime(a->entry);
atime_nsec = archive_entry_atime_nsec(a->entry);
}
if (archive_entry_birthtime_is_set(a->entry)) {
birthtime = archive_entry_birthtime(a->entry);
birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
}
if (archive_entry_mtime_is_set(a->entry)) {
mtime = archive_entry_mtime(a->entry);
mtime_nsec = archive_entry_mtime_nsec(a->entry);
}
if (archive_entry_ctime_is_set(a->entry)) {
cctime = archive_entry_ctime(a->entry);
ctime_nsec = archive_entry_ctime_nsec(a->entry);
}
return set_times(a, a->fd, a->mode, a->name,
atime, atime_nsec,
birthtime, birthtime_nsec,
mtime, mtime_nsec,
cctime, ctime_nsec);
}
static int
set_mode(struct archive_write_disk *a, int mode)
{
int r = ARCHIVE_OK;
mode &= 07777; /* Strip off file type bits. */
if (a->todo & TODO_SGID_CHECK) {
/*
* If we don't know the GID is right, we must stat()
* to verify it. We can't just check the GID of this
* process, since systems sometimes set GID from
* the enclosing dir or based on ACLs.
*/
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
if (a->pst->st_gid != a->gid) {
mode &= ~ S_ISGID;
if (a->flags & ARCHIVE_EXTRACT_OWNER) {
/*
* This is only an error if you
* requested owner restore. If you
* didn't, we'll try to restore
* sgid/suid, but won't consider it a
* problem if we can't.
*/
archive_set_error(&a->archive, -1,
"Can't restore SGID bit");
r = ARCHIVE_WARN;
}
}
/* While we're here, double-check the UID. */
if (a->pst->st_uid != a->uid
&& (a->todo & TODO_SUID)) {
mode &= ~ S_ISUID;
if (a->flags & ARCHIVE_EXTRACT_OWNER) {
archive_set_error(&a->archive, -1,
"Can't restore SUID bit");
r = ARCHIVE_WARN;
}
}
a->todo &= ~TODO_SGID_CHECK;
a->todo &= ~TODO_SUID_CHECK;
} else if (a->todo & TODO_SUID_CHECK) {
/*
* If we don't know the UID is right, we can just check
* the user, since all systems set the file UID from
* the process UID.
*/
if (a->user_uid != a->uid) {
mode &= ~ S_ISUID;
if (a->flags & ARCHIVE_EXTRACT_OWNER) {
archive_set_error(&a->archive, -1,
"Can't make file SUID");
r = ARCHIVE_WARN;
}
}
a->todo &= ~TODO_SUID_CHECK;
}
if (S_ISLNK(a->mode)) {
#ifdef HAVE_LCHMOD
/*
* If this is a symlink, use lchmod(). If the
* platform doesn't support lchmod(), just skip it. A
* platform that doesn't provide a way to set
* permissions on symlinks probably ignores
* permissions on symlinks, so a failure here has no
* impact.
*/
if (lchmod(a->name, mode) != 0) {
switch (errno) {
case ENOTSUP:
case ENOSYS:
#if ENOTSUP != EOPNOTSUPP
case EOPNOTSUPP:
#endif
/*
* if lchmod is defined but the platform
* doesn't support it, silently ignore
* error
*/
break;
default:
archive_set_error(&a->archive, errno,
"Can't set permissions to 0%o", (int)mode);
r = ARCHIVE_WARN;
}
}
#endif
} else if (!S_ISDIR(a->mode)) {
/*
* If it's not a symlink and not a dir, then use
* fchmod() or chmod(), depending on whether we have
* an fd. Dirs get their perms set during the
* post-extract fixup, which is handled elsewhere.
*/
#ifdef HAVE_FCHMOD
if (a->fd >= 0) {
if (fchmod(a->fd, mode) != 0) {
archive_set_error(&a->archive, errno,
"Can't set permissions to 0%o", (int)mode);
r = ARCHIVE_WARN;
}
} else
#endif
/* If this platform lacks fchmod(), then
* we'll just use chmod(). */
if (chmod(a->name, mode) != 0) {
archive_set_error(&a->archive, errno,
"Can't set permissions to 0%o", (int)mode);
r = ARCHIVE_WARN;
}
}
return (r);
}
static int
set_fflags(struct archive_write_disk *a)
{
struct fixup_entry *le;
unsigned long set, clear;
int r;
int critical_flags;
mode_t mode = archive_entry_mode(a->entry);
/*
* Make 'critical_flags' hold all file flags that can't be
* immediately restored. For example, on BSD systems,
* SF_IMMUTABLE prevents hardlinks from being created, so
* should not be set until after any hardlinks are created. To
* preserve some semblance of portability, this uses #ifdef
* extensively. Ugly, but it works.
*
* Yes, Virginia, this does create a security race. It's mitigated
* somewhat by the practice of creating dirs 0700 until the extract
* is done, but it would be nice if we could do more than that.
* People restoring critical file systems should be wary of
* other programs that might try to muck with files as they're
* being restored.
*/
/* Hopefully, the compiler will optimize this mess into a constant. */
critical_flags = 0;
#ifdef SF_IMMUTABLE
critical_flags |= SF_IMMUTABLE;
#endif
#ifdef UF_IMMUTABLE
critical_flags |= UF_IMMUTABLE;
#endif
#ifdef SF_APPEND
critical_flags |= SF_APPEND;
#endif
#ifdef UF_APPEND
critical_flags |= UF_APPEND;
#endif
#ifdef EXT2_APPEND_FL
critical_flags |= EXT2_APPEND_FL;
#endif
#ifdef EXT2_IMMUTABLE_FL
critical_flags |= EXT2_IMMUTABLE_FL;
#endif
if (a->todo & TODO_FFLAGS) {
archive_entry_fflags(a->entry, &set, &clear);
/*
* The first test encourages the compiler to eliminate
* all of this if it's not necessary.
*/
if ((critical_flags != 0) && (set & critical_flags)) {
le = current_fixup(a, a->name);
if (le == NULL)
return (ARCHIVE_FATAL);
le->fixup |= TODO_FFLAGS;
le->fflags_set = set;
/* Store the mode if it's not already there. */
if ((le->fixup & TODO_MODE) == 0)
le->mode = mode;
} else {
r = set_fflags_platform(a, a->fd,
a->name, mode, set, clear);
if (r != ARCHIVE_OK)
return (r);
}
}
return (ARCHIVE_OK);
}
#if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
/*
* BSD reads flags using stat() and sets them with one of {f,l,}chflags()
*/
static int
set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
mode_t mode, unsigned long set, unsigned long clear)
{
int r;
(void)mode; /* UNUSED */
if (set == 0 && clear == 0)
return (ARCHIVE_OK);
/*
* XXX Is the stat here really necessary? Or can I just use
* the 'set' flags directly? In particular, I'm not sure
* about the correct approach if we're overwriting an existing
* file that already has flags on it. XXX
*/
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
a->st.st_flags &= ~clear;
a->st.st_flags |= set;
#ifdef HAVE_FCHFLAGS
/* If platform has fchflags() and we were given an fd, use it. */
if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
return (ARCHIVE_OK);
#endif
/*
* If we can't use the fd to set the flags, we'll use the
* pathname to set flags. We prefer lchflags() but will use
* chflags() if we must.
*/
#ifdef HAVE_LCHFLAGS
if (lchflags(name, a->st.st_flags) == 0)
return (ARCHIVE_OK);
#elif defined(HAVE_CHFLAGS)
if (S_ISLNK(a->st.st_mode)) {
archive_set_error(&a->archive, errno,
"Can't set file flags on symlink.");
return (ARCHIVE_WARN);
}
if (chflags(name, a->st.st_flags) == 0)
return (ARCHIVE_OK);
#endif
archive_set_error(&a->archive, errno,
"Failed to set file flags");
return (ARCHIVE_WARN);
}
#elif defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)
/*
* Linux uses ioctl() to read and write file flags.
*/
static int
set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
mode_t mode, unsigned long set, unsigned long clear)
{
int ret;
int myfd = fd;
int newflags, oldflags;
int sf_mask = 0;
if (set == 0 && clear == 0)
return (ARCHIVE_OK);
/* Only regular files and dirs can have flags. */
if (!S_ISREG(mode) && !S_ISDIR(mode))
return (ARCHIVE_OK);
/* If we weren't given an fd, open it ourselves. */
if (myfd < 0) {
myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(myfd);
}
if (myfd < 0)
return (ARCHIVE_OK);
/*
* Linux has no define for the flags that are only settable by
* the root user. This code may seem a little complex, but
* there seem to be some Linux systems that lack these
* defines. (?) The code below degrades reasonably gracefully
* if sf_mask is incomplete.
*/
#ifdef EXT2_IMMUTABLE_FL
sf_mask |= EXT2_IMMUTABLE_FL;
#endif
#ifdef EXT2_APPEND_FL
sf_mask |= EXT2_APPEND_FL;
#endif
/*
* XXX As above, this would be way simpler if we didn't have
* to read the current flags from disk. XXX
*/
ret = ARCHIVE_OK;
/* Read the current file flags. */
if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) < 0)
goto fail;
/* Try setting the flags as given. */
newflags = (oldflags & ~clear) | set;
if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
goto cleanup;
if (errno != EPERM)
goto fail;
/* If we couldn't set all the flags, try again with a subset. */
newflags &= ~sf_mask;
oldflags &= sf_mask;
newflags |= oldflags;
if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
goto cleanup;
/* We couldn't set the flags, so report the failure. */
fail:
archive_set_error(&a->archive, errno,
"Failed to set file flags");
ret = ARCHIVE_WARN;
cleanup:
if (fd < 0)
close(myfd);
return (ret);
}
#else
/*
* Of course, some systems have neither BSD chflags() nor Linux' flags
* support through ioctl().
*/
static int
set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
mode_t mode, unsigned long set, unsigned long clear)
{
(void)a; /* UNUSED */
(void)fd; /* UNUSED */
(void)name; /* UNUSED */
(void)mode; /* UNUSED */
(void)set; /* UNUSED */
(void)clear; /* UNUSED */
return (ARCHIVE_OK);
}
#endif /* __linux */
#ifndef HAVE_COPYFILE_H
/* Default is to simply drop Mac extended metadata. */
static int
set_mac_metadata(struct archive_write_disk *a, const char *pathname,
const void *metadata, size_t metadata_size)
{
(void)a; /* UNUSED */
(void)pathname; /* UNUSED */
(void)metadata; /* UNUSED */
(void)metadata_size; /* UNUSED */
return (ARCHIVE_OK);
}
static int
fixup_appledouble(struct archive_write_disk *a, const char *pathname)
{
(void)a; /* UNUSED */
(void)pathname; /* UNUSED */
return (ARCHIVE_OK);
}
#else
/*
* On Mac OS, we use copyfile() to unpack the metadata and
* apply it to the target file.
*/
#if defined(HAVE_SYS_XATTR_H)
static int
copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
{
ssize_t xattr_size;
char *xattr_names = NULL, *xattr_val = NULL;
int ret = ARCHIVE_OK, xattr_i;
xattr_size = flistxattr(tmpfd, NULL, 0, 0);
if (xattr_size == -1) {
archive_set_error(&a->archive, errno,
"Failed to read metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
xattr_names = malloc(xattr_size);
if (xattr_names == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for metadata(xattr)");
ret = ARCHIVE_FATAL;
goto exit_xattr;
}
xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
if (xattr_size == -1) {
archive_set_error(&a->archive, errno,
"Failed to read metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
for (xattr_i = 0; xattr_i < xattr_size;
xattr_i += strlen(xattr_names + xattr_i) + 1) {
char *xattr_val_saved;
ssize_t s;
int f;
s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
if (s == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
xattr_val_saved = xattr_val;
xattr_val = realloc(xattr_val, s);
if (xattr_val == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
free(xattr_val_saved);
goto exit_xattr;
}
s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
if (s == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
if (f == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
}
exit_xattr:
free(xattr_names);
free(xattr_val);
return (ret);
}
#endif
static int
copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
{
acl_t acl, dfacl = NULL;
int acl_r, ret = ARCHIVE_OK;
acl = acl_get_fd(tmpfd);
if (acl == NULL) {
if (errno == ENOENT)
/* There are not any ACLs. */
return (ret);
archive_set_error(&a->archive, errno,
"Failed to get metadata(acl)");
ret = ARCHIVE_WARN;
goto exit_acl;
}
dfacl = acl_dup(acl);
acl_r = acl_set_fd(dffd, dfacl);
if (acl_r == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(acl)");
ret = ARCHIVE_WARN;
goto exit_acl;
}
exit_acl:
if (acl)
acl_free(acl);
if (dfacl)
acl_free(dfacl);
return (ret);
}
static int
create_tempdatafork(struct archive_write_disk *a, const char *pathname)
{
struct archive_string tmpdatafork;
int tmpfd;
archive_string_init(&tmpdatafork);
archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
tmpfd = mkstemp(tmpdatafork.s);
if (tmpfd < 0) {
archive_set_error(&a->archive, errno,
"Failed to mkstemp");
archive_string_free(&tmpdatafork);
return (-1);
}
if (copyfile(pathname, tmpdatafork.s, 0,
COPYFILE_UNPACK | COPYFILE_NOFOLLOW
| COPYFILE_ACL | COPYFILE_XATTR) < 0) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
close(tmpfd);
tmpfd = -1;
}
unlink(tmpdatafork.s);
archive_string_free(&tmpdatafork);
return (tmpfd);
}
static int
copy_metadata(struct archive_write_disk *a, const char *metadata,
const char *datafork, int datafork_compressed)
{
int ret = ARCHIVE_OK;
if (datafork_compressed) {
int dffd, tmpfd;
tmpfd = create_tempdatafork(a, metadata);
if (tmpfd == -1)
return (ARCHIVE_WARN);
/*
* Do not open the data fork compressed by HFS+ compression
* with at least a writing mode(O_RDWR or O_WRONLY). it
* makes the data fork uncompressed.
*/
dffd = open(datafork, 0);
if (dffd == -1) {
archive_set_error(&a->archive, errno,
"Failed to open the data fork for metadata");
close(tmpfd);
return (ARCHIVE_WARN);
}
#if defined(HAVE_SYS_XATTR_H)
ret = copy_xattrs(a, tmpfd, dffd);
if (ret == ARCHIVE_OK)
#endif
ret = copy_acls(a, tmpfd, dffd);
close(tmpfd);
close(dffd);
} else {
if (copyfile(metadata, datafork, 0,
COPYFILE_UNPACK | COPYFILE_NOFOLLOW
| COPYFILE_ACL | COPYFILE_XATTR) < 0) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
ret = ARCHIVE_WARN;
}
}
return (ret);
}
static int
set_mac_metadata(struct archive_write_disk *a, const char *pathname,
const void *metadata, size_t metadata_size)
{
struct archive_string tmp;
ssize_t written;
int fd;
int ret = ARCHIVE_OK;
/* This would be simpler if copyfile() could just accept the
* metadata as a block of memory; then we could sidestep this
* silly dance of writing the data to disk just so that
* copyfile() can read it back in again. */
archive_string_init(&tmp);
archive_strcpy(&tmp, pathname);
archive_strcat(&tmp, ".XXXXXX");
fd = mkstemp(tmp.s);
if (fd < 0) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
archive_string_free(&tmp);
return (ARCHIVE_WARN);
}
written = write(fd, metadata, metadata_size);
close(fd);
if ((size_t)written != metadata_size) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
ret = ARCHIVE_WARN;
} else {
int compressed;
#if defined(UF_COMPRESSED)
if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
(ret = lazy_stat(a)) == ARCHIVE_OK)
compressed = a->st.st_flags & UF_COMPRESSED;
else
#endif
compressed = 0;
ret = copy_metadata(a, tmp.s, pathname, compressed);
}
unlink(tmp.s);
archive_string_free(&tmp);
return (ret);
}
static int
fixup_appledouble(struct archive_write_disk *a, const char *pathname)
{
char buff[8];
struct stat st;
const char *p;
struct archive_string datafork;
int fd = -1, ret = ARCHIVE_OK;
archive_string_init(&datafork);
/* Check if the current file name is a type of the resource
* fork file. */
p = strrchr(pathname, '/');
if (p == NULL)
p = pathname;
else
p++;
if (p[0] != '.' || p[1] != '_')
goto skip_appledouble;
/*
* Check if the data fork file exists.
*
* TODO: Check if this write disk object has handled it.
*/
archive_strncpy(&datafork, pathname, p - pathname);
archive_strcat(&datafork, p + 2);
if (lstat(datafork.s, &st) == -1 ||
(st.st_mode & AE_IFMT) != AE_IFREG)
goto skip_appledouble;
/*
* Check if the file is in the AppleDouble form.
*/
fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(fd);
if (fd == -1) {
archive_set_error(&a->archive, errno,
"Failed to open a restoring file");
ret = ARCHIVE_WARN;
goto skip_appledouble;
}
if (read(fd, buff, 8) == -1) {
archive_set_error(&a->archive, errno,
"Failed to read a restoring file");
close(fd);
ret = ARCHIVE_WARN;
goto skip_appledouble;
}
close(fd);
/* Check AppleDouble Magic Code. */
if (archive_be32dec(buff) != 0x00051607)
goto skip_appledouble;
/* Check AppleDouble Version. */
if (archive_be32dec(buff+4) != 0x00020000)
goto skip_appledouble;
ret = copy_metadata(a, pathname, datafork.s,
#if defined(UF_COMPRESSED)
st.st_flags & UF_COMPRESSED);
#else
0);
#endif
if (ret == ARCHIVE_OK) {
unlink(pathname);
ret = ARCHIVE_EOF;
}
skip_appledouble:
archive_string_free(&datafork);
return (ret);
}
#endif
#if HAVE_LSETXATTR || HAVE_LSETEA
/*
* Restore extended attributes - Linux and AIX implementations:
* AIX' ea interface is syntaxwise identical to the Linux xattr interface.
*/
static int
set_xattrs(struct archive_write_disk *a)
{
struct archive_entry *entry = a->entry;
static int warning_done = 0;
int ret = ARCHIVE_OK;
int i = archive_entry_xattr_reset(entry);
while (i--) {
const char *name;
const void *value;
size_t size;
archive_entry_xattr_next(entry, &name, &value, &size);
if (name != NULL &&
strncmp(name, "xfsroot.", 8) != 0 &&
strncmp(name, "system.", 7) != 0) {
int e;
#if HAVE_FSETXATTR
if (a->fd >= 0)
e = fsetxattr(a->fd, name, value, size, 0);
else
#elif HAVE_FSETEA
if (a->fd >= 0)
e = fsetea(a->fd, name, value, size, 0);
else
#endif
{
#if HAVE_LSETXATTR
e = lsetxattr(archive_entry_pathname(entry),
name, value, size, 0);
#elif HAVE_LSETEA
e = lsetea(archive_entry_pathname(entry),
name, value, size, 0);
#endif
}
if (e == -1) {
if (errno == ENOTSUP || errno == ENOSYS) {
if (!warning_done) {
warning_done = 1;
archive_set_error(&a->archive, errno,
"Cannot restore extended "
"attributes on this file "
"system");
}
} else
archive_set_error(&a->archive, errno,
"Failed to set extended attribute");
ret = ARCHIVE_WARN;
}
} else {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid extended attribute encountered");
ret = ARCHIVE_WARN;
}
}
return (ret);
}
#elif HAVE_EXTATTR_SET_FILE && HAVE_DECL_EXTATTR_NAMESPACE_USER
/*
* Restore extended attributes - FreeBSD implementation
*/
static int
set_xattrs(struct archive_write_disk *a)
{
struct archive_entry *entry = a->entry;
static int warning_done = 0;
int ret = ARCHIVE_OK;
int i = archive_entry_xattr_reset(entry);
while (i--) {
const char *name;
const void *value;
size_t size;
archive_entry_xattr_next(entry, &name, &value, &size);
if (name != NULL) {
int e;
int namespace;
if (strncmp(name, "user.", 5) == 0) {
/* "user." attributes go to user namespace */
name += 5;
namespace = EXTATTR_NAMESPACE_USER;
} else {
/* Warn about other extended attributes. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Can't restore extended attribute ``%s''",
name);
ret = ARCHIVE_WARN;
continue;
}
errno = 0;
#if HAVE_EXTATTR_SET_FD
if (a->fd >= 0)
e = extattr_set_fd(a->fd, namespace, name, value, size);
else
#endif
/* TODO: should we use extattr_set_link() instead? */
{
e = extattr_set_file(archive_entry_pathname(entry),
namespace, name, value, size);
}
if (e != (int)size) {
if (errno == ENOTSUP || errno == ENOSYS) {
if (!warning_done) {
warning_done = 1;
archive_set_error(&a->archive, errno,
"Cannot restore extended "
"attributes on this file "
"system");
}
} else {
archive_set_error(&a->archive, errno,
"Failed to set extended attribute");
}
ret = ARCHIVE_WARN;
}
}
}
return (ret);
}
#else
/*
* Restore extended attributes - stub implementation for unsupported systems
*/
static int
set_xattrs(struct archive_write_disk *a)
{
static int warning_done = 0;
/* If there aren't any extended attributes, then it's okay not
* to extract them, otherwise, issue a single warning. */
if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
warning_done = 1;
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Cannot restore extended attributes on this system");
return (ARCHIVE_WARN);
}
/* Warning was already emitted; suppress further warnings. */
return (ARCHIVE_OK);
}
#endif
/*
* Test if file on disk is older than entry.
*/
static int
older(struct stat *st, struct archive_entry *entry)
{
/* First, test the seconds and return if we have a definite answer. */
/* Definitely older. */
if (st->st_mtime < archive_entry_mtime(entry))
return (1);
/* Definitely younger. */
if (st->st_mtime > archive_entry_mtime(entry))
return (0);
/* If this platform supports fractional seconds, try those. */
#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
/* Definitely older. */
if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
/* Definitely older. */
if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_MTIME_N
/* older. */
if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_UMTIME
/* older. */
if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_MTIME_USEC
/* older. */
if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
return (1);
#else
/* This system doesn't have high-res timestamps. */
#endif
/* Same age or newer, so not older. */
return (0);
}
#endif /* !_WIN32 || __CYGWIN__ */
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1520_4 |
crossvul-cpp_data_bad_3514_0 | /*
* $Id: device-linux.c,v 1.28 2011/02/06 03:41:38 reubenhwk Exp $
*
* Authors:
* Lars Fenneberg <lf@elemental.net>
*
* This software is Copyright 1996,1997 by the above mentioned author(s),
* All Rights Reserved.
*
* The license which is distributed with this software in the file COPYRIGHT
* applies to this software. If your distribution is missing this file, you
* may request it from <pekkas@netcore.fi>.
*
*/
#include "config.h"
#include "includes.h"
#include "radvd.h"
#include "defaults.h"
#include "pathnames.h" /* for PATH_PROC_NET_IF_INET6 */
#ifndef IPV6_ADDR_LINKLOCAL
#define IPV6_ADDR_LINKLOCAL 0x0020U
#endif
/*
* this function gets the hardware type and address of an interface,
* determines the link layer token length and checks it against
* the defined prefixes
*/
int
setup_deviceinfo(struct Interface *iface)
{
struct ifreq ifr;
struct AdvPrefix *prefix;
char zero[sizeof(iface->if_addr)];
strncpy(ifr.ifr_name, iface->Name, IFNAMSIZ-1);
ifr.ifr_name[IFNAMSIZ-1] = '\0';
if (ioctl(sock, SIOCGIFMTU, &ifr) < 0) {
flog(LOG_ERR, "ioctl(SIOCGIFMTU) failed for %s: %s",
iface->Name, strerror(errno));
return (-1);
}
dlog(LOG_DEBUG, 3, "mtu for %s is %d", iface->Name, ifr.ifr_mtu);
iface->if_maxmtu = ifr.ifr_mtu;
if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
{
flog(LOG_ERR, "ioctl(SIOCGIFHWADDR) failed for %s: %s",
iface->Name, strerror(errno));
return (-1);
}
dlog(LOG_DEBUG, 3, "hardware type for %s is %d", iface->Name,
ifr.ifr_hwaddr.sa_family);
switch(ifr.ifr_hwaddr.sa_family)
{
case ARPHRD_ETHER:
iface->if_hwaddr_len = 48;
iface->if_prefix_len = 64;
break;
#ifdef ARPHRD_FDDI
case ARPHRD_FDDI:
iface->if_hwaddr_len = 48;
iface->if_prefix_len = 64;
break;
#endif /* ARPHDR_FDDI */
#ifdef ARPHRD_ARCNET
case ARPHRD_ARCNET:
iface->if_hwaddr_len = 8;
iface->if_prefix_len = -1;
iface->if_maxmtu = -1;
break;
#endif /* ARPHDR_ARCNET */
default:
iface->if_hwaddr_len = -1;
iface->if_prefix_len = -1;
iface->if_maxmtu = -1;
break;
}
dlog(LOG_DEBUG, 3, "link layer token length for %s is %d", iface->Name,
iface->if_hwaddr_len);
dlog(LOG_DEBUG, 3, "prefix length for %s is %d", iface->Name,
iface->if_prefix_len);
if (iface->if_hwaddr_len != -1) {
unsigned int if_hwaddr_len_bytes = (iface->if_hwaddr_len + 7) >> 3;
if (if_hwaddr_len_bytes > sizeof(iface->if_hwaddr)) {
flog(LOG_ERR, "address length %d too big for %s", if_hwaddr_len_bytes, iface->Name);
return(-2);
}
memcpy(iface->if_hwaddr, ifr.ifr_hwaddr.sa_data, if_hwaddr_len_bytes);
memset(zero, 0, sizeof(zero));
if (!memcmp(iface->if_hwaddr, zero, if_hwaddr_len_bytes))
flog(LOG_WARNING, "WARNING, MAC address on %s is all zero!",
iface->Name);
}
prefix = iface->AdvPrefixList;
while (prefix)
{
if ((iface->if_prefix_len != -1) &&
(iface->if_prefix_len != prefix->PrefixLen))
{
flog(LOG_WARNING, "prefix length should be %d for %s",
iface->if_prefix_len, iface->Name);
}
prefix = prefix->next;
}
return (0);
}
/*
* this function extracts the link local address and interface index
* from PATH_PROC_NET_IF_INET6. Note: 'sock' unused in Linux.
*/
int setup_linklocal_addr(struct Interface *iface)
{
FILE *fp;
char str_addr[40];
unsigned int plen, scope, dad_status, if_idx;
char devname[IFNAMSIZ];
if ((fp = fopen(PATH_PROC_NET_IF_INET6, "r")) == NULL)
{
flog(LOG_ERR, "can't open %s: %s", PATH_PROC_NET_IF_INET6,
strerror(errno));
return (-1);
}
while (fscanf(fp, "%32s %x %02x %02x %02x %15s\n",
str_addr, &if_idx, &plen, &scope, &dad_status,
devname) != EOF)
{
if (scope == IPV6_ADDR_LINKLOCAL &&
strcmp(devname, iface->Name) == 0)
{
struct in6_addr addr;
unsigned int ap;
int i;
for (i=0; i<16; i++)
{
sscanf(str_addr + i * 2, "%02x", &ap);
addr.s6_addr[i] = (unsigned char)ap;
}
memcpy(&iface->if_addr, &addr, sizeof(iface->if_addr));
iface->if_index = if_idx;
fclose(fp);
return 0;
}
}
flog(LOG_ERR, "no linklocal address configured for %s", iface->Name);
fclose(fp);
return (-1);
}
int setup_allrouters_membership(struct Interface *iface)
{
struct ipv6_mreq mreq;
memset(&mreq, 0, sizeof(mreq));
mreq.ipv6mr_interface = iface->if_index;
/* ipv6-allrouters: ff02::2 */
mreq.ipv6mr_multiaddr.s6_addr32[0] = htonl(0xFF020000);
mreq.ipv6mr_multiaddr.s6_addr32[3] = htonl(0x2);
if (setsockopt(sock, SOL_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
{
/* linux-2.6.12-bk4 returns error with HUP signal but keep listening */
if (errno != EADDRINUSE)
{
flog(LOG_ERR, "can't join ipv6-allrouters on %s", iface->Name);
return (-1);
}
}
return (0);
}
int check_allrouters_membership(struct Interface *iface)
{
#define ALL_ROUTERS_MCAST "ff020000000000000000000000000002"
FILE *fp;
unsigned int if_idx, allrouters_ok=0;
char addr[32+1];
char buffer[301] = {""}, *str;
int ret=0;
if ((fp = fopen(PATH_PROC_NET_IGMP6, "r")) == NULL)
{
flog(LOG_ERR, "can't open %s: %s", PATH_PROC_NET_IGMP6,
strerror(errno));
return (-1);
}
str = fgets(buffer, 300, fp);
while (str && (ret = sscanf(str, "%u %*s %32[0-9A-Fa-f]", &if_idx, addr)) ) {
if (ret == 2) {
if (iface->if_index == if_idx) {
if (strncmp(addr, ALL_ROUTERS_MCAST, sizeof(addr)) == 0){
allrouters_ok = 1;
break;
}
}
}
str = fgets(buffer, 300, fp);
}
fclose(fp);
if (!allrouters_ok) {
flog(LOG_WARNING, "resetting ipv6-allrouters membership on %s", iface->Name);
setup_allrouters_membership(iface);
}
return(0);
}
/* note: also called from the root context */
int
set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
int
set_interface_linkmtu(const char *iface, uint32_t mtu)
{
if (privsep_enabled())
return privsep_interface_linkmtu(iface, mtu);
return set_interface_var(iface,
PROC_SYS_IP6_LINKMTU, "LinkMTU",
mtu);
}
int
set_interface_curhlim(const char *iface, uint8_t hlim)
{
if (privsep_enabled())
return privsep_interface_curhlim(iface, hlim);
return set_interface_var(iface,
PROC_SYS_IP6_CURHLIM, "CurHopLimit",
hlim);
}
int
set_interface_reachtime(const char *iface, uint32_t rtime)
{
int ret;
if (privsep_enabled())
return privsep_interface_reachtime(iface, rtime);
ret = set_interface_var(iface,
PROC_SYS_IP6_BASEREACHTIME_MS,
NULL,
rtime);
if (ret)
ret = set_interface_var(iface,
PROC_SYS_IP6_BASEREACHTIME,
"BaseReachableTimer",
rtime / 1000); /* sec */
return ret;
}
int
set_interface_retranstimer(const char *iface, uint32_t rettimer)
{
int ret;
if (privsep_enabled())
return privsep_interface_retranstimer(iface, rettimer);
ret = set_interface_var(iface,
PROC_SYS_IP6_RETRANSTIMER_MS,
NULL,
rettimer);
if (ret)
ret = set_interface_var(iface,
PROC_SYS_IP6_RETRANSTIMER,
"RetransTimer",
rettimer / 1000 * USER_HZ); /* XXX user_hz */
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_3514_0 |
crossvul-cpp_data_good_1569_0 | /*
Copyright (C) 2010 ABRT team
Copyright (C) 2010 RedHat 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "internal_libreport.h"
#include <errno.h>
#define NEW_PD_SUFFIX ".new"
static struct dump_dir *try_dd_create(const char *base_dir_name, const char *dir_name, uid_t uid)
{
char *path = concat_path_file(base_dir_name, dir_name);
struct dump_dir *dd = dd_create(path, uid, DEFAULT_DUMP_DIR_MODE);
free(path);
return dd;
}
struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name)
{
INITIALIZE_LIBREPORT();
char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER);
if (!type)
{
error_msg(_("Missing required item: '%s'"), FILENAME_ANALYZER);
return NULL;
}
if (!str_is_correct_filename(type))
{
error_msg(_("'%s' is not correct file name"), FILENAME_ANALYZER);
return NULL;
}
uid_t uid = (uid_t)-1L;
char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);
if (uid_str)
{
char *endptr;
errno = 0;
long val = strtol(uid_str, &endptr, 10);
if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val)
{
error_msg(_("uid value is not valid: '%s'"), uid_str);
return NULL;
}
uid = (uid_t)val;
}
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0)
{
perror_msg("gettimeofday()");
return NULL;
}
char *problem_id = xasprintf("%s-%s.%ld-%lu"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid());
log_info("Saving to %s/%s with uid %d", base_dir_name, problem_id, uid);
struct dump_dir *dd;
if (base_dir_name)
dd = try_dd_create(base_dir_name, problem_id, uid);
else
{
/* Try /var/run/abrt */
dd = try_dd_create(LOCALSTATEDIR"/run/abrt", problem_id, uid);
/* Try $HOME/tmp */
if (!dd)
{
char *home = getenv("HOME");
if (home && home[0])
{
home = concat_path_file(home, "tmp");
/*mkdir(home, 0777); - do we want this? */
dd = try_dd_create(home, problem_id, uid);
free(home);
}
}
//TODO: try user's home dir obtained by getpwuid(getuid())?
/* Try system temporary directory */
if (!dd)
dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid);
}
if (!dd) /* try_dd_create() already emitted the error message */
goto ret;
GHashTableIter iter;
char *name;
struct problem_item *value;
g_hash_table_iter_init(&iter, problem_data);
while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))
{
if (!str_is_correct_filename(name))
{
error_msg("Problem data field name contains disallowed chars: '%s'", name);
continue;
}
if (value->flags & CD_FLAG_BIN)
{
char *dest = concat_path_file(dd->dd_dirname, name);
log_info("copying '%s' to '%s'", value->content, dest);
off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH);
if (copied < 0)
error_msg("Can't copy %s to %s", value->content, dest);
else
log_info("copied %li bytes", (unsigned long)copied);
free(dest);
continue;
}
dd_save_text(dd, name, value->content);
}
/* need to create basic files AFTER we save the pd to dump_dir
* otherwise we can't skip already created files like in case when
* reporting from anaconda where we can't read /etc/{system,redhat}-release
* and os_release is taken from anaconda
*/
dd_create_basic_files(dd, uid, NULL);
problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0';
char* new_path = concat_path_file(base_dir_name, problem_id);
log_info("Renaming from '%s' to '%s'", dd->dd_dirname, new_path);
dd_rename(dd, new_path);
ret:
free(problem_id);
return dd;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1569_0 |
crossvul-cpp_data_good_440_0 | #include "first.h"
#include "base.h"
#include "log.h"
#include "buffer.h"
#include "plugin.h"
#include <stdlib.h>
#include <string.h>
/* plugin config for all request/connections */
typedef struct {
array *alias;
} plugin_config;
typedef struct {
PLUGIN_DATA;
plugin_config **config_storage;
plugin_config conf;
} plugin_data;
/* init the plugin data */
INIT_FUNC(mod_alias_init) {
plugin_data *p;
p = calloc(1, sizeof(*p));
return p;
}
/* detroy the plugin data */
FREE_FUNC(mod_alias_free) {
plugin_data *p = p_d;
if (!p) return HANDLER_GO_ON;
if (p->config_storage) {
size_t i;
for (i = 0; i < srv->config_context->used; i++) {
plugin_config *s = p->config_storage[i];
if (NULL == s) continue;
array_free(s->alias);
free(s);
}
free(p->config_storage);
}
free(p);
return HANDLER_GO_ON;
}
/* handle plugin config and check values */
SETDEFAULTS_FUNC(mod_alias_set_defaults) {
plugin_data *p = p_d;
size_t i = 0;
config_values_t cv[] = {
{ "alias.url", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
{ NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
};
if (!p) return HANDLER_ERROR;
p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
for (i = 0; i < srv->config_context->used; i++) {
data_config const* config = (data_config const*)srv->config_context->data[i];
plugin_config *s;
s = calloc(1, sizeof(plugin_config));
s->alias = array_init();
cv[0].destination = s->alias;
p->config_storage[i] = s;
if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
return HANDLER_ERROR;
}
if (!array_is_kvstring(s->alias)) {
log_error_write(srv, __FILE__, __LINE__, "s",
"unexpected value for alias.url; expected list of \"urlpath\" => \"filepath\"");
return HANDLER_ERROR;
}
if (s->alias->used >= 2) {
const array *a = s->alias;
size_t j, k;
for (j = 0; j < a->used; j ++) {
const buffer *prefix = a->data[a->sorted[j]]->key;
for (k = j + 1; k < a->used; k ++) {
const buffer *key = a->data[a->sorted[k]]->key;
if (buffer_string_length(key) < buffer_string_length(prefix)) {
break;
}
if (memcmp(key->ptr, prefix->ptr, buffer_string_length(prefix)) != 0) {
break;
}
/* ok, they have same prefix. check position */
if (a->sorted[j] < a->sorted[k]) {
log_error_write(srv, __FILE__, __LINE__, "SBSBS",
"url.alias: `", key, "' will never match as `", prefix, "' matched first");
return HANDLER_ERROR;
}
}
}
}
}
return HANDLER_GO_ON;
}
#define PATCH(x) \
p->conf.x = s->x;
static int mod_alias_patch_connection(server *srv, connection *con, plugin_data *p) {
size_t i, j;
plugin_config *s = p->config_storage[0];
PATCH(alias);
/* skip the first, the global context */
for (i = 1; i < srv->config_context->used; i++) {
data_config *dc = (data_config *)srv->config_context->data[i];
s = p->config_storage[i];
/* condition didn't match */
if (!config_check_cond(srv, con, dc)) continue;
/* merge config */
for (j = 0; j < dc->value->used; j++) {
data_unset *du = dc->value->data[j];
if (buffer_is_equal_string(du->key, CONST_STR_LEN("alias.url"))) {
PATCH(alias);
}
}
}
return 0;
}
#undef PATCH
PHYSICALPATH_FUNC(mod_alias_physical_handler) {
plugin_data *p = p_d;
int uri_len, basedir_len;
char *uri_ptr;
size_t k;
if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;
mod_alias_patch_connection(srv, con, p);
/* not to include the tailing slash */
basedir_len = buffer_string_length(con->physical.basedir);
if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len;
uri_len = buffer_string_length(con->physical.path) - basedir_len;
uri_ptr = con->physical.path->ptr + basedir_len;
for (k = 0; k < p->conf.alias->used; k++) {
data_string *ds = (data_string *)p->conf.alias->data[k];
int alias_len = buffer_string_length(ds->key);
if (alias_len > uri_len) continue;
if (buffer_is_empty(ds->key)) continue;
if (0 == (con->conf.force_lowercase_filenames ?
strncasecmp(uri_ptr, ds->key->ptr, alias_len) :
strncmp(uri_ptr, ds->key->ptr, alias_len))) {
/* matched */
/* check for path traversal in url-path following alias if key
* does not end in slash, but replacement value ends in slash */
if (uri_ptr[alias_len] == '.') {
char *s = uri_ptr + alias_len + 1;
if (*s == '.') ++s;
if (*s == '/' || *s == '\0') {
size_t vlen = buffer_string_length(ds->value);
if (0 != alias_len && ds->key->ptr[alias_len-1] != '/'
&& 0 != vlen && ds->value->ptr[vlen-1] == '/') {
con->http_status = 403;
return HANDLER_FINISHED;
}
}
}
buffer_copy_buffer(con->physical.basedir, ds->value);
buffer_copy_buffer(srv->tmp_buf, ds->value);
buffer_append_string(srv->tmp_buf, uri_ptr + alias_len);
buffer_copy_buffer(con->physical.path, srv->tmp_buf);
return HANDLER_GO_ON;
}
}
/* not found */
return HANDLER_GO_ON;
}
/* this function is called at dlopen() time and inits the callbacks */
int mod_alias_plugin_init(plugin *p);
int mod_alias_plugin_init(plugin *p) {
p->version = LIGHTTPD_VERSION_ID;
p->name = buffer_init_string("alias");
p->init = mod_alias_init;
p->handle_physical= mod_alias_physical_handler;
p->set_defaults = mod_alias_set_defaults;
p->cleanup = mod_alias_free;
p->data = NULL;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_440_0 |
crossvul-cpp_data_good_1466_0 | /* pigz.c -- parallel implementation of gzip
* Copyright (C) 2007-2015 Mark Adler
* Version 2.3.2 xx Jan 2015 Mark Adler
*/
/*
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Mark Adler
madler@alumni.caltech.edu
Mark accepts donations for providing this software. Donations are not
required or expected. Any amount that you feel is appropriate would be
appreciated. You can use this link:
https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=536055
*/
/* Version history:
1.0 17 Jan 2007 First version, pipe only
1.1 28 Jan 2007 Avoid void * arithmetic (some compilers don't get that)
Add note about requiring zlib 1.2.3
Allow compression level 0 (no compression)
Completely rewrite parallelism -- add a write thread
Use deflateSetDictionary() to make use of history
Tune argument defaults to best performance on four cores
1.2.1 1 Feb 2007 Add long command line options, add all gzip options
Add debugging options
1.2.2 19 Feb 2007 Add list (--list) function
Process file names on command line, write .gz output
Write name and time in gzip header, set output file time
Implement all command line options except --recursive
Add --keep option to prevent deleting input files
Add thread tracing information with -vv used
Copy crc32_combine() from zlib (shared libraries issue)
1.3 25 Feb 2007 Implement --recursive
Expand help to show all options
Show help if no arguments or output piping are provided
Process options in GZIP environment variable
Add progress indicator to write thread if --verbose
1.4 4 Mar 2007 Add --independent to facilitate damaged file recovery
Reallocate jobs for new --blocksize or --processes
Do not delete original if writing to stdout
Allow --processes 1, which does no threading
Add NOTHREAD define to compile without threads
Incorporate license text from zlib in source code
1.5 25 Mar 2007 Reinitialize jobs for new compression level
Copy attributes and owner from input file to output file
Add decompression and testing
Add -lt (or -ltv) to show all entries and proper lengths
Add decompression, testing, listing of LZW (.Z) files
Only generate and show trace log if DEBUG defined
Take "-" argument to mean read file from stdin
1.6 30 Mar 2007 Add zlib stream compression (--zlib), and decompression
1.7 29 Apr 2007 Decompress first entry of a zip file (if deflated)
Avoid empty deflate blocks at end of deflate stream
Show zlib check value (Adler-32) when listing
Don't complain when decompressing empty file
Warn about trailing junk for gzip and zlib streams
Make listings consistent, ignore gzip extra flags
Add zip stream compression (--zip)
1.8 13 May 2007 Document --zip option in help output
2.0 19 Oct 2008 Complete rewrite of thread usage and synchronization
Use polling threads and a pool of memory buffers
Remove direct pthread library use, hide in yarn.c
2.0.1 20 Oct 2008 Check version of zlib at compile time, need >= 1.2.3
2.1 24 Oct 2008 Decompress with read, write, inflate, and check threads
Remove spurious use of ctime_r(), ctime() more portable
Change application of job->calc lock to be a semaphore
Detect size of off_t at run time to select %lu vs. %llu
#define large file support macro even if not __linux__
Remove _LARGEFILE64_SOURCE, _FILE_OFFSET_BITS is enough
Detect file-too-large error and report, blame build
Replace check combination routines with those from zlib
2.1.1 28 Oct 2008 Fix a leak for files with an integer number of blocks
Update for yarn 1.1 (yarn_prefix and yarn_abort)
2.1.2 30 Oct 2008 Work around use of beta zlib in production systems
2.1.3 8 Nov 2008 Don't use zlib combination routines, put back in pigz
2.1.4 9 Nov 2008 Fix bug when decompressing very short files
2.1.5 20 Jul 2009 Added 2008, 2009 to --license statement
Allow numeric parameter immediately after -p or -b
Enforce parameter after -p, -b, -s, before other options
Enforce numeric parameters to have only numeric digits
Try to determine the number of processors for -p default
Fix --suffix short option to be -S to match gzip [Bloch]
Decompress if executable named "unpigz" [Amundsen]
Add a little bit of testing to Makefile
2.1.6 17 Jan 2010 Added pigz.spec to distribution for RPM systems [Brown]
Avoid some compiler warnings
Process symbolic links if piping to stdout [Hoffstätte]
Decompress if executable named "gunzip" [Hoffstätte]
Allow ".tgz" suffix [Chernookiy]
Fix adler32 comparison on .zz files
2.1.7 17 Dec 2011 Avoid unused parameter warning in reenter()
Don't assume 2's complement ints in compress_thread()
Replicate gzip -cdf cat-like behavior
Replicate gzip -- option to suppress option decoding
Test output from make test instead of showing it
Updated pigz.spec to install unpigz, pigz.1 [Obermaier]
Add PIGZ environment variable [Mueller]
Replicate gzip suffix search when decoding or listing
Fix bug in load() to set in_left to zero on end of file
Do not check suffix when input file won't be modified
Decompress to stdout if name is "*cat" [Hayasaka]
Write data descriptor signature to be like Info-ZIP
Update and sort options list in help
Use CC variable for compiler in Makefile
Exit with code 2 if a warning has been issued
Fix thread synchronization problem when tracing
Change macro name MAX to MAX2 to avoid library conflicts
Determine number of processors on HP-UX [Lloyd]
2.2 31 Dec 2011 Check for expansion bound busting (e.g. modified zlib)
Make the "threads" list head global variable volatile
Fix construction and printing of 32-bit check values
Add --rsyncable functionality
2.2.1 1 Jan 2012 Fix bug in --rsyncable buffer management
2.2.2 1 Jan 2012 Fix another bug in --rsyncable buffer management
2.2.3 15 Jan 2012 Remove volatile in yarn.c
Reduce the number of input buffers
Change initial rsyncable hash to comparison value
Improve the efficiency of arriving at a byte boundary
Add thread portability #defines from yarn.c
Have rsyncable compression be independent of threading
Fix bug where constructed dictionaries not being used
2.2.4 11 Mar 2012 Avoid some return value warnings
Improve the portability of printing the off_t type
Check for existence of compress binary before using
Update zlib version checking to 1.2.6 for new functions
Fix bug in zip (-K) output
Fix license in pigz.spec
Remove thread portability #defines in pigz.c
2.2.5 28 Jul 2012 Avoid race condition in free_pool()
Change suffix to .tar when decompressing or listing .tgz
Print name of executable in error messages
Show help properly when the name is unpigz or gunzip
Fix permissions security problem before output is closed
2.3 3 Mar 2013 Don't complain about missing suffix on stdout
Put all global variables in a structure for readability
Do not decompress concatenated zlib streams (just gzip)
Add option for compression level 11 to use zopfli
Fix handling of junk after compressed data
2.3.1 9 Oct 2013 Fix builds of pigzt and pigzn to include zopfli
Add -lm, needed to link log function on some systems
Respect LDFLAGS in Makefile, use CFLAGS consistently
Add memory allocation tracking
Fix casting error in uncompressed length calculation
Update zopfli to Mar 10, 2013 Google state
Support zopfli in single thread case
Add -F, -I, -M, and -O options for zopfli tuning
2.3.2 xx Jan 2015 -
*/
#define VERSION "pigz 2.3.2\n"
/* To-do:
- make source portable for Windows, VMS, etc. (see gzip source code)
- make build portable (currently good for Unixish)
*/
/*
pigz compresses using threads to make use of multiple processors and cores.
The input is broken up into 128 KB chunks with each compressed in parallel.
The individual check value for each chunk is also calculated in parallel.
The compressed data is written in order to the output, and a combined check
value is calculated from the individual check values.
The compressed data format generated is in the gzip, zlib, or single-entry
zip format using the deflate compression method. The compression produces
partial raw deflate streams which are concatenated by a single write thread
and wrapped with the appropriate header and trailer, where the trailer
contains the combined check value.
Each partial raw deflate stream is terminated by an empty stored block
(using the Z_SYNC_FLUSH option of zlib), in order to end that partial bit
stream at a byte boundary, unless that partial stream happens to already end
at a byte boundary (the latter requires zlib 1.2.6 or later). Ending on a
byte boundary allows the partial streams to be concatenated simply as
sequences of bytes. This adds a very small four to five byte overhead
(average 3.75 bytes) to the output for each input chunk.
The default input block size is 128K, but can be changed with the -b option.
The number of compress threads is set by default to 8, which can be changed
using the -p option. Specifying -p 1 avoids the use of threads entirely.
pigz will try to determine the number of processors in the machine, in which
case if that number is two or greater, pigz will use that as the default for
-p instead of 8.
The input blocks, while compressed independently, have the last 32K of the
previous block loaded as a preset dictionary to preserve the compression
effectiveness of deflating in a single thread. This can be turned off using
the --independent or -i option, so that the blocks can be decompressed
independently for partial error recovery or for random access.
Decompression can't be parallelized, at least not without specially prepared
deflate streams for that purpose. As a result, pigz uses a single thread
(the main thread) for decompression, but will create three other threads for
reading, writing, and check calculation, which can speed up decompression
under some circumstances. Parallel decompression can be turned off by
specifying one process (-dp 1 or -tp 1).
pigz requires zlib 1.2.1 or later to allow setting the dictionary when doing
raw deflate. Since zlib 1.2.3 corrects security vulnerabilities in zlib
version 1.2.1 and 1.2.2, conditionals check for zlib 1.2.3 or later during
the compilation of pigz.c. zlib 1.2.4 includes some improvements to
Z_FULL_FLUSH and deflateSetDictionary() that permit identical output for
pigz with and without threads, which is not possible with zlib 1.2.3. This
may be important for uses of pigz -R where small changes in the contents
should result in small changes in the archive for rsync. Note that due to
the details of how the lower levels of compression result in greater speed,
compression level 3 and below does not permit identical pigz output with
and without threads.
pigz uses the POSIX pthread library for thread control and communication,
through the yarn.h interface to yarn.c. yarn.c can be replaced with
equivalent implementations using other thread libraries. pigz can be
compiled with NOTHREAD #defined to not use threads at all (in which case
pigz will not be able to live up to the "parallel" in its name).
*/
/*
Details of parallel compression implementation:
When doing parallel compression, pigz uses the main thread to read the input
in 'size' sized chunks (see -b), and puts those in a compression job list,
each with a sequence number to keep track of the ordering. If it is not the
first chunk, then that job also points to the previous input buffer, from
which the last 32K will be used as a dictionary (unless -i is specified).
This sets a lower limit of 32K on 'size'.
pigz launches up to 'procs' compression threads (see -p). Each compression
thread continues to look for jobs in the compression list and perform those
jobs until instructed to return. When a job is pulled, the dictionary, if
provided, will be loaded into the deflate engine and then that input buffer
is dropped for reuse. Then the input data is compressed into an output
buffer that grows in size if necessary to hold the compressed data. The job
is then put into the write job list, sorted by the sequence number. The
compress thread however continues to calculate the check value on the input
data, either a CRC-32 or Adler-32, possibly in parallel with the write
thread writing the output data. Once that's done, the compress thread drops
the input buffer and also releases the lock on the check value so that the
write thread can combine it with the previous check values. The compress
thread has then completed that job, and goes to look for another.
All of the compress threads are left running and waiting even after the last
chunk is processed, so that they can support the next input to be compressed
(more than one input file on the command line). Once pigz is done, it will
call all the compress threads home (that'll do pig, that'll do).
Before starting to read the input, the main thread launches the write thread
so that it is ready pick up jobs immediately. The compress thread puts the
write jobs in the list in sequence sorted order, so that the first job in
the list is always has the lowest sequence number. The write thread waits
for the next write job in sequence, and then gets that job. The job still
holds its input buffer, from which the write thread gets the input buffer
length for use in check value combination. Then the write thread drops that
input buffer to allow its reuse. Holding on to the input buffer until the
write thread starts also has the benefit that the read and compress threads
can't get way ahead of the write thread and build up a large backlog of
unwritten compressed data. The write thread will write the compressed data,
drop the output buffer, and then wait for the check value to be unlocked
by the compress thread. Then the write thread combines the check value for
this chunk with the total check value for eventual use in the trailer. If
this is not the last chunk, the write thread then goes back to look for the
next output chunk in sequence. After the last chunk, the write thread
returns and joins the main thread. Unlike the compress threads, a new write
thread is launched for each input stream. The write thread writes the
appropriate header and trailer around the compressed data.
The input and output buffers are reused through their collection in pools.
Each buffer has a use count, which when decremented to zero returns the
buffer to the respective pool. Each input buffer has up to three parallel
uses: as the input for compression, as the data for the check value
calculation, and as a dictionary for compression. Each output buffer has
only one use, which is as the output of compression followed serially as
data to be written. The input pool is limited in the number of buffers, so
that reading does not get way ahead of compression and eat up memory with
more input than can be used. The limit is approximately two times the
number of compression threads. In the case that reading is fast as compared
to compression, that number allows a second set of buffers to be read while
the first set of compressions are being performed. The number of output
buffers is not directly limited, but is indirectly limited by the release of
input buffers to about the same number.
*/
/* use large file functions if available */
#define _FILE_OFFSET_BITS 64
/* included headers and what is expected from each */
#include <stdio.h> /* fflush(), fprintf(), fputs(), getchar(), putc(), */
/* puts(), printf(), vasprintf(), stderr, EOF, NULL,
SEEK_END, size_t, off_t */
#include <stdlib.h> /* exit(), malloc(), free(), realloc(), atol(), */
/* atoi(), getenv() */
#include <stdarg.h> /* va_start(), va_end(), va_list */
#include <string.h> /* memset(), memchr(), memcpy(), strcmp(), strcpy() */
/* strncpy(), strlen(), strcat(), strrchr() */
#include <errno.h> /* errno, EEXIST */
#include <assert.h> /* assert() */
#include <time.h> /* ctime(), time(), time_t, mktime() */
#include <signal.h> /* signal(), SIGINT */
#include <sys/types.h> /* ssize_t */
#include <sys/stat.h> /* chmod(), stat(), fstat(), lstat(), struct stat, */
/* S_IFDIR, S_IFLNK, S_IFMT, S_IFREG */
#include <sys/time.h> /* utimes(), gettimeofday(), struct timeval */
#include <unistd.h> /* unlink(), _exit(), read(), write(), close(), */
/* lseek(), isatty(), chown() */
#include <fcntl.h> /* open(), O_CREAT, O_EXCL, O_RDONLY, O_TRUNC, */
/* O_WRONLY */
#include <dirent.h> /* opendir(), readdir(), closedir(), DIR, */
/* struct dirent */
#include <limits.h> /* PATH_MAX, UINT_MAX, INT_MAX */
#if __STDC_VERSION__-0 >= 199901L || __GNUC__-0 >= 3
# include <inttypes.h> /* intmax_t */
#endif
#ifdef DEBUG
# if defined(__APPLE__)
# include <malloc/malloc.h>
# define MALLOC_SIZE(p) malloc_size(p)
# elif defined (__linux)
# include <malloc.h>
# define MALLOC_SIZE(p) malloc_usable_size(p)
# elif defined (_WIN32) || defined(_WIN64)
# include <malloc.h>
# define MALLOC_SIZE(p) _msize(p)
# else
# define MALLOC_SIZE(p) (0)
# endif
#endif
#ifdef __hpux
# include <sys/param.h>
# include <sys/pstat.h>
#endif
#include "zlib.h" /* deflateInit2(), deflateReset(), deflate(), */
/* deflateEnd(), deflateSetDictionary(), crc32(),
inflateBackInit(), inflateBack(), inflateBackEnd(),
Z_DEFAULT_COMPRESSION, Z_DEFAULT_STRATEGY,
Z_DEFLATED, Z_NO_FLUSH, Z_NULL, Z_OK,
Z_SYNC_FLUSH, z_stream */
#if !defined(ZLIB_VERNUM) || ZLIB_VERNUM < 0x1230
# error Need zlib version 1.2.3 or later
#endif
#ifndef NOTHREAD
# include "yarn.h" /* thread, launch(), join(), join_all(), */
/* lock, new_lock(), possess(), twist(), wait_for(),
release(), peek_lock(), free_lock(), yarn_name */
#endif
#include "zopfli/src/zopfli/deflate.h" /* ZopfliDeflatePart(),
ZopfliInitOptions(),
ZopfliOptions */
/* for local functions and globals */
#define local static
/* prevent end-of-line conversions on MSDOSish operating systems */
#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
# include <io.h> /* setmode(), O_BINARY */
# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
#else
# define SET_BINARY_MODE(fd)
#endif
/* release an allocated pointer, if allocated, and mark as unallocated */
#define RELEASE(ptr) \
do { \
if ((ptr) != NULL) { \
FREE(ptr); \
ptr = NULL; \
} \
} while (0)
/* sliding dictionary size for deflate */
#define DICT 32768U
/* largest power of 2 that fits in an unsigned int -- used to limit requests
to zlib functions that use unsigned int lengths */
#define MAXP2 (UINT_MAX - (UINT_MAX >> 1))
/* rsyncable constants -- RSYNCBITS is the number of bits in the mask for
comparison. For random input data, there will be a hit on average every
1<<RSYNCBITS bytes. So for an RSYNCBITS of 12, there will be an average of
one hit every 4096 bytes, resulting in a mean block size of 4096. RSYNCMASK
is the resulting bit mask. RSYNCHIT is what the hash value is compared to
after applying the mask.
The choice of 12 for RSYNCBITS is consistent with the original rsyncable
patch for gzip which also uses a 12-bit mask. This results in a relatively
small hit to compression, on the order of 1.5% to 3%. A mask of 13 bits can
be used instead if a hit of less than 1% to the compression is desired, at
the expense of more blocks transmitted for rsync updates. (Your mileage may
vary.)
This implementation of rsyncable uses a different hash algorithm than what
the gzip rsyncable patch uses in order to provide better performance in
several regards. The algorithm is simply to shift the hash value left one
bit and exclusive-or that with the next byte. This is masked to the number
of hash bits (RSYNCMASK) and compared to all ones except for a zero in the
top bit (RSYNCHIT). This rolling hash has a very small window of 19 bytes
(RSYNCBITS+7). The small window provides the benefit of much more rapid
resynchronization after a change, than does the 4096-byte window of the gzip
rsyncable patch.
The comparison value is chosen to avoid matching any repeated bytes or short
sequences. The gzip rsyncable patch on the other hand uses a sum and zero
for comparison, which results in certain bad behaviors, such as always
matching everywhere in a long sequence of zeros. Such sequences occur
frequently in tar files.
This hash efficiently discards history older than 19 bytes simply by
shifting that data past the top of the mask -- no history needs to be
retained to undo its impact on the hash value, as is needed for a sum.
The choice of the comparison value (RSYNCHIT) has the virtue of avoiding
extremely short blocks. The shortest block is five bytes (RSYNCBITS-7) from
hit to hit, and is unlikely. Whereas with the gzip rsyncable algorithm,
blocks of one byte are not only possible, but in fact are the most likely
block size.
Thanks and acknowledgement to Kevin Day for his experimentation and insights
on rsyncable hash characteristics that led to some of the choices here.
*/
#define RSYNCBITS 12
#define RSYNCMASK ((1U << RSYNCBITS) - 1)
#define RSYNCHIT (RSYNCMASK >> 1)
/* initial pool counts and sizes -- INBUFS is the limit on the number of input
spaces as a function of the number of processors (used to throttle the
creation of compression jobs), OUTPOOL is the initial size of the output
data buffer, chosen to make resizing of the buffer very unlikely and to
allow prepending with a dictionary for use as an input buffer for zopfli */
#define INBUFS(p) (((p)<<1)+3)
#define OUTPOOL(s) ((s)+((s)>>4)+DICT)
/* input buffer size */
#define BUF 32768U
/* globals (modified by main thread only when it's the only thread) */
local struct {
char *prog; /* name by which pigz was invoked */
int ind; /* input file descriptor */
int outd; /* output file descriptor */
char inf[PATH_MAX+1]; /* input file name (accommodate recursion) */
char *outf; /* output file name (allocated if not NULL) */
int verbosity; /* 0 = quiet, 1 = normal, 2 = verbose, 3 = trace */
int headis; /* 1 to store name, 2 to store date, 3 both */
int pipeout; /* write output to stdout even if file */
int keep; /* true to prevent deletion of input file */
int force; /* true to overwrite, compress links, cat */
int form; /* gzip = 0, zlib = 1, zip = 2 or 3 */
unsigned char magic1; /* first byte of possible header when decoding */
int recurse; /* true to dive down into directory structure */
char *sufx; /* suffix to use (".gz" or user supplied) */
char *name; /* name for gzip header */
time_t mtime; /* time stamp from input file for gzip header */
int list; /* true to list files instead of compress */
int first; /* true if we need to print listing header */
int decode; /* 0 to compress, 1 to decompress, 2 to test */
int level; /* compression level */
ZopfliOptions zopts; /* zopfli compression options */
int rsync; /* true for rsync blocking */
int procs; /* maximum number of compression threads (>= 1) */
int setdict; /* true to initialize dictionary in each thread */
size_t block; /* uncompressed input size per thread (>= 32K) */
/* saved gzip/zip header data for decompression, testing, and listing */
time_t stamp; /* time stamp from gzip header */
char *hname; /* name from header (allocated) */
unsigned long zip_crc; /* local header crc */
unsigned long zip_clen; /* local header compressed length */
unsigned long zip_ulen; /* local header uncompressed length */
/* globals for decompression and listing buffered reading */
unsigned char in_buf[BUF]; /* input buffer */
unsigned char *in_next; /* next unused byte in buffer */
size_t in_left; /* number of unused bytes in buffer */
int in_eof; /* true if reached end of file on input */
int in_short; /* true if last read didn't fill buffer */
off_t in_tot; /* total bytes read from input */
off_t out_tot; /* total bytes written to output */
unsigned long out_check; /* check value of output */
#ifndef NOTHREAD
/* globals for decompression parallel reading */
unsigned char in_buf2[BUF]; /* second buffer for parallel reads */
size_t in_len; /* data waiting in next buffer */
int in_which; /* -1: start, 0: in_buf2, 1: in_buf */
lock *load_state; /* value = 0 to wait, 1 to read a buffer */
thread *load_thread; /* load_read() thread for joining */
#endif
} g;
/* display a complaint with the program name on stderr */
local int complain(char *fmt, ...)
{
va_list ap;
if (g.verbosity > 0) {
fprintf(stderr, "%s: ", g.prog);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
putc('\n', stderr);
fflush(stderr);
}
return 0;
}
/* exit with error, delete output file if in the middle of writing it */
local int bail(char *why, char *what)
{
if (g.outd != -1 && g.outf != NULL)
unlink(g.outf);
complain("abort: %s%s", why, what);
exit(1);
return 0;
}
#ifdef DEBUG
/* memory tracking */
local struct mem_track_s {
size_t num; /* current number of allocations */
size_t size; /* total size of current allocations */
size_t max; /* maximum size of allocations */
#ifndef NOTHREAD
lock *lock; /* lock for access across threads */
#endif
} mem_track;
#ifndef NOTHREAD
# define mem_track_grab(m) possess((m)->lock)
# define mem_track_drop(m) release((m)->lock)
#else
# define mem_track_grab(m)
# define mem_track_drop(m)
#endif
local void *malloc_track(struct mem_track_s *mem, size_t size)
{
void *ptr;
ptr = malloc(size);
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->num++;
mem->size += size;
if (mem->size > mem->max)
mem->max = mem->size;
mem_track_drop(mem);
}
return ptr;
}
local void *realloc_track(struct mem_track_s *mem, void *ptr, size_t size)
{
size_t was;
if (ptr == NULL)
return malloc_track(mem, size);
was = MALLOC_SIZE(ptr);
ptr = realloc(ptr, size);
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->size -= was;
mem->size += size;
if (mem->size > mem->max)
mem->max = mem->size;
mem_track_drop(mem);
}
return ptr;
}
local void free_track(struct mem_track_s *mem, void *ptr)
{
size_t size;
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->num--;
mem->size -= size;
mem_track_drop(mem);
free(ptr);
}
}
#ifndef NOTHREAD
local void *yarn_malloc(size_t size)
{
return malloc_track(&mem_track, size);
}
local void yarn_free(void *ptr)
{
return free_track(&mem_track, ptr);
}
#endif
local voidpf zlib_alloc(voidpf opaque, uInt items, uInt size)
{
return malloc_track(opaque, items * (size_t)size);
}
local void zlib_free(voidpf opaque, voidpf address)
{
free_track(opaque, address);
}
#define MALLOC(s) malloc_track(&mem_track, s)
#define REALLOC(p, s) realloc_track(&mem_track, p, s)
#define FREE(p) free_track(&mem_track, p)
#define OPAQUE (&mem_track)
#define ZALLOC zlib_alloc
#define ZFREE zlib_free
/* starting time of day for tracing */
local struct timeval start;
/* trace log */
local struct log {
struct timeval when; /* time of entry */
char *msg; /* message */
struct log *next; /* next entry */
} *log_head, **log_tail = NULL;
#ifndef NOTHREAD
local lock *log_lock = NULL;
#endif
/* maximum log entry length */
#define MAXMSG 256
/* set up log (call from main thread before other threads launched) */
local void log_init(void)
{
if (log_tail == NULL) {
mem_track.num = 0;
mem_track.size = 0;
mem_track.max = 0;
#ifndef NOTHREAD
mem_track.lock = new_lock(0);
yarn_mem(yarn_malloc, yarn_free);
log_lock = new_lock(0);
#endif
log_head = NULL;
log_tail = &log_head;
}
}
/* add entry to trace log */
local void log_add(char *fmt, ...)
{
struct timeval now;
struct log *me;
va_list ap;
char msg[MAXMSG];
gettimeofday(&now, NULL);
me = MALLOC(sizeof(struct log));
if (me == NULL)
bail("not enough memory", "");
me->when = now;
va_start(ap, fmt);
vsnprintf(msg, MAXMSG, fmt, ap);
va_end(ap);
me->msg = MALLOC(strlen(msg) + 1);
if (me->msg == NULL) {
FREE(me);
bail("not enough memory", "");
}
strcpy(me->msg, msg);
me->next = NULL;
#ifndef NOTHREAD
assert(log_lock != NULL);
possess(log_lock);
#endif
*log_tail = me;
log_tail = &(me->next);
#ifndef NOTHREAD
twist(log_lock, BY, +1);
#endif
}
/* pull entry from trace log and print it, return false if empty */
local int log_show(void)
{
struct log *me;
struct timeval diff;
if (log_tail == NULL)
return 0;
#ifndef NOTHREAD
possess(log_lock);
#endif
me = log_head;
if (me == NULL) {
#ifndef NOTHREAD
release(log_lock);
#endif
return 0;
}
log_head = me->next;
if (me->next == NULL)
log_tail = &log_head;
#ifndef NOTHREAD
twist(log_lock, BY, -1);
#endif
diff.tv_usec = me->when.tv_usec - start.tv_usec;
diff.tv_sec = me->when.tv_sec - start.tv_sec;
if (diff.tv_usec < 0) {
diff.tv_usec += 1000000L;
diff.tv_sec--;
}
fprintf(stderr, "trace %ld.%06ld %s\n",
(long)diff.tv_sec, (long)diff.tv_usec, me->msg);
fflush(stderr);
FREE(me->msg);
FREE(me);
return 1;
}
/* release log resources (need to do log_init() to use again) */
local void log_free(void)
{
struct log *me;
if (log_tail != NULL) {
#ifndef NOTHREAD
possess(log_lock);
#endif
while ((me = log_head) != NULL) {
log_head = me->next;
FREE(me->msg);
FREE(me);
}
#ifndef NOTHREAD
twist(log_lock, TO, 0);
free_lock(log_lock);
log_lock = NULL;
yarn_mem(malloc, free);
free_lock(mem_track.lock);
#endif
log_tail = NULL;
}
}
/* show entries until no more, free log */
local void log_dump(void)
{
if (log_tail == NULL)
return;
while (log_show())
;
log_free();
if (mem_track.num || mem_track.size)
complain("memory leak: %lu allocs of %lu bytes total",
mem_track.num, mem_track.size);
if (mem_track.max)
fprintf(stderr, "%lu bytes of memory used\n", mem_track.max);
}
/* debugging macro */
#define Trace(x) \
do { \
if (g.verbosity > 2) { \
log_add x; \
} \
} while (0)
#else /* !DEBUG */
#define MALLOC malloc
#define REALLOC realloc
#define FREE free
#define OPAQUE Z_NULL
#define ZALLOC Z_NULL
#define ZFREE Z_NULL
#define log_dump()
#define Trace(x)
#endif
/* read up to len bytes into buf, repeating read() calls as needed */
local size_t readn(int desc, unsigned char *buf, size_t len)
{
ssize_t ret;
size_t got;
got = 0;
while (len) {
ret = read(desc, buf, len);
if (ret < 0)
bail("read error on ", g.inf);
if (ret == 0)
break;
buf += ret;
len -= ret;
got += ret;
}
return got;
}
/* write len bytes, repeating write() calls as needed */
local void writen(int desc, unsigned char *buf, size_t len)
{
ssize_t ret;
while (len) {
ret = write(desc, buf, len);
if (ret < 1) {
complain("write error code %d", errno);
bail("write error on ", g.outf);
}
buf += ret;
len -= ret;
}
}
/* convert Unix time to MS-DOS date and time, assuming current timezone
(you got a better idea?) */
local unsigned long time2dos(time_t t)
{
struct tm *tm;
unsigned long dos;
if (t == 0)
t = time(NULL);
tm = localtime(&t);
if (tm->tm_year < 80 || tm->tm_year > 207)
return 0;
dos = (tm->tm_year - 80) << 25;
dos += (tm->tm_mon + 1) << 21;
dos += tm->tm_mday << 16;
dos += tm->tm_hour << 11;
dos += tm->tm_min << 5;
dos += (tm->tm_sec + 1) >> 1; /* round to double-seconds */
return dos;
}
/* put a 4-byte integer into a byte array in LSB order or MSB order */
#define PUT2L(a,b) (*(a)=(b)&0xff,(a)[1]=(b)>>8)
#define PUT4L(a,b) (PUT2L(a,(b)&0xffff),PUT2L((a)+2,(b)>>16))
#define PUT4M(a,b) (*(a)=(b)>>24,(a)[1]=(b)>>16,(a)[2]=(b)>>8,(a)[3]=(b))
/* write a gzip, zlib, or zip header using the information in the globals */
local unsigned long put_header(void)
{
unsigned long len;
unsigned char head[30];
if (g.form > 1) { /* zip */
/* write local header */
PUT4L(head, 0x04034b50UL); /* local header signature */
PUT2L(head + 4, 20); /* version needed to extract (2.0) */
PUT2L(head + 6, 8); /* flags: data descriptor follows data */
PUT2L(head + 8, 8); /* deflate */
PUT4L(head + 10, time2dos(g.mtime));
PUT4L(head + 14, 0); /* crc (not here) */
PUT4L(head + 18, 0); /* compressed length (not here) */
PUT4L(head + 22, 0); /* uncompressed length (not here) */
PUT2L(head + 26, g.name == NULL ? 1 : /* length of name */
strlen(g.name));
PUT2L(head + 28, 9); /* length of extra field (see below) */
writen(g.outd, head, 30); /* write local header */
len = 30;
/* write file name (use "-" for stdin) */
if (g.name == NULL)
writen(g.outd, (unsigned char *)"-", 1);
else
writen(g.outd, (unsigned char *)g.name, strlen(g.name));
len += g.name == NULL ? 1 : strlen(g.name);
/* write extended timestamp extra field block (9 bytes) */
PUT2L(head, 0x5455); /* extended timestamp signature */
PUT2L(head + 2, 5); /* number of data bytes in this block */
head[4] = 1; /* flag presence of mod time */
PUT4L(head + 5, g.mtime); /* mod time */
writen(g.outd, head, 9); /* write extra field block */
len += 9;
}
else if (g.form) { /* zlib */
head[0] = 0x78; /* deflate, 32K window */
head[1] = (g.level >= 9 ? 3 :
(g.level == 1 ? 0 :
(g.level >= 6 || g.level == Z_DEFAULT_COMPRESSION ?
1 : 2))) << 6;
head[1] += 31 - (((head[0] << 8) + head[1]) % 31);
writen(g.outd, head, 2);
len = 2;
}
else { /* gzip */
head[0] = 31;
head[1] = 139;
head[2] = 8; /* deflate */
head[3] = g.name != NULL ? 8 : 0;
PUT4L(head + 4, g.mtime);
head[8] = g.level >= 9 ? 2 : (g.level == 1 ? 4 : 0);
head[9] = 3; /* unix */
writen(g.outd, head, 10);
len = 10;
if (g.name != NULL)
writen(g.outd, (unsigned char *)g.name, strlen(g.name) + 1);
if (g.name != NULL)
len += strlen(g.name) + 1;
}
return len;
}
/* write a gzip, zlib, or zip trailer */
local void put_trailer(unsigned long ulen, unsigned long clen,
unsigned long check, unsigned long head)
{
unsigned char tail[46];
if (g.form > 1) { /* zip */
unsigned long cent;
/* write data descriptor (as promised in local header) */
PUT4L(tail, 0x08074b50UL);
PUT4L(tail + 4, check);
PUT4L(tail + 8, clen);
PUT4L(tail + 12, ulen);
writen(g.outd, tail, 16);
/* write central file header */
PUT4L(tail, 0x02014b50UL); /* central header signature */
tail[4] = 63; /* obeyed version 6.3 of the zip spec */
tail[5] = 255; /* ignore external attributes */
PUT2L(tail + 6, 20); /* version needed to extract (2.0) */
PUT2L(tail + 8, 8); /* data descriptor is present */
PUT2L(tail + 10, 8); /* deflate */
PUT4L(tail + 12, time2dos(g.mtime));
PUT4L(tail + 16, check); /* crc */
PUT4L(tail + 20, clen); /* compressed length */
PUT4L(tail + 24, ulen); /* uncompressed length */
PUT2L(tail + 28, g.name == NULL ? 1 : /* length of name */
strlen(g.name));
PUT2L(tail + 30, 9); /* length of extra field (see below) */
PUT2L(tail + 32, 0); /* no file comment */
PUT2L(tail + 34, 0); /* disk number 0 */
PUT2L(tail + 36, 0); /* internal file attributes */
PUT4L(tail + 38, 0); /* external file attributes (ignored) */
PUT4L(tail + 42, 0); /* offset of local header */
writen(g.outd, tail, 46); /* write central file header */
cent = 46;
/* write file name (use "-" for stdin) */
if (g.name == NULL)
writen(g.outd, (unsigned char *)"-", 1);
else
writen(g.outd, (unsigned char *)g.name, strlen(g.name));
cent += g.name == NULL ? 1 : strlen(g.name);
/* write extended timestamp extra field block (9 bytes) */
PUT2L(tail, 0x5455); /* extended timestamp signature */
PUT2L(tail + 2, 5); /* number of data bytes in this block */
tail[4] = 1; /* flag presence of mod time */
PUT4L(tail + 5, g.mtime); /* mod time */
writen(g.outd, tail, 9); /* write extra field block */
cent += 9;
/* write end of central directory record */
PUT4L(tail, 0x06054b50UL); /* end of central directory signature */
PUT2L(tail + 4, 0); /* number of this disk */
PUT2L(tail + 6, 0); /* disk with start of central directory */
PUT2L(tail + 8, 1); /* number of entries on this disk */
PUT2L(tail + 10, 1); /* total number of entries */
PUT4L(tail + 12, cent); /* size of central directory */
PUT4L(tail + 16, head + clen + 16); /* offset of central directory */
PUT2L(tail + 20, 0); /* no zip file comment */
writen(g.outd, tail, 22); /* write end of central directory record */
}
else if (g.form) { /* zlib */
PUT4M(tail, check);
writen(g.outd, tail, 4);
}
else { /* gzip */
PUT4L(tail, check);
PUT4L(tail + 4, ulen);
writen(g.outd, tail, 8);
}
}
/* compute check value depending on format */
#define CHECK(a,b,c) (g.form == 1 ? adler32(a,b,c) : crc32(a,b,c))
#ifndef NOTHREAD
/* -- threaded portions of pigz -- */
/* -- check value combination routines for parallel calculation -- */
#define COMB(a,b,c) (g.form == 1 ? adler32_comb(a,b,c) : crc32_comb(a,b,c))
/* combine two crc-32's or two adler-32's (copied from zlib 1.2.3 so that pigz
can be compatible with older versions of zlib) */
/* we copy the combination routines from zlib here, in order to avoid
linkage issues with the zlib 1.2.3 builds on Sun, Ubuntu, and others */
local unsigned long gf2_matrix_times(unsigned long *mat, unsigned long vec)
{
unsigned long sum;
sum = 0;
while (vec) {
if (vec & 1)
sum ^= *mat;
vec >>= 1;
mat++;
}
return sum;
}
local void gf2_matrix_square(unsigned long *square, unsigned long *mat)
{
int n;
for (n = 0; n < 32; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
local unsigned long crc32_comb(unsigned long crc1, unsigned long crc2,
size_t len2)
{
int n;
unsigned long row;
unsigned long even[32]; /* even-power-of-two zeros operator */
unsigned long odd[32]; /* odd-power-of-two zeros operator */
/* degenerate case */
if (len2 == 0)
return crc1;
/* put operator for one zero bit in odd */
odd[0] = 0xedb88320UL; /* CRC-32 polynomial */
row = 1;
for (n = 1; n < 32; n++) {
odd[n] = row;
row <<= 1;
}
/* put operator for two zero bits in even */
gf2_matrix_square(even, odd);
/* put operator for four zero bits in odd */
gf2_matrix_square(odd, even);
/* apply len2 zeros to crc1 (first square will put the operator for one
zero byte, eight zero bits, in even) */
do {
/* apply zeros operator for this bit of len2 */
gf2_matrix_square(even, odd);
if (len2 & 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
/* if no more bits set, then done */
if (len2 == 0)
break;
/* another iteration of the loop with odd and even swapped */
gf2_matrix_square(odd, even);
if (len2 & 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
/* if no more bits set, then done */
} while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}
#define BASE 65521U /* largest prime smaller than 65536 */
#define LOW16 0xffff /* mask lower 16 bits */
local unsigned long adler32_comb(unsigned long adler1, unsigned long adler2,
size_t len2)
{
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* the derivation of this formula is left as an exercise for the reader */
rem = (unsigned)(len2 % BASE);
sum1 = adler1 & LOW16;
sum2 = (rem * sum1) % BASE;
sum1 += (adler2 & LOW16) + BASE - 1;
sum2 += ((adler1 >> 16) & LOW16) + ((adler2 >> 16) & LOW16) + BASE - rem;
if (sum1 >= BASE) sum1 -= BASE;
if (sum1 >= BASE) sum1 -= BASE;
if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 >= BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
}
/* -- pool of spaces for buffer management -- */
/* These routines manage a pool of spaces. Each pool specifies a fixed size
buffer to be contained in each space. Each space has a use count, which
when decremented to zero returns the space to the pool. If a space is
requested from the pool and the pool is empty, a space is immediately
created unless a specified limit on the number of spaces has been reached.
Only if the limit is reached will it wait for a space to be returned to the
pool. Each space knows what pool it belongs to, so that it can be returned.
*/
/* a space (one buffer for each space) */
struct space {
lock *use; /* use count -- return to pool when zero */
unsigned char *buf; /* buffer of size size */
size_t size; /* current size of this buffer */
size_t len; /* for application usage (initially zero) */
struct pool *pool; /* pool to return to */
struct space *next; /* for pool linked list */
};
/* pool of spaces (one pool for each type needed) */
struct pool {
lock *have; /* unused spaces available, lock for list */
struct space *head; /* linked list of available buffers */
size_t size; /* size of new buffers in this pool */
int limit; /* number of new spaces allowed, or -1 */
int made; /* number of buffers made */
};
/* initialize a pool (pool structure itself provided, not allocated) -- the
limit is the maximum number of spaces in the pool, or -1 to indicate no
limit, i.e., to never wait for a buffer to return to the pool */
local void new_pool(struct pool *pool, size_t size, int limit)
{
pool->have = new_lock(0);
pool->head = NULL;
pool->size = size;
pool->limit = limit;
pool->made = 0;
}
/* get a space from a pool -- the use count is initially set to one, so there
is no need to call use_space() for the first use */
local struct space *get_space(struct pool *pool)
{
struct space *space;
/* if can't create any more, wait for a space to show up */
possess(pool->have);
if (pool->limit == 0)
wait_for(pool->have, NOT_TO_BE, 0);
/* if a space is available, pull it from the list and return it */
if (pool->head != NULL) {
space = pool->head;
possess(space->use);
pool->head = space->next;
twist(pool->have, BY, -1); /* one less in pool */
twist(space->use, TO, 1); /* initially one user */
space->len = 0;
return space;
}
/* nothing available, don't want to wait, make a new space */
assert(pool->limit != 0);
if (pool->limit > 0)
pool->limit--;
pool->made++;
release(pool->have);
space = MALLOC(sizeof(struct space));
if (space == NULL)
bail("not enough memory", "");
space->use = new_lock(1); /* initially one user */
space->buf = MALLOC(pool->size);
if (space->buf == NULL)
bail("not enough memory", "");
space->size = pool->size;
space->len = 0;
space->pool = pool; /* remember the pool this belongs to */
return space;
}
/* compute next size up by multiplying by about 2**(1/3) and round to the next
power of 2 if we're close (so three applications results in doubling) -- if
small, go up to at least 16, if overflow, go to max size_t value */
local size_t grow(size_t size)
{
size_t was, top;
int shift;
was = size;
size += size >> 2;
top = size;
for (shift = 0; top > 7; shift++)
top >>= 1;
if (top == 7)
size = (size_t)1 << (shift + 3);
if (size < 16)
size = 16;
if (size <= was)
size = (size_t)0 - 1;
return size;
}
/* increase the size of the buffer in space */
local void grow_space(struct space *space)
{
size_t more;
/* compute next size up */
more = grow(space->size);
if (more == space->size)
bail("not enough memory", "");
/* reallocate the buffer */
space->buf = REALLOC(space->buf, more);
if (space->buf == NULL)
bail("not enough memory", "");
space->size = more;
}
/* increment the use count to require one more drop before returning this space
to the pool */
local void use_space(struct space *space)
{
possess(space->use);
twist(space->use, BY, +1);
}
/* drop a space, returning it to the pool if the use count is zero */
local void drop_space(struct space *space)
{
int use;
struct pool *pool;
possess(space->use);
use = peek_lock(space->use);
assert(use != 0);
if (use == 1) {
pool = space->pool;
possess(pool->have);
space->next = pool->head;
pool->head = space;
twist(pool->have, BY, +1);
}
twist(space->use, BY, -1);
}
/* free the memory and lock resources of a pool -- return number of spaces for
debugging and resource usage measurement */
local int free_pool(struct pool *pool)
{
int count;
struct space *space;
possess(pool->have);
count = 0;
while ((space = pool->head) != NULL) {
pool->head = space->next;
FREE(space->buf);
free_lock(space->use);
FREE(space);
count++;
}
assert(count == pool->made);
release(pool->have);
free_lock(pool->have);
return count;
}
/* input and output buffer pools */
local struct pool in_pool;
local struct pool out_pool;
local struct pool dict_pool;
local struct pool lens_pool;
/* -- parallel compression -- */
/* compress or write job (passed from compress list to write list) -- if seq is
equal to -1, compress_thread is instructed to return; if more is false then
this is the last chunk, which after writing tells write_thread to return */
struct job {
long seq; /* sequence number */
int more; /* true if this is not the last chunk */
struct space *in; /* input data to compress */
struct space *out; /* dictionary or resulting compressed data */
struct space *lens; /* coded list of flush block lengths */
unsigned long check; /* check value for input data */
lock *calc; /* released when check calculation complete */
struct job *next; /* next job in the list (either list) */
};
/* list of compress jobs (with tail for appending to list) */
local lock *compress_have = NULL; /* number of compress jobs waiting */
local struct job *compress_head, **compress_tail;
/* list of write jobs */
local lock *write_first; /* lowest sequence number in list */
local struct job *write_head;
/* number of compression threads running */
local int cthreads = 0;
/* write thread if running */
local thread *writeth = NULL;
/* setup job lists (call from main thread) */
local void setup_jobs(void)
{
/* set up only if not already set up*/
if (compress_have != NULL)
return;
/* allocate locks and initialize lists */
compress_have = new_lock(0);
compress_head = NULL;
compress_tail = &compress_head;
write_first = new_lock(-1);
write_head = NULL;
/* initialize buffer pools (initial size for out_pool not critical, since
buffers will be grown in size if needed -- initial size chosen to make
this unlikely -- same for lens_pool) */
new_pool(&in_pool, g.block, INBUFS(g.procs));
new_pool(&out_pool, OUTPOOL(g.block), -1);
new_pool(&dict_pool, DICT, -1);
new_pool(&lens_pool, g.block >> (RSYNCBITS - 1), -1);
}
/* command the compress threads to all return, then join them all (call from
main thread), free all the thread-related resources */
local void finish_jobs(void)
{
struct job job;
int caught;
/* only do this once */
if (compress_have == NULL)
return;
/* command all of the extant compress threads to return */
possess(compress_have);
job.seq = -1;
job.next = NULL;
compress_head = &job;
compress_tail = &(job.next);
twist(compress_have, BY, +1); /* will wake them all up */
/* join all of the compress threads, verify they all came back */
caught = join_all();
Trace(("-- joined %d compress threads", caught));
assert(caught == cthreads);
cthreads = 0;
/* free the resources */
caught = free_pool(&lens_pool);
Trace(("-- freed %d block lengths buffers", caught));
caught = free_pool(&dict_pool);
Trace(("-- freed %d dictionary buffers", caught));
caught = free_pool(&out_pool);
Trace(("-- freed %d output buffers", caught));
caught = free_pool(&in_pool);
Trace(("-- freed %d input buffers", caught));
free_lock(write_first);
free_lock(compress_have);
compress_have = NULL;
}
/* compress all strm->avail_in bytes at strm->next_in to out->buf, updating
out->len, grow the size of the buffer (out->size) if necessary -- respect
the size limitations of the zlib stream data types (size_t may be larger
than unsigned) */
local void deflate_engine(z_stream *strm, struct space *out, int flush)
{
size_t room;
do {
room = out->size - out->len;
if (room == 0) {
grow_space(out);
room = out->size - out->len;
}
strm->next_out = out->buf + out->len;
strm->avail_out = room < UINT_MAX ? (unsigned)room : UINT_MAX;
(void)deflate(strm, flush);
out->len = strm->next_out - out->buf;
} while (strm->avail_out == 0);
assert(strm->avail_in == 0);
}
/* get the next compression job from the head of the list, compress and compute
the check value on the input, and put a job in the write list with the
results -- keep looking for more jobs, returning when a job is found with a
sequence number of -1 (leave that job in the list for other incarnations to
find) */
local void compress_thread(void *dummy)
{
struct job *job; /* job pulled and working on */
struct job *here, **prior; /* pointers for inserting in write list */
unsigned long check; /* check value of input */
unsigned char *next; /* pointer for blocks, check value data */
size_t left; /* input left to process */
size_t len; /* remaining bytes to compress/check */
#if ZLIB_VERNUM >= 0x1260
int bits; /* deflate pending bits */
#endif
struct space *temp = NULL; /* temporary space for zopfli input */
z_stream strm; /* deflate stream */
(void)dummy;
/* initialize the deflate stream for this thread */
strm.zfree = ZFREE;
strm.zalloc = ZALLOC;
strm.opaque = OPAQUE;
if (deflateInit2(&strm, 6, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK)
bail("not enough memory", "");
/* keep looking for work */
for (;;) {
/* get a job (like I tell my son) */
possess(compress_have);
wait_for(compress_have, NOT_TO_BE, 0);
job = compress_head;
assert(job != NULL);
if (job->seq == -1)
break;
compress_head = job->next;
if (job->next == NULL)
compress_tail = &compress_head;
twist(compress_have, BY, -1);
/* got a job -- initialize and set the compression level (note that if
deflateParams() is called immediately after deflateReset(), there is
no need to initialize the input/output for the stream) */
Trace(("-- compressing #%ld", job->seq));
if (g.level <= 9) {
(void)deflateReset(&strm);
(void)deflateParams(&strm, g.level, Z_DEFAULT_STRATEGY);
}
else {
temp = get_space(&out_pool);
temp->len = 0;
}
/* set dictionary if provided, release that input or dictionary buffer
(not NULL if g.setdict is true and if this is not the first work
unit) */
if (job->out != NULL) {
len = job->out->len;
left = len < DICT ? len : DICT;
if (g.level <= 9)
deflateSetDictionary(&strm, job->out->buf + (len - left),
left);
else {
memcpy(temp->buf, job->out->buf + (len - left), left);
temp->len = left;
}
drop_space(job->out);
}
/* set up input and output */
job->out = get_space(&out_pool);
if (g.level <= 9) {
strm.next_in = job->in->buf;
strm.next_out = job->out->buf;
}
else
memcpy(temp->buf + temp->len, job->in->buf, job->in->len);
/* compress each block, either flushing or finishing */
next = job->lens == NULL ? NULL : job->lens->buf;
left = job->in->len;
job->out->len = 0;
do {
/* decode next block length from blocks list */
len = next == NULL ? 128 : *next++;
if (len < 128) /* 64..32831 */
len = (len << 8) + (*next++) + 64;
else if (len == 128) /* end of list */
len = left;
else if (len < 192) /* 1..63 */
len &= 0x3f;
else if (len < 224){ /* 32832..2129983 */
len = ((len & 0x1f) << 16) + (*next++ << 8);
len += *next++ + 32832U;
}
else { /* 2129984..539000895 */
len = ((len & 0x1f) << 24) + (*next++ << 16);
len += *next++ << 8;
len += *next++ + 2129984UL;
}
left -= len;
if (g.level <= 9) {
/* run MAXP2-sized amounts of input through deflate -- this
loop is needed for those cases where the unsigned type is
smaller than the size_t type, or when len is close to the
limit of the size_t type */
while (len > MAXP2) {
strm.avail_in = MAXP2;
deflate_engine(&strm, job->out, Z_NO_FLUSH);
len -= MAXP2;
}
/* run the last piece through deflate -- end on a byte
boundary, using a sync marker if necessary, or finish the
deflate stream if this is the last block */
strm.avail_in = (unsigned)len;
if (left || job->more) {
#if ZLIB_VERNUM >= 0x1260
deflate_engine(&strm, job->out, Z_BLOCK);
/* add enough empty blocks to get to a byte boundary */
(void)deflatePending(&strm, Z_NULL, &bits);
if (bits & 1)
deflate_engine(&strm, job->out, Z_SYNC_FLUSH);
else if (bits & 7) {
do { /* add static empty blocks */
bits = deflatePrime(&strm, 10, 2);
assert(bits == Z_OK);
(void)deflatePending(&strm, Z_NULL, &bits);
} while (bits & 7);
deflate_engine(&strm, job->out, Z_BLOCK);
}
#else
deflate_engine(&strm, job->out, Z_SYNC_FLUSH);
#endif
}
else
deflate_engine(&strm, job->out, Z_FINISH);
}
else {
/* compress len bytes using zopfli, bring to byte boundary */
unsigned char bits, *out;
size_t outsize;
out = NULL;
outsize = 0;
bits = 0;
ZopfliDeflatePart(&g.zopts, 2, !(left || job->more),
temp->buf, temp->len, temp->len + len,
&bits, &out, &outsize);
assert(job->out->len + outsize + 5 <= job->out->size);
memcpy(job->out->buf + job->out->len, out, outsize);
free(out);
job->out->len += outsize;
if (left || job->more) {
bits &= 7;
if (bits & 1) {
if (bits == 7)
job->out->buf[job->out->len++] = 0;
job->out->buf[job->out->len++] = 0;
job->out->buf[job->out->len++] = 0;
job->out->buf[job->out->len++] = 0xff;
job->out->buf[job->out->len++] = 0xff;
}
else if (bits) {
do {
job->out->buf[job->out->len - 1] += 2 << bits;
job->out->buf[job->out->len++] = 0;
bits += 2;
} while (bits < 8);
}
}
temp->len += len;
}
} while (left);
if (g.level > 9)
drop_space(temp);
if (job->lens != NULL) {
drop_space(job->lens);
job->lens = NULL;
}
Trace(("-- compressed #%ld%s", job->seq, job->more ? "" : " (last)"));
/* reserve input buffer until check value has been calculated */
use_space(job->in);
/* insert write job in list in sorted order, alert write thread */
possess(write_first);
prior = &write_head;
while ((here = *prior) != NULL) {
if (here->seq > job->seq)
break;
prior = &(here->next);
}
job->next = here;
*prior = job;
twist(write_first, TO, write_head->seq);
/* calculate the check value in parallel with writing, alert the write
thread that the calculation is complete, and drop this usage of the
input buffer */
len = job->in->len;
next = job->in->buf;
check = CHECK(0L, Z_NULL, 0);
while (len > MAXP2) {
check = CHECK(check, next, MAXP2);
len -= MAXP2;
next += MAXP2;
}
check = CHECK(check, next, (unsigned)len);
drop_space(job->in);
job->check = check;
Trace(("-- checked #%ld%s", job->seq, job->more ? "" : " (last)"));
possess(job->calc);
twist(job->calc, TO, 1);
/* done with that one -- go find another job */
}
/* found job with seq == -1 -- free deflate memory and return to join */
release(compress_have);
(void)deflateEnd(&strm);
}
/* collect the write jobs off of the list in sequence order and write out the
compressed data until the last chunk is written -- also write the header and
trailer and combine the individual check values of the input buffers */
local void write_thread(void *dummy)
{
long seq; /* next sequence number looking for */
struct job *job; /* job pulled and working on */
size_t len; /* input length */
int more; /* true if more chunks to write */
unsigned long head; /* header length */
unsigned long ulen; /* total uncompressed size (overflow ok) */
unsigned long clen; /* total compressed size (overflow ok) */
unsigned long check; /* check value of uncompressed data */
(void)dummy;
/* build and write header */
Trace(("-- write thread running"));
head = put_header();
/* process output of compress threads until end of input */
ulen = clen = 0;
check = CHECK(0L, Z_NULL, 0);
seq = 0;
do {
/* get next write job in order */
possess(write_first);
wait_for(write_first, TO_BE, seq);
job = write_head;
write_head = job->next;
twist(write_first, TO, write_head == NULL ? -1 : write_head->seq);
/* update lengths, save uncompressed length for COMB */
more = job->more;
len = job->in->len;
drop_space(job->in);
ulen += (unsigned long)len;
clen += (unsigned long)(job->out->len);
/* write the compressed data and drop the output buffer */
Trace(("-- writing #%ld", seq));
writen(g.outd, job->out->buf, job->out->len);
drop_space(job->out);
Trace(("-- wrote #%ld%s", seq, more ? "" : " (last)"));
/* wait for check calculation to complete, then combine, once
the compress thread is done with the input, release it */
possess(job->calc);
wait_for(job->calc, TO_BE, 1);
release(job->calc);
check = COMB(check, job->check, len);
/* free the job */
free_lock(job->calc);
FREE(job);
/* get the next buffer in sequence */
seq++;
} while (more);
/* write trailer */
put_trailer(ulen, clen, check, head);
/* verify no more jobs, prepare for next use */
possess(compress_have);
assert(compress_head == NULL && peek_lock(compress_have) == 0);
release(compress_have);
possess(write_first);
assert(write_head == NULL);
twist(write_first, TO, -1);
}
/* encode a hash hit to the block lengths list -- hit == 0 ends the list */
local void append_len(struct job *job, size_t len)
{
struct space *lens;
assert(len < 539000896UL);
if (job->lens == NULL)
job->lens = get_space(&lens_pool);
lens = job->lens;
if (lens->size < lens->len + 3)
grow_space(lens);
if (len < 64)
lens->buf[lens->len++] = len + 128;
else if (len < 32832U) {
len -= 64;
lens->buf[lens->len++] = len >> 8;
lens->buf[lens->len++] = len;
}
else if (len < 2129984UL) {
len -= 32832U;
lens->buf[lens->len++] = (len >> 16) + 192;
lens->buf[lens->len++] = len >> 8;
lens->buf[lens->len++] = len;
}
else {
len -= 2129984UL;
lens->buf[lens->len++] = (len >> 24) + 224;
lens->buf[lens->len++] = len >> 16;
lens->buf[lens->len++] = len >> 8;
lens->buf[lens->len++] = len;
}
}
/* compress ind to outd, using multiple threads for the compression and check
value calculations and one other thread for writing the output -- compress
threads will be launched and left running (waiting actually) to support
subsequent calls of parallel_compress() */
local void parallel_compress(void)
{
long seq; /* sequence number */
struct space *curr; /* input data to compress */
struct space *next; /* input data that follows curr */
struct space *hold; /* input data that follows next */
struct space *dict; /* dictionary for next compression */
struct job *job; /* job for compress, then write */
int more; /* true if more input to read */
unsigned hash; /* hash for rsyncable */
unsigned char *scan; /* next byte to compute hash on */
unsigned char *end; /* after end of data to compute hash on */
unsigned char *last; /* position after last hit */
size_t left; /* last hit in curr to end of curr */
size_t len; /* for various length computations */
/* if first time or after an option change, setup the job lists */
setup_jobs();
/* start write thread */
writeth = launch(write_thread, NULL);
/* read from input and start compress threads (write thread will pick up
the output of the compress threads) */
seq = 0;
next = get_space(&in_pool);
next->len = readn(g.ind, next->buf, next->size);
hold = NULL;
dict = NULL;
scan = next->buf;
hash = RSYNCHIT;
left = 0;
do {
/* create a new job */
job = MALLOC(sizeof(struct job));
if (job == NULL)
bail("not enough memory", "");
job->calc = new_lock(0);
/* update input spaces */
curr = next;
next = hold;
hold = NULL;
/* get more input if we don't already have some */
if (next == NULL) {
next = get_space(&in_pool);
next->len = readn(g.ind, next->buf, next->size);
}
/* if rsyncable, generate block lengths and prepare curr for job to
likely have less than size bytes (up to the last hash hit) */
job->lens = NULL;
if (g.rsync && curr->len) {
/* compute the hash function starting where we last left off to
cover either size bytes or to EOF, whichever is less, through
the data in curr (and in the next loop, through next) -- save
the block lengths resulting from the hash hits in the job->lens
list */
if (left == 0) {
/* scan is in curr */
last = curr->buf;
end = curr->buf + curr->len;
while (scan < end) {
hash = ((hash << 1) ^ *scan++) & RSYNCMASK;
if (hash == RSYNCHIT) {
len = scan - last;
append_len(job, len);
last = scan;
}
}
/* continue scan in next */
left = scan - last;
scan = next->buf;
}
/* scan in next for enough bytes to fill curr, or what is available
in next, whichever is less (if next isn't full, then we're at
the end of the file) -- the bytes in curr since the last hit,
stored in left, counts towards the size of the first block */
last = next->buf;
len = curr->size - curr->len;
if (len > next->len)
len = next->len;
end = next->buf + len;
while (scan < end) {
hash = ((hash << 1) ^ *scan++) & RSYNCMASK;
if (hash == RSYNCHIT) {
len = (scan - last) + left;
left = 0;
append_len(job, len);
last = scan;
}
}
append_len(job, 0);
/* create input in curr for job up to last hit or entire buffer if
no hits at all -- save remainder in next and possibly hold */
len = (job->lens->len == 1 ? scan : last) - next->buf;
if (len) {
/* got hits in next, or no hits in either -- copy to curr */
memcpy(curr->buf + curr->len, next->buf, len);
curr->len += len;
memmove(next->buf, next->buf + len, next->len - len);
next->len -= len;
scan -= len;
left = 0;
}
else if (job->lens->len != 1 && left && next->len) {
/* had hits in curr, but none in next, and last hit in curr
wasn't right at the end, so we have input there to save --
use curr up to the last hit, save the rest, moving next to
hold */
hold = next;
next = get_space(&in_pool);
memcpy(next->buf, curr->buf + (curr->len - left), left);
next->len = left;
curr->len -= left;
}
else {
/* else, last match happened to be right at the end of curr,
or we're at the end of the input compressing the rest */
left = 0;
}
}
/* compress curr->buf to curr->len -- compress thread will drop curr */
job->in = curr;
/* set job->more if there is more to compress after curr */
more = next->len != 0;
job->more = more;
/* provide dictionary for this job, prepare dictionary for next job */
job->out = dict;
if (more && g.setdict) {
if (curr->len >= DICT || job->out == NULL) {
dict = curr;
use_space(dict);
}
else {
dict = get_space(&dict_pool);
len = DICT - curr->len;
memcpy(dict->buf, job->out->buf + (job->out->len - len), len);
memcpy(dict->buf + len, curr->buf, curr->len);
dict->len = DICT;
}
}
/* preparation of job is complete */
job->seq = seq;
Trace(("-- read #%ld%s", seq, more ? "" : " (last)"));
if (++seq < 1)
bail("input too long: ", g.inf);
/* start another compress thread if needed */
if (cthreads < seq && cthreads < g.procs) {
(void)launch(compress_thread, NULL);
cthreads++;
}
/* put job at end of compress list, let all the compressors know */
possess(compress_have);
job->next = NULL;
*compress_tail = job;
compress_tail = &(job->next);
twist(compress_have, BY, +1);
} while (more);
drop_space(next);
/* wait for the write thread to complete (we leave the compress threads out
there and waiting in case there is another stream to compress) */
join(writeth);
writeth = NULL;
Trace(("-- write thread joined"));
}
#endif
/* repeated code in single_compress to compress available input and write it */
#define DEFLATE_WRITE(flush) \
do { \
do { \
strm->avail_out = out_size; \
strm->next_out = out; \
(void)deflate(strm, flush); \
writen(g.outd, out, out_size - strm->avail_out); \
clen += out_size - strm->avail_out; \
} while (strm->avail_out == 0); \
assert(strm->avail_in == 0); \
} while (0)
/* do a simple compression in a single thread from ind to outd -- if reset is
true, instead free the memory that was allocated and retained for input,
output, and deflate */
local void single_compress(int reset)
{
size_t got; /* amount of data in in[] */
size_t more; /* amount of data in next[] (0 if eof) */
size_t start; /* start of data in next[] */
size_t have; /* bytes in current block for -i */
size_t hist; /* offset of permitted history */
int fresh; /* if true, reset compression history */
unsigned hash; /* hash for rsyncable */
unsigned char *scan; /* pointer for hash computation */
size_t left; /* bytes left to compress after hash hit */
unsigned long head; /* header length */
unsigned long ulen; /* total uncompressed size (overflow ok) */
unsigned long clen; /* total compressed size (overflow ok) */
unsigned long check; /* check value of uncompressed data */
static unsigned out_size; /* size of output buffer */
static unsigned char *in, *next, *out; /* reused i/o buffers */
static z_stream *strm = NULL; /* reused deflate structure */
/* if requested, just release the allocations and return */
if (reset) {
if (strm != NULL) {
(void)deflateEnd(strm);
FREE(strm);
FREE(out);
FREE(next);
FREE(in);
strm = NULL;
}
return;
}
/* initialize the deflate structure if this is the first time */
if (strm == NULL) {
out_size = g.block > MAXP2 ? MAXP2 : (unsigned)g.block;
if ((in = MALLOC(g.block + DICT)) == NULL ||
(next = MALLOC(g.block + DICT)) == NULL ||
(out = MALLOC(out_size)) == NULL ||
(strm = MALLOC(sizeof(z_stream))) == NULL)
bail("not enough memory", "");
strm->zfree = ZFREE;
strm->zalloc = ZALLOC;
strm->opaque = OPAQUE;
if (deflateInit2(strm, 6, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) !=
Z_OK)
bail("not enough memory", "");
}
/* write header */
head = put_header();
/* set compression level in case it changed */
if (g.level <= 9) {
(void)deflateReset(strm);
(void)deflateParams(strm, g.level, Z_DEFAULT_STRATEGY);
}
/* do raw deflate and calculate check value */
got = 0;
more = readn(g.ind, next, g.block);
ulen = (unsigned long)more;
start = 0;
hist = 0;
clen = 0;
have = 0;
check = CHECK(0L, Z_NULL, 0);
hash = RSYNCHIT;
do {
/* get data to compress, see if there is any more input */
if (got == 0) {
scan = in; in = next; next = scan;
strm->next_in = in + start;
got = more;
if (g.level > 9) {
left = start + more - hist;
if (left > DICT)
left = DICT;
memcpy(next, in + ((start + more) - left), left);
start = left;
hist = 0;
}
else
start = 0;
more = readn(g.ind, next + start, g.block);
ulen += (unsigned long)more;
}
/* if rsyncable, compute hash until a hit or the end of the block */
left = 0;
if (g.rsync && got) {
scan = strm->next_in;
left = got;
do {
if (left == 0) {
/* went to the end -- if no more or no hit in size bytes,
then proceed to do a flush or finish with got bytes */
if (more == 0 || got == g.block)
break;
/* fill in[] with what's left there and as much as possible
from next[] -- set up to continue hash hit search */
if (g.level > 9) {
left = (strm->next_in - in) - hist;
if (left > DICT)
left = DICT;
}
memmove(in, strm->next_in - left, left + got);
hist = 0;
strm->next_in = in + left;
scan = in + left + got;
left = more > g.block - got ? g.block - got : more;
memcpy(scan, next + start, left);
got += left;
more -= left;
start += left;
/* if that emptied the next buffer, try to refill it */
if (more == 0) {
more = readn(g.ind, next, g.block);
ulen += (unsigned long)more;
start = 0;
}
}
left--;
hash = ((hash << 1) ^ *scan++) & RSYNCMASK;
} while (hash != RSYNCHIT);
got -= left;
}
/* clear history for --independent option */
fresh = 0;
if (!g.setdict) {
have += got;
if (have > g.block) {
fresh = 1;
have = got;
}
}
if (g.level <= 9) {
/* clear history if requested */
if (fresh)
(void)deflateReset(strm);
/* compress MAXP2-size chunks in case unsigned type is small */
while (got > MAXP2) {
strm->avail_in = MAXP2;
check = CHECK(check, strm->next_in, strm->avail_in);
DEFLATE_WRITE(Z_NO_FLUSH);
got -= MAXP2;
}
/* compress the remainder, emit a block, finish if end of input */
strm->avail_in = (unsigned)got;
got = left;
check = CHECK(check, strm->next_in, strm->avail_in);
if (more || got) {
#if ZLIB_VERNUM >= 0x1260
int bits;
DEFLATE_WRITE(Z_BLOCK);
(void)deflatePending(strm, Z_NULL, &bits);
if (bits & 1)
DEFLATE_WRITE(Z_SYNC_FLUSH);
else if (bits & 7) {
do {
bits = deflatePrime(strm, 10, 2);
assert(bits == Z_OK);
(void)deflatePending(strm, Z_NULL, &bits);
} while (bits & 7);
DEFLATE_WRITE(Z_NO_FLUSH);
}
#else
DEFLATE_WRITE(Z_SYNC_FLUSH);
#endif
}
else
DEFLATE_WRITE(Z_FINISH);
}
else {
/* compress got bytes using zopfli, bring to byte boundary */
unsigned char bits, *out;
size_t outsize, off;
/* discard history if requested */
off = strm->next_in - in;
if (fresh)
hist = off;
out = NULL;
outsize = 0;
bits = 0;
ZopfliDeflatePart(&g.zopts, 2, !(more || left),
in + hist, off - hist, (off - hist) + got,
&bits, &out, &outsize);
bits &= 7;
if ((more || left) && bits) {
if (bits & 1) {
writen(g.outd, out, outsize);
if (bits == 7)
writen(g.outd, (unsigned char *)"\0", 1);
writen(g.outd, (unsigned char *)"\0\0\xff\xff", 4);
}
else {
assert(outsize > 0);
writen(g.outd, out, outsize - 1);
do {
out[outsize - 1] += 2 << bits;
writen(g.outd, out + outsize - 1, 1);
out[outsize - 1] = 0;
bits += 2;
} while (bits < 8);
writen(g.outd, out + outsize - 1, 1);
}
}
else
writen(g.outd, out, outsize);
free(out);
while (got > MAXP2) {
check = CHECK(check, strm->next_in, MAXP2);
strm->next_in += MAXP2;
got -= MAXP2;
}
check = CHECK(check, strm->next_in, (unsigned)got);
strm->next_in += got;
got = left;
}
/* do until no more input */
} while (more || got);
/* write trailer */
put_trailer(ulen, clen, check, head);
}
/* --- decompression --- */
#ifndef NOTHREAD
/* parallel read thread */
local void load_read(void *dummy)
{
size_t len;
(void)dummy;
Trace(("-- launched decompress read thread"));
do {
possess(g.load_state);
wait_for(g.load_state, TO_BE, 1);
g.in_len = len = readn(g.ind, g.in_which ? g.in_buf : g.in_buf2, BUF);
Trace(("-- decompress read thread read %lu bytes", len));
twist(g.load_state, TO, 0);
} while (len == BUF);
Trace(("-- exited decompress read thread"));
}
#endif
/* load() is called when the input has been consumed in order to provide more
input data: load the input buffer with BUF or fewer bytes (fewer if at end
of file) from the file g.ind, set g.in_next to point to the g.in_left bytes
read, update g.in_tot, and return g.in_left -- g.in_eof is set to true when
g.in_left has gone to zero and there is no more data left to read */
local size_t load(void)
{
/* if already detected end of file, do nothing */
if (g.in_short) {
g.in_eof = 1;
g.in_left = 0;
return 0;
}
#ifndef NOTHREAD
/* if first time in or procs == 1, read a buffer to have something to
return, otherwise wait for the previous read job to complete */
if (g.procs > 1) {
/* if first time, fire up the read thread, ask for a read */
if (g.in_which == -1) {
g.in_which = 1;
g.load_state = new_lock(1);
g.load_thread = launch(load_read, NULL);
}
/* wait for the previously requested read to complete */
possess(g.load_state);
wait_for(g.load_state, TO_BE, 0);
release(g.load_state);
/* set up input buffer with the data just read */
g.in_next = g.in_which ? g.in_buf : g.in_buf2;
g.in_left = g.in_len;
/* if not at end of file, alert read thread to load next buffer,
alternate between g.in_buf and g.in_buf2 */
if (g.in_len == BUF) {
g.in_which = 1 - g.in_which;
possess(g.load_state);
twist(g.load_state, TO, 1);
}
/* at end of file -- join read thread (already exited), clean up */
else {
join(g.load_thread);
free_lock(g.load_state);
g.in_which = -1;
}
}
else
#endif
{
/* don't use threads -- simply read a buffer into g.in_buf */
g.in_left = readn(g.ind, g.in_next = g.in_buf, BUF);
}
/* note end of file */
if (g.in_left < BUF) {
g.in_short = 1;
/* if we got bupkis, now is the time to mark eof */
if (g.in_left == 0)
g.in_eof = 1;
}
/* update the total and return the available bytes */
g.in_tot += g.in_left;
return g.in_left;
}
/* initialize for reading new input */
local void in_init(void)
{
g.in_left = 0;
g.in_eof = 0;
g.in_short = 0;
g.in_tot = 0;
#ifndef NOTHREAD
g.in_which = -1;
#endif
}
/* buffered reading macros for decompression and listing */
#define GET() (g.in_left == 0 && (g.in_eof || load() == 0) ? 0 : \
(g.in_left--, *g.in_next++))
#define GET2() (tmp2 = GET(), tmp2 + ((unsigned)(GET()) << 8))
#define GET4() (tmp4 = GET2(), tmp4 + ((unsigned long)(GET2()) << 16))
#define SKIP(dist) \
do { \
size_t togo = (dist); \
while (togo > g.in_left) { \
togo -= g.in_left; \
if (load() == 0) \
return -1; \
} \
g.in_left -= togo; \
g.in_next += togo; \
} while (0)
/* pull LSB order or MSB order integers from an unsigned char buffer */
#define PULL2L(p) ((p)[0] + ((unsigned)((p)[1]) << 8))
#define PULL4L(p) (PULL2L(p) + ((unsigned long)(PULL2L((p) + 2)) << 16))
#define PULL2M(p) (((unsigned)((p)[0]) << 8) + (p)[1])
#define PULL4M(p) (((unsigned long)(PULL2M(p)) << 16) + PULL2M((p) + 2))
/* convert MS-DOS date and time to a Unix time, assuming current timezone
(you got a better idea?) */
local time_t dos2time(unsigned long dos)
{
struct tm tm;
if (dos == 0)
return time(NULL);
tm.tm_year = ((int)(dos >> 25) & 0x7f) + 80;
tm.tm_mon = ((int)(dos >> 21) & 0xf) - 1;
tm.tm_mday = (int)(dos >> 16) & 0x1f;
tm.tm_hour = (int)(dos >> 11) & 0x1f;
tm.tm_min = (int)(dos >> 5) & 0x3f;
tm.tm_sec = (int)(dos << 1) & 0x3e;
tm.tm_isdst = -1; /* figure out if DST or not */
return mktime(&tm);
}
/* convert an unsigned 32-bit integer to signed, even if long > 32 bits */
local long tolong(unsigned long val)
{
return (long)(val & 0x7fffffffUL) - (long)(val & 0x80000000UL);
}
#define LOW32 0xffffffffUL
/* process zip extra field to extract zip64 lengths and Unix mod time */
local int read_extra(unsigned len, int save)
{
unsigned id, size, tmp2;
unsigned long tmp4;
/* process extra blocks */
while (len >= 4) {
id = GET2();
size = GET2();
if (g.in_eof)
return -1;
len -= 4;
if (size > len)
break;
len -= size;
if (id == 0x0001) {
/* Zip64 Extended Information Extra Field */
if (g.zip_ulen == LOW32 && size >= 8) {
g.zip_ulen = GET4();
SKIP(4);
size -= 8;
}
if (g.zip_clen == LOW32 && size >= 8) {
g.zip_clen = GET4();
SKIP(4);
size -= 8;
}
}
if (save) {
if ((id == 0x000d || id == 0x5855) && size >= 8) {
/* PKWare Unix or Info-ZIP Type 1 Unix block */
SKIP(4);
g.stamp = tolong(GET4());
size -= 8;
}
if (id == 0x5455 && size >= 5) {
/* Extended Timestamp block */
size--;
if (GET() & 1) {
g.stamp = tolong(GET4());
size -= 4;
}
}
}
SKIP(size);
}
SKIP(len);
return 0;
}
/* read a gzip, zip, zlib, or lzw header from ind and return the method in the
range 0..256 (256 implies a zip method greater than 255), or on error return
negative: -1 is immediate EOF, -2 is not a recognized compressed format, -3
is premature EOF within the header, -4 is unexpected header flag values, -5
is the zip central directory; a method of 257 is lzw -- if the return value
is not negative, then get_header() sets g.form to indicate gzip (0), zlib
(1), or zip (2, or 3 if the entry is followed by a data descriptor) */
local int get_header(int save)
{
unsigned magic; /* magic header */
int method; /* compression method */
int flags; /* header flags */
unsigned fname, extra; /* name and extra field lengths */
unsigned tmp2; /* for macro */
unsigned long tmp4; /* for macro */
/* clear return information */
if (save) {
g.stamp = 0;
RELEASE(g.hname);
}
/* see if it's a gzip, zlib, or lzw file */
g.form = -1;
g.magic1 = GET();
if (g.in_eof)
return -1;
magic = g.magic1 << 8;
magic += GET();
if (g.in_eof)
return -2;
if (magic % 31 == 0) { /* it's zlib */
g.form = 1;
return (int)((magic >> 8) & 0xf);
}
if (magic == 0x1f9d) /* it's lzw */
return 257;
if (magic == 0x504b) { /* it's zip */
magic = GET2(); /* the rest of the signature */
if (g.in_eof)
return -3;
if (magic == 0x0201 || magic == 0x0806)
return -5; /* central header or archive extra */
if (magic != 0x0403)
return -4; /* not a local header */
SKIP(2);
flags = GET2();
if (g.in_eof)
return -3;
if (flags & 0xfff0)
return -4;
method = GET(); /* return low byte of method or 256 */
if (GET() != 0 || flags & 1)
method = 256; /* unknown or encrypted */
if (g.in_eof)
return -3;
if (save)
g.stamp = dos2time(GET4());
else
SKIP(4);
g.zip_crc = GET4();
g.zip_clen = GET4();
g.zip_ulen = GET4();
fname = GET2();
extra = GET2();
if (save) {
char *next = g.hname = MALLOC(fname + 1);
if (g.hname == NULL)
bail("not enough memory", "");
while (fname > g.in_left) {
memcpy(next, g.in_next, g.in_left);
fname -= g.in_left;
next += g.in_left;
if (load() == 0)
return -3;
}
memcpy(next, g.in_next, fname);
g.in_left -= fname;
g.in_next += fname;
next += fname;
*next = 0;
}
else
SKIP(fname);
read_extra(extra, save);
g.form = 2 + ((flags & 8) >> 3);
return g.in_eof ? -3 : method;
}
if (magic != 0x1f8b) { /* not gzip */
g.in_left++; /* unget second magic byte */
g.in_next--;
return -2;
}
/* it's gzip -- get method and flags */
method = GET();
flags = GET();
if (g.in_eof)
return -1;
if (flags & 0xe0)
return -4;
/* get time stamp */
if (save)
g.stamp = tolong(GET4());
else
SKIP(4);
/* skip extra field and OS */
SKIP(2);
/* skip extra field, if present */
if (flags & 4) {
extra = GET2();
if (g.in_eof)
return -3;
SKIP(extra);
}
/* read file name, if present, into allocated memory */
if ((flags & 8) && save) {
unsigned char *end;
size_t copy, have, size = 128;
g.hname = MALLOC(size);
if (g.hname == NULL)
bail("not enough memory", "");
have = 0;
do {
if (g.in_left == 0 && load() == 0)
return -3;
end = memchr(g.in_next, 0, g.in_left);
copy = end == NULL ? g.in_left : (size_t)(end - g.in_next) + 1;
if (have + copy > size) {
while (have + copy > (size <<= 1))
;
g.hname = REALLOC(g.hname, size);
if (g.hname == NULL)
bail("not enough memory", "");
}
memcpy(g.hname + have, g.in_next, copy);
have += copy;
g.in_left -= copy;
g.in_next += copy;
} while (end == NULL);
}
else if (flags & 8)
while (GET() != 0)
if (g.in_eof)
return -3;
/* skip comment */
if (flags & 16)
while (GET() != 0)
if (g.in_eof)
return -3;
/* skip header crc */
if (flags & 2)
SKIP(2);
/* return gzip compression method */
g.form = 0;
return method;
}
/* --- list contents of compressed input (gzip, zlib, or lzw) */
/* find standard compressed file suffix, return length of suffix */
local size_t compressed_suffix(char *nm)
{
size_t len;
len = strlen(nm);
if (len > 4) {
nm += len - 4;
len = 4;
if (strcmp(nm, ".zip") == 0 || strcmp(nm, ".ZIP") == 0 ||
strcmp(nm, ".tgz") == 0)
return 4;
}
if (len > 3) {
nm += len - 3;
len = 3;
if (strcmp(nm, ".gz") == 0 || strcmp(nm, "-gz") == 0 ||
strcmp(nm, ".zz") == 0 || strcmp(nm, "-zz") == 0)
return 3;
}
if (len > 2) {
nm += len - 2;
if (strcmp(nm, ".z") == 0 || strcmp(nm, "-z") == 0 ||
strcmp(nm, "_z") == 0 || strcmp(nm, ".Z") == 0)
return 2;
}
return 0;
}
/* listing file name lengths for -l and -lv */
#define NAMEMAX1 48 /* name display limit at verbosity 1 */
#define NAMEMAX2 16 /* name display limit at verbosity 2 */
/* print gzip or lzw file information */
local void show_info(int method, unsigned long check, off_t len, int cont)
{
size_t max; /* maximum name length for current verbosity */
size_t n; /* name length without suffix */
time_t now; /* for getting current year */
char mod[26]; /* modification time in text */
char tag[NAMEMAX1+1]; /* header or file name, possibly truncated */
/* create abbreviated name from header file name or actual file name */
max = g.verbosity > 1 ? NAMEMAX2 : NAMEMAX1;
memset(tag, 0, max + 1);
if (cont)
strncpy(tag, "<...>", max + 1);
else if (g.hname == NULL) {
n = strlen(g.inf) - compressed_suffix(g.inf);
strncpy(tag, g.inf, n > max + 1 ? max + 1 : n);
if (strcmp(g.inf + n, ".tgz") == 0 && n < max + 1)
strncpy(tag + n, ".tar", max + 1 - n);
}
else
strncpy(tag, g.hname, max + 1);
if (tag[max])
strcpy(tag + max - 3, "...");
/* convert time stamp to text */
if (g.stamp) {
strcpy(mod, ctime(&g.stamp));
now = time(NULL);
if (strcmp(mod + 20, ctime(&now) + 20) != 0)
strcpy(mod + 11, mod + 19);
}
else
strcpy(mod + 4, "------ -----");
mod[16] = 0;
/* if first time, print header */
if (g.first) {
if (g.verbosity > 1)
fputs("method check timestamp ", stdout);
if (g.verbosity > 0)
puts("compressed original reduced name");
g.first = 0;
}
/* print information */
if (g.verbosity > 1) {
if (g.form == 3 && !g.decode)
printf("zip%3d -------- %s ", method, mod + 4);
else if (g.form > 1)
printf("zip%3d %08lx %s ", method, check, mod + 4);
else if (g.form == 1)
printf("zlib%2d %08lx %s ", method, check, mod + 4);
else if (method == 257)
printf("lzw -------- %s ", mod + 4);
else
printf("gzip%2d %08lx %s ", method, check, mod + 4);
}
if (g.verbosity > 0) {
if ((g.form == 3 && !g.decode) ||
(method == 8 && g.in_tot > (len + (len >> 10) + 12)) ||
(method == 257 && g.in_tot > len + (len >> 1) + 3))
#if __STDC_VERSION__-0 >= 199901L || __GNUC__-0 >= 3
printf("%10jd %10jd? unk %s\n",
(intmax_t)g.in_tot, (intmax_t)len, tag);
else
printf("%10jd %10jd %6.1f%% %s\n",
(intmax_t)g.in_tot, (intmax_t)len,
len == 0 ? 0 : 100 * (len - g.in_tot)/(double)len,
tag);
#else
printf(sizeof(off_t) == sizeof(long) ?
"%10ld %10ld? unk %s\n" : "%10lld %10lld? unk %s\n",
g.in_tot, len, tag);
else
printf(sizeof(off_t) == sizeof(long) ?
"%10ld %10ld %6.1f%% %s\n" : "%10lld %10lld %6.1f%% %s\n",
g.in_tot, len,
len == 0 ? 0 : 100 * (len - g.in_tot)/(double)len,
tag);
#endif
}
}
/* list content information about the gzip file at ind (only works if the gzip
file contains a single gzip stream with no junk at the end, and only works
well if the uncompressed length is less than 4 GB) */
local void list_info(void)
{
int method; /* get_header() return value */
size_t n; /* available trailer bytes */
off_t at; /* used to calculate compressed length */
unsigned char tail[8]; /* trailer containing check and length */
unsigned long check, len; /* check value and length from trailer */
/* initialize input buffer */
in_init();
/* read header information and position input after header */
method = get_header(1);
if (method < 0) {
RELEASE(g.hname);
if (method != -1 && g.verbosity > 1)
complain("%s not a compressed file -- skipping", g.inf);
return;
}
/* list zip file */
if (g.form > 1) {
g.in_tot = g.zip_clen;
show_info(method, g.zip_crc, g.zip_ulen, 0);
return;
}
/* list zlib file */
if (g.form == 1) {
at = lseek(g.ind, 0, SEEK_END);
if (at == -1) {
check = 0;
do {
len = g.in_left < 4 ? g.in_left : 4;
g.in_next += g.in_left - len;
while (len--)
check = (check << 8) + *g.in_next++;
} while (load() != 0);
check &= LOW32;
}
else {
g.in_tot = at;
lseek(g.ind, -4, SEEK_END);
readn(g.ind, tail, 4);
check = PULL4M(tail);
}
g.in_tot -= 6;
show_info(method, check, 0, 0);
return;
}
/* list lzw file */
if (method == 257) {
at = lseek(g.ind, 0, SEEK_END);
if (at == -1)
while (load() != 0)
;
else
g.in_tot = at;
g.in_tot -= 3;
show_info(method, 0, 0, 0);
return;
}
/* skip to end to get trailer (8 bytes), compute compressed length */
if (g.in_short) { /* whole thing already read */
if (g.in_left < 8) {
complain("%s not a valid gzip file -- skipping", g.inf);
return;
}
g.in_tot = g.in_left - 8; /* compressed size */
memcpy(tail, g.in_next + (g.in_left - 8), 8);
}
else if ((at = lseek(g.ind, -8, SEEK_END)) != -1) {
g.in_tot = at - g.in_tot + g.in_left; /* compressed size */
readn(g.ind, tail, 8); /* get trailer */
}
else { /* can't seek */
at = g.in_tot - g.in_left; /* save header size */
do {
n = g.in_left < 8 ? g.in_left : 8;
memcpy(tail, g.in_next + (g.in_left - n), n);
load();
} while (g.in_left == BUF); /* read until end */
if (g.in_left < 8) {
if (n + g.in_left < 8) {
complain("%s not a valid gzip file -- skipping", g.inf);
return;
}
if (g.in_left) {
if (n + g.in_left > 8)
memcpy(tail, tail + n - (8 - g.in_left), 8 - g.in_left);
memcpy(tail + 8 - g.in_left, g.in_next, g.in_left);
}
}
else
memcpy(tail, g.in_next + (g.in_left - 8), 8);
g.in_tot -= at + 8;
}
if (g.in_tot < 2) {
complain("%s not a valid gzip file -- skipping", g.inf);
return;
}
/* convert trailer to check and uncompressed length (modulo 2^32) */
check = PULL4L(tail);
len = PULL4L(tail + 4);
/* list information about contents */
show_info(method, check, len, 0);
RELEASE(g.hname);
}
/* --- copy input to output (when acting like cat) --- */
local void cat(void)
{
/* write first magic byte (if we're here, there's at least one byte) */
writen(g.outd, &g.magic1, 1);
g.out_tot = 1;
/* copy the remainder of the input to the output (if there were any more
bytes of input, then g.in_left is non-zero and g.in_next is pointing to
the second magic byte) */
while (g.in_left) {
writen(g.outd, g.in_next, g.in_left);
g.out_tot += g.in_left;
g.in_left = 0;
load();
}
}
/* --- decompress deflate input --- */
/* call-back input function for inflateBack() */
local unsigned inb(void *desc, unsigned char **buf)
{
(void)desc;
load();
*buf = g.in_next;
return g.in_left;
}
/* output buffers and window for infchk() and unlzw() */
#define OUTSIZE 32768U /* must be at least 32K for inflateBack() window */
local unsigned char out_buf[OUTSIZE];
#ifndef NOTHREAD
/* output data for parallel write and check */
local unsigned char out_copy[OUTSIZE];
local size_t out_len;
/* outb threads states */
local lock *outb_write_more = NULL;
local lock *outb_check_more;
/* output write thread */
local void outb_write(void *dummy)
{
size_t len;
(void)dummy;
Trace(("-- launched decompress write thread"));
do {
possess(outb_write_more);
wait_for(outb_write_more, TO_BE, 1);
len = out_len;
if (len && g.decode == 1)
writen(g.outd, out_copy, len);
Trace(("-- decompress wrote %lu bytes", len));
twist(outb_write_more, TO, 0);
} while (len);
Trace(("-- exited decompress write thread"));
}
/* output check thread */
local void outb_check(void *dummy)
{
size_t len;
(void)dummy;
Trace(("-- launched decompress check thread"));
do {
possess(outb_check_more);
wait_for(outb_check_more, TO_BE, 1);
len = out_len;
g.out_check = CHECK(g.out_check, out_copy, len);
Trace(("-- decompress checked %lu bytes", len));
twist(outb_check_more, TO, 0);
} while (len);
Trace(("-- exited decompress check thread"));
}
#endif
/* call-back output function for inflateBack() -- wait for the last write and
check calculation to complete, copy the write buffer, and then alert the
write and check threads and return for more decompression while that's
going on (or just write and check if no threads or if proc == 1) */
local int outb(void *desc, unsigned char *buf, unsigned len)
{
#ifndef NOTHREAD
static thread *wr, *ch;
if (g.procs > 1) {
/* if first time, initialize state and launch threads */
if (outb_write_more == NULL) {
outb_write_more = new_lock(0);
outb_check_more = new_lock(0);
wr = launch(outb_write, NULL);
ch = launch(outb_check, NULL);
}
/* wait for previous write and check threads to complete */
possess(outb_check_more);
wait_for(outb_check_more, TO_BE, 0);
possess(outb_write_more);
wait_for(outb_write_more, TO_BE, 0);
/* copy the output and alert the worker bees */
out_len = len;
g.out_tot += len;
memcpy(out_copy, buf, len);
twist(outb_write_more, TO, 1);
twist(outb_check_more, TO, 1);
/* if requested with len == 0, clean up -- terminate and join write and
check threads, free lock */
if (len == 0) {
join(ch);
join(wr);
free_lock(outb_check_more);
free_lock(outb_write_more);
outb_write_more = NULL;
}
/* return for more decompression while last buffer is being written
and having its check value calculated -- we wait for those to finish
the next time this function is called */
return 0;
}
#endif
(void)desc;
/* if just one process or no threads, then do it without threads */
if (len) {
if (g.decode == 1)
writen(g.outd, buf, len);
g.out_check = CHECK(g.out_check, buf, len);
g.out_tot += len;
}
return 0;
}
/* inflate for decompression or testing -- decompress from ind to outd unless
decode != 1, in which case just test ind, and then also list if list != 0;
look for and decode multiple, concatenated gzip and/or zlib streams;
read and check the gzip, zlib, or zip trailer */
local void infchk(void)
{
int ret, cont, was;
unsigned long check, len;
z_stream strm;
unsigned tmp2;
unsigned long tmp4;
off_t clen;
cont = 0;
do {
/* header already read -- set up for decompression */
g.in_tot = g.in_left; /* track compressed data length */
g.out_tot = 0;
g.out_check = CHECK(0L, Z_NULL, 0);
strm.zalloc = ZALLOC;
strm.zfree = ZFREE;
strm.opaque = OPAQUE;
ret = inflateBackInit(&strm, 15, out_buf);
if (ret != Z_OK)
bail("not enough memory", "");
/* decompress, compute lengths and check value */
strm.avail_in = g.in_left;
strm.next_in = g.in_next;
ret = inflateBack(&strm, inb, NULL, outb, NULL);
if (ret != Z_STREAM_END)
bail("corrupted input -- invalid deflate data: ", g.inf);
g.in_left = strm.avail_in;
g.in_next = strm.next_in;
inflateBackEnd(&strm);
outb(NULL, NULL, 0); /* finish off final write and check */
/* compute compressed data length */
clen = g.in_tot - g.in_left;
/* read and check trailer */
if (g.form > 1) { /* zip local trailer (if any) */
if (g.form == 3) { /* data descriptor follows */
/* read original version of data descriptor */
g.zip_crc = GET4();
g.zip_clen = GET4();
g.zip_ulen = GET4();
if (g.in_eof)
bail("corrupted zip entry -- missing trailer: ", g.inf);
/* if crc doesn't match, try info-zip variant with sig */
if (g.zip_crc != g.out_check) {
if (g.zip_crc != 0x08074b50UL || g.zip_clen != g.out_check)
bail("corrupted zip entry -- crc32 mismatch: ", g.inf);
g.zip_crc = g.zip_clen;
g.zip_clen = g.zip_ulen;
g.zip_ulen = GET4();
}
/* handle incredibly rare cases where crc equals signature */
else if (g.zip_crc == 0x08074b50UL &&
g.zip_clen == g.zip_crc &&
((clen & LOW32) != g.zip_crc ||
g.zip_ulen == g.zip_crc)) {
g.zip_crc = g.zip_clen;
g.zip_clen = g.zip_ulen;
g.zip_ulen = GET4();
}
/* if second length doesn't match, try 64-bit lengths */
if (g.zip_ulen != (g.out_tot & LOW32)) {
g.zip_ulen = GET4();
(void)GET4();
}
if (g.in_eof)
bail("corrupted zip entry -- missing trailer: ", g.inf);
}
if (g.zip_clen != (clen & LOW32) ||
g.zip_ulen != (g.out_tot & LOW32))
bail("corrupted zip entry -- length mismatch: ", g.inf);
check = g.zip_crc;
}
else if (g.form == 1) { /* zlib (big-endian) trailer */
check = (unsigned long)(GET()) << 24;
check += (unsigned long)(GET()) << 16;
check += (unsigned)(GET()) << 8;
check += GET();
if (g.in_eof)
bail("corrupted zlib stream -- missing trailer: ", g.inf);
if (check != g.out_check)
bail("corrupted zlib stream -- adler32 mismatch: ", g.inf);
}
else { /* gzip trailer */
check = GET4();
len = GET4();
if (g.in_eof)
bail("corrupted gzip stream -- missing trailer: ", g.inf);
if (check != g.out_check)
bail("corrupted gzip stream -- crc32 mismatch: ", g.inf);
if (len != (g.out_tot & LOW32))
bail("corrupted gzip stream -- length mismatch: ", g.inf);
}
/* show file information if requested */
if (g.list) {
g.in_tot = clen;
show_info(8, check, g.out_tot, cont);
cont = 1;
}
/* if a gzip entry follows a gzip entry, decompress it (don't replace
saved header information from first entry) */
was = g.form;
} while (was == 0 && (ret = get_header(0)) == 8 && g.form == 0);
/* gzip -cdf copies junk after gzip stream directly to output */
if (was == 0 && ret == -2 && g.force && g.pipeout && g.decode != 2 &&
!g.list)
cat();
else if (was > 1 && get_header(0) != -5)
complain("entries after the first in %s were ignored", g.inf);
else if ((was == 0 && ret != -1) || (was == 1 && (GET(), !g.in_eof)))
complain("%s OK, has trailing junk which was ignored", g.inf);
}
/* --- decompress Unix compress (LZW) input --- */
/* Type for accumulating bits. 23 bits will be used to accumulate up to 16-bit
symbols. */
typedef uint_fast32_t bits_t;
#define NOMORE() (g.in_left == 0 && (g.in_eof || load() == 0))
#define NEXT() (g.in_left--, *g.in_next++)
/* Decompress a compress (LZW) file from ind to outd. The compress magic
header (two bytes) has already been read and verified. */
local void unlzw(void)
{
unsigned bits; /* current bits per code (9..16) */
unsigned mask; /* mask for current bits codes = (1<<bits)-1 */
bits_t buf; /* bit buffer (need 23 bits) */
unsigned left; /* bits left in buf (0..7 after code pulled) */
off_t mark; /* offset where last change in bits began */
unsigned code; /* code, table traversal index */
unsigned max; /* maximum bits per code for this stream */
unsigned flags; /* compress flags, then block compress flag */
unsigned end; /* last valid entry in prefix/suffix tables */
unsigned prev; /* previous code */
unsigned final; /* last character written for previous code */
unsigned stack; /* next position for reversed string */
unsigned outcnt; /* bytes in output buffer */
/* memory for unlzw() -- the first 256 entries of prefix[] and suffix[] are
never used, so could have offset the index but it's faster to waste a
little memory */
uint_least16_t prefix[65536]; /* index to LZW prefix string */
unsigned char suffix[65536]; /* one-character LZW suffix */
unsigned char match[65280 + 2]; /* buffer for reversed match */
/* process remainder of compress header -- a flags byte */
g.out_tot = 0;
if (NOMORE())
bail("lzw premature end: ", g.inf);
flags = NEXT();
if (flags & 0x60)
bail("unknown lzw flags set: ", g.inf);
max = flags & 0x1f;
if (max < 9 || max > 16)
bail("lzw bits out of range: ", g.inf);
if (max == 9) /* 9 doesn't really mean 9 */
max = 10;
flags &= 0x80; /* true if block compress */
/* mark the start of the compressed data for computing the first flush */
mark = g.in_tot - g.in_left;
/* clear table, start at nine bits per symbol */
bits = 9;
mask = 0x1ff;
end = flags ? 256 : 255;
/* set up: get first 9-bit code, which is the first decompressed byte, but
don't create a table entry until the next code */
if (NOMORE()) /* no compressed data is ok */
return;
buf = NEXT();
if (NOMORE())
bail("lzw premature end: ", g.inf); /* need at least nine bits */
buf += NEXT() << 8;
final = prev = buf & mask; /* code */
buf >>= bits;
left = 16 - bits;
if (prev > 255)
bail("invalid lzw code: ", g.inf);
out_buf[0] = final; /* write first decompressed byte */
outcnt = 1;
/* decode codes */
stack = 0;
for (;;) {
/* if the table will be full after this, increment the code size */
if (end >= mask && bits < max) {
/* flush unused input bits and bytes to next 8*bits bit boundary
(this is a vestigial aspect of the compressed data format
derived from an implementation that made use of a special VAX
machine instruction!) */
{
unsigned rem = ((g.in_tot - g.in_left) - mark) % bits;
if (rem)
rem = bits - rem;
while (rem > g.in_left) {
rem -= g.in_left;
if (load() == 0)
break;
}
g.in_left -= rem;
g.in_next += rem;
}
buf = 0;
left = 0;
/* mark this new location for computing the next flush */
mark = g.in_tot - g.in_left;
/* go to the next number of bits per symbol */
bits++;
mask <<= 1;
mask++;
}
/* get a code of bits bits */
if (NOMORE())
break; /* end of compressed data */
buf += (bits_t)(NEXT()) << left;
left += 8;
if (left < bits) {
if (NOMORE())
bail("lzw premature end: ", g.inf);
buf += (bits_t)(NEXT()) << left;
left += 8;
}
code = buf & mask;
buf >>= bits;
left -= bits;
/* process clear code (256) */
if (code == 256 && flags) {
/* flush unused input bits and bytes to next 8*bits bit boundary */
{
unsigned rem = ((g.in_tot - g.in_left) - mark) % bits;
if (rem)
rem = bits - rem;
while (rem > g.in_left) {
rem -= g.in_left;
if (load() == 0)
break;
}
g.in_left -= rem;
g.in_next += rem;
}
buf = 0;
left = 0;
/* mark this new location for computing the next flush */
mark = g.in_tot - g.in_left;
/* go back to nine bits per symbol */
bits = 9; /* initialize bits and mask */
mask = 0x1ff;
end = 255; /* empty table */
continue; /* get next code */
}
/* special code to reuse last match */
{
unsigned temp = code; /* save the current code */
if (code > end) {
/* Be picky on the allowed code here, and make sure that the
code we drop through (prev) will be a valid index so that
random input does not cause an exception. */
if (code != end + 1 || prev > end)
bail("invalid lzw code: ", g.inf);
match[stack++] = final;
code = prev;
}
/* walk through linked list to generate output in reverse order */
while (code >= 256) {
match[stack++] = suffix[code];
code = prefix[code];
}
match[stack++] = code;
final = code;
/* link new table entry */
if (end < mask) {
end++;
prefix[end] = prev;
suffix[end] = final;
}
/* set previous code for next iteration */
prev = temp;
}
/* write output in forward order */
while (stack > OUTSIZE - outcnt) {
while (outcnt < OUTSIZE)
out_buf[outcnt++] = match[--stack];
g.out_tot += outcnt;
if (g.decode == 1)
writen(g.outd, out_buf, outcnt);
outcnt = 0;
}
do {
out_buf[outcnt++] = match[--stack];
} while (stack);
}
/* write any remaining buffered output */
g.out_tot += outcnt;
if (outcnt && g.decode == 1)
writen(g.outd, out_buf, outcnt);
}
/* --- file processing --- */
/* extract file name from path */
local char *justname(char *path)
{
char *p;
p = strrchr(path, '/');
return p == NULL ? path : p + 1;
}
/* Copy file attributes, from -> to, as best we can. This is best effort, so
no errors are reported. The mode bits, including suid, sgid, and the sticky
bit are copied (if allowed), the owner's user id and group id are copied
(again if allowed), and the access and modify times are copied. */
local void copymeta(char *from, char *to)
{
struct stat st;
struct timeval times[2];
/* get all of from's Unix meta data, return if not a regular file */
if (stat(from, &st) != 0 || (st.st_mode & S_IFMT) != S_IFREG)
return;
/* set to's mode bits, ignore errors */
(void)chmod(to, st.st_mode & 07777);
/* copy owner's user and group, ignore errors */
(void)chown(to, st.st_uid, st.st_gid);
/* copy access and modify times, ignore errors */
times[0].tv_sec = st.st_atime;
times[0].tv_usec = 0;
times[1].tv_sec = st.st_mtime;
times[1].tv_usec = 0;
(void)utimes(to, times);
}
/* set the access and modify times of fd to t */
local void touch(char *path, time_t t)
{
struct timeval times[2];
times[0].tv_sec = t;
times[0].tv_usec = 0;
times[1].tv_sec = t;
times[1].tv_usec = 0;
(void)utimes(path, times);
}
/* process provided input file, or stdin if path is NULL -- process() can
call itself for recursive directory processing */
local void process(char *path)
{
int method = -1; /* get_header() return value */
size_t len; /* length of base name (minus suffix) */
struct stat st; /* to get file type and mod time */
/* all compressed suffixes for decoding search, in length order */
static char *sufs[] = {".z", "-z", "_z", ".Z", ".gz", "-gz", ".zz", "-zz",
".zip", ".ZIP", ".tgz", NULL};
/* open input file with name in, descriptor ind -- set name and mtime */
if (path == NULL) {
strcpy(g.inf, "<stdin>");
g.ind = 0;
g.name = NULL;
g.mtime = g.headis & 2 ?
(fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0;
len = 0;
}
else {
/* set input file name (already set if recursed here) */
if (path != g.inf) {
strncpy(g.inf, path, sizeof(g.inf));
if (g.inf[sizeof(g.inf) - 1])
bail("name too long: ", path);
}
len = strlen(g.inf);
/* try to stat input file -- if not there and decoding, look for that
name with compressed suffixes */
if (lstat(g.inf, &st)) {
if (errno == ENOENT && (g.list || g.decode)) {
char **try = sufs;
do {
if (*try == NULL || len + strlen(*try) >= sizeof(g.inf))
break;
strcpy(g.inf + len, *try++);
errno = 0;
} while (lstat(g.inf, &st) && errno == ENOENT);
}
#ifdef EOVERFLOW
if (errno == EOVERFLOW || errno == EFBIG)
bail(g.inf,
" too large -- not compiled with large file support");
#endif
if (errno) {
g.inf[len] = 0;
complain("%s does not exist -- skipping", g.inf);
return;
}
len = strlen(g.inf);
}
/* only process regular files, but allow symbolic links if -f,
recurse into directory if -r */
if ((st.st_mode & S_IFMT) != S_IFREG &&
(st.st_mode & S_IFMT) != S_IFLNK &&
(st.st_mode & S_IFMT) != S_IFDIR) {
complain("%s is a special file or device -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) {
complain("%s is a symbolic link -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) {
complain("%s is a directory -- skipping", g.inf);
return;
}
/* recurse into directory (assumes Unix) */
if ((st.st_mode & S_IFMT) == S_IFDIR) {
char *roll, *item, *cut, *base, *bigger;
size_t len, hold;
DIR *here;
struct dirent *next;
/* accumulate list of entries (need to do this, since readdir()
behavior not defined if directory modified between calls) */
here = opendir(g.inf);
if (here == NULL)
return;
hold = 512;
roll = MALLOC(hold);
if (roll == NULL)
bail("not enough memory", "");
*roll = 0;
item = roll;
while ((next = readdir(here)) != NULL) {
if (next->d_name[0] == 0 ||
(next->d_name[0] == '.' && (next->d_name[1] == 0 ||
(next->d_name[1] == '.' && next->d_name[2] == 0))))
continue;
len = strlen(next->d_name) + 1;
if (item + len + 1 > roll + hold) {
do { /* make roll bigger */
hold <<= 1;
} while (item + len + 1 > roll + hold);
bigger = REALLOC(roll, hold);
if (bigger == NULL) {
FREE(roll);
bail("not enough memory", "");
}
item = bigger + (item - roll);
roll = bigger;
}
strcpy(item, next->d_name);
item += len;
*item = 0;
}
closedir(here);
/* run process() for each entry in the directory */
cut = base = g.inf + strlen(g.inf);
if (base > g.inf && base[-1] != (unsigned char)'/') {
if ((size_t)(base - g.inf) >= sizeof(g.inf))
bail("path too long", g.inf);
*base++ = '/';
}
item = roll;
while (*item) {
strncpy(base, item, sizeof(g.inf) - (base - g.inf));
if (g.inf[sizeof(g.inf) - 1]) {
strcpy(g.inf + (sizeof(g.inf) - 4), "...");
bail("path too long: ", g.inf);
}
process(g.inf);
item += strlen(item) + 1;
}
*cut = 0;
/* release list of entries */
FREE(roll);
return;
}
/* don't compress .gz (or provided suffix) files, unless -f */
if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) &&
strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) {
complain("%s ends with %s -- skipping", g.inf, g.sufx);
return;
}
/* create output file only if input file has compressed suffix */
if (g.decode == 1 && !g.pipeout && !g.list) {
int suf = compressed_suffix(g.inf);
if (suf == 0) {
complain("%s does not have compressed suffix -- skipping",
g.inf);
return;
}
len -= suf;
}
/* open input file */
g.ind = open(g.inf, O_RDONLY, 0);
if (g.ind < 0)
bail("read error on ", g.inf);
/* prepare gzip header information for compression */
g.name = g.headis & 1 ? justname(g.inf) : NULL;
g.mtime = g.headis & 2 ? st.st_mtime : 0;
}
SET_BINARY_MODE(g.ind);
/* if decoding or testing, try to read gzip header */
g.hname = NULL;
if (g.decode) {
in_init();
method = get_header(1);
if (method != 8 && method != 257 &&
/* gzip -cdf acts like cat on uncompressed input */
!(method == -2 && g.force && g.pipeout && g.decode != 2 &&
!g.list)) {
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
if (method != -1)
complain(method < 0 ? "%s is not compressed -- skipping" :
"%s has unknown compression method -- skipping",
g.inf);
return;
}
/* if requested, test input file (possibly a special list) */
if (g.decode == 2) {
if (method == 8)
infchk();
else {
unlzw();
if (g.list) {
g.in_tot -= 3;
show_info(method, 0, g.out_tot, 0);
}
}
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
}
/* if requested, just list information about input file */
if (g.list) {
list_info();
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* create output file out, descriptor outd */
if (path == NULL || g.pipeout) {
/* write to stdout */
g.outf = MALLOC(strlen("<stdout>") + 1);
if (g.outf == NULL)
bail("not enough memory", "");
strcpy(g.outf, "<stdout>");
g.outd = 1;
if (!g.decode && !g.force && isatty(g.outd))
bail("trying to write compressed data to a terminal",
" (use -f to force)");
}
else {
char *to = g.inf, *sufx = "";
size_t pre = 0;
/* select parts of the output file name */
if (g.decode) {
/* for -dN or -dNT, use the path from the input file and the name
from the header, stripping any path in the header name */
if ((g.headis & 1) != 0 && g.hname != NULL) {
pre = justname(g.inf) - g.inf;
to = justname(g.hname);
len = strlen(to);
}
/* for -d or -dNn, replace abbreviated suffixes */
else if (strcmp(to + len, ".tgz") == 0)
sufx = ".tar";
}
else
/* add appropriate suffix when compressing */
sufx = g.sufx;
/* create output file and open to write */
g.outf = MALLOC(pre + len + strlen(sufx) + 1);
if (g.outf == NULL)
bail("not enough memory", "");
memcpy(g.outf, g.inf, pre);
memcpy(g.outf + pre, to, len);
strcpy(g.outf + pre + len, sufx);
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY |
(g.force ? 0 : O_EXCL), 0600);
/* if exists and not -f, give user a chance to overwrite */
if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) {
int ch, reply;
fprintf(stderr, "%s exists -- overwrite (y/n)? ", g.outf);
fflush(stderr);
reply = -1;
do {
ch = getchar();
if (reply < 0 && ch != ' ' && ch != '\t')
reply = ch == 'y' || ch == 'Y' ? 1 : 0;
} while (ch != EOF && ch != '\n' && ch != '\r');
if (reply == 1)
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY,
0600);
}
/* if exists and no overwrite, report and go on to next */
if (g.outd < 0 && errno == EEXIST) {
complain("%s exists -- skipping", g.outf);
RELEASE(g.outf);
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* if some other error, give up */
if (g.outd < 0)
bail("write error on ", g.outf);
}
SET_BINARY_MODE(g.outd);
RELEASE(g.hname);
/* process ind to outd */
if (g.verbosity > 1)
fprintf(stderr, "%s to %s ", g.inf, g.outf);
if (g.decode) {
if (method == 8)
infchk();
else if (method == 257)
unlzw();
else
cat();
}
#ifndef NOTHREAD
else if (g.procs > 1)
parallel_compress();
#endif
else
single_compress(0);
if (g.verbosity > 1) {
putc('\n', stderr);
fflush(stderr);
}
/* finish up, copy attributes, set times, delete original */
if (g.ind != 0)
close(g.ind);
if (g.outd != 1) {
if (close(g.outd))
bail("write error on ", g.outf);
g.outd = -1; /* now prevent deletion on interrupt */
if (g.ind != 0) {
copymeta(g.inf, g.outf);
if (!g.keep)
unlink(g.inf);
}
if (g.decode && (g.headis & 2) != 0 && g.stamp)
touch(g.outf, g.stamp);
}
RELEASE(g.outf);
}
local char *helptext[] = {
"Usage: pigz [options] [files ...]",
" will compress files in place, adding the suffix '.gz'. If no files are",
#ifdef NOTHREAD
" specified, stdin will be compressed to stdout. pigz does what gzip does.",
#else
" specified, stdin will be compressed to stdout. pigz does what gzip does,",
" but spreads the work over multiple processors and cores when compressing.",
#endif
"",
"Options:",
" -0 to -9, -11 Compression level (11 is much slower, a few % better)",
" --fast, --best Compression levels 1 and 9 respectively",
" -b, --blocksize mmm Set compression block size to mmmK (default 128K)",
" -c, --stdout Write all processed output to stdout (won't delete)",
" -d, --decompress Decompress the compressed input",
" -f, --force Force overwrite, compress .gz, links, and to terminal",
" -F --first Do iterations first, before block split for -11",
" -h, --help Display a help screen and quit",
" -i, --independent Compress blocks independently for damage recovery",
" -I, --iterations n Number of iterations for -11 optimization",
" -k, --keep Do not delete original file after processing",
" -K, --zip Compress to PKWare zip (.zip) single entry format",
" -l, --list List the contents of the compressed input",
" -L, --license Display the pigz license and quit",
" -M, --maxsplits n Maximum number of split blocks for -11",
" -n, --no-name Do not store or restore file name in/from header",
" -N, --name Store/restore file name and mod time in/from header",
" -O --oneblock Do not split into smaller blocks for -11",
#ifndef NOTHREAD
" -p, --processes n Allow up to n compression threads (default is the",
" number of online processors, or 8 if unknown)",
#endif
" -q, --quiet Print no messages, even on error",
" -r, --recursive Process the contents of all subdirectories",
" -R, --rsyncable Input-determined block locations for rsync",
" -S, --suffix .sss Use suffix .sss instead of .gz (for compression)",
" -t, --test Test the integrity of the compressed input",
" -T, --no-time Do not store or restore mod time in/from header",
#ifdef DEBUG
" -v, --verbose Provide more verbose output (-vv to debug)",
#else
" -v, --verbose Provide more verbose output",
#endif
" -V --version Show the version of pigz",
" -z, --zlib Compress to zlib (.zz) instead of gzip format",
" -- All arguments after \"--\" are treated as files"
};
/* display the help text above */
local void help(void)
{
int n;
if (g.verbosity == 0)
return;
for (n = 0; n < (int)(sizeof(helptext) / sizeof(char *)); n++)
fprintf(stderr, "%s\n", helptext[n]);
fflush(stderr);
exit(0);
}
#ifndef NOTHREAD
/* try to determine the number of processors */
local int nprocs(int n)
{
# ifdef _SC_NPROCESSORS_ONLN
n = (int)sysconf(_SC_NPROCESSORS_ONLN);
# else
# ifdef _SC_NPROC_ONLN
n = (int)sysconf(_SC_NPROC_ONLN);
# else
# ifdef __hpux
struct pst_dynamic psd;
if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) != -1)
n = psd.psd_proc_cnt;
# endif
# endif
# endif
return n;
}
#endif
/* set option defaults */
local void defaults(void)
{
g.level = Z_DEFAULT_COMPRESSION;
/* default zopfli options as set by ZopfliInitOptions():
verbose = 0
numiterations = 15
blocksplitting = 1
blocksplittinglast = 0
blocksplittingmax = 15
*/
ZopfliInitOptions(&g.zopts);
#ifdef NOTHREAD
g.procs = 1;
#else
g.procs = nprocs(8);
#endif
g.block = 131072UL; /* 128K */
g.rsync = 0; /* don't do rsync blocking */
g.setdict = 1; /* initialize dictionary each thread */
g.verbosity = 1; /* normal message level */
g.headis = 3; /* store/restore name and timestamp */
g.pipeout = 0; /* don't force output to stdout */
g.sufx = ".gz"; /* compressed file suffix */
g.decode = 0; /* compress */
g.list = 0; /* compress */
g.keep = 0; /* delete input file once compressed */
g.force = 0; /* don't overwrite, don't compress links */
g.recurse = 0; /* don't go into directories */
g.form = 0; /* use gzip format */
}
/* long options conversion to short options */
local char *longopts[][2] = {
{"LZW", "Z"}, {"ascii", "a"}, {"best", "9"}, {"bits", "Z"},
{"blocksize", "b"}, {"decompress", "d"}, {"fast", "1"}, {"first", "F"},
{"force", "f"}, {"help", "h"}, {"independent", "i"}, {"iterations", "I"},
{"keep", "k"}, {"license", "L"}, {"list", "l"}, {"maxsplits", "M"},
{"name", "N"}, {"no-name", "n"}, {"no-time", "T"}, {"oneblock", "O"},
{"processes", "p"}, {"quiet", "q"}, {"recursive", "r"}, {"rsyncable", "R"},
{"silent", "q"}, {"stdout", "c"}, {"suffix", "S"}, {"test", "t"},
{"to-stdout", "c"}, {"uncompress", "d"}, {"verbose", "v"},
{"version", "V"}, {"zip", "K"}, {"zlib", "z"}};
#define NLOPTS (sizeof(longopts) / (sizeof(char *) << 1))
/* either new buffer size, new compression level, or new number of processes --
get rid of old buffers and threads to force the creation of new ones with
the new settings */
local void new_opts(void)
{
single_compress(1);
#ifndef NOTHREAD
finish_jobs();
#endif
}
/* verify that arg is only digits, and if so, return the decimal value */
local size_t num(char *arg)
{
char *str = arg;
size_t val = 0;
if (*str == 0)
bail("internal error: empty parameter", "");
do {
if (*str < '0' || *str > '9' ||
(val && ((~(size_t)0) - (*str - '0')) / val < 10))
bail("invalid numeric parameter: ", arg);
val = val * 10 + (*str - '0');
} while (*++str);
return val;
}
/* process an option, return true if a file name and not an option */
local int option(char *arg)
{
static int get = 0; /* if not zero, look for option parameter */
char bad[3] = "-X"; /* for error messages (X is replaced) */
/* if no argument or dash option, check status of get */
if (get && (arg == NULL || *arg == '-')) {
bad[1] = "bpSIM"[get - 1];
bail("missing parameter after ", bad);
}
if (arg == NULL)
return 0;
/* process long option or short options */
if (*arg == '-') {
/* a single dash will be interpreted as stdin */
if (*++arg == 0)
return 1;
/* process long option (fall through with equivalent short option) */
if (*arg == '-') {
int j;
arg++;
for (j = NLOPTS - 1; j >= 0; j--)
if (strcmp(arg, longopts[j][0]) == 0) {
arg = longopts[j][1];
break;
}
if (j < 0)
bail("invalid option: ", arg - 2);
}
/* process short options (more than one allowed after dash) */
do {
/* if looking for a parameter, don't process more single character
options until we have the parameter */
if (get) {
if (get == 3)
bail("invalid usage: -s must be followed by space", "");
break; /* allow -pnnn and -bnnn, fall to parameter code */
}
/* process next single character option or compression level */
bad[1] = *arg;
switch (*arg) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
g.level = *arg - '0';
while (arg[1] >= '0' && arg[1] <= '9') {
if (g.level && (INT_MAX - (arg[1] - '0')) / g.level < 10)
bail("only levels 0..9 and 11 are allowed", "");
g.level = g.level * 10 + *++arg - '0';
}
if (g.level == 10 || g.level > 11)
bail("only levels 0..9 and 11 are allowed", "");
new_opts();
break;
case 'F': g.zopts.blocksplittinglast = 1; break;
case 'I': get = 4; break;
case 'K': g.form = 2; g.sufx = ".zip"; break;
case 'L':
fputs(VERSION, stderr);
fputs("Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013"
" Mark Adler\n",
stderr);
fputs("Subject to the terms of the zlib license.\n",
stderr);
fputs("No warranty is provided or implied.\n", stderr);
exit(0);
case 'M': get = 5; break;
case 'N': g.headis |= 0xf; break;
case 'O': g.zopts.blocksplitting = 0; break;
case 'R': g.rsync = 1; break;
case 'S': get = 3; break;
case 'T': g.headis &= ~0xa; break;
case 'V': fputs(VERSION, stderr); exit(0);
case 'Z':
bail("invalid option: LZW output not supported: ", bad);
case 'a':
bail("invalid option: ascii conversion not supported: ", bad);
case 'b': get = 1; break;
case 'c': g.pipeout = 1; break;
case 'd': if (!g.decode) g.headis >>= 2; g.decode = 1; break;
case 'f': g.force = 1; break;
case 'h': help(); break;
case 'i': g.setdict = 0; break;
case 'k': g.keep = 1; break;
case 'l': g.list = 1; break;
case 'n': g.headis &= ~5; break;
case 'p': get = 2; break;
case 'q': g.verbosity = 0; break;
case 'r': g.recurse = 1; break;
case 't': g.decode = 2; break;
case 'v': g.verbosity++; break;
case 'z': g.form = 1; g.sufx = ".zz"; break;
default:
bail("invalid option: ", bad);
}
} while (*++arg);
if (*arg == 0)
return 0;
}
/* process option parameter for -b, -p, -S, -I, or -M */
if (get) {
size_t n;
if (get == 1) {
n = num(arg);
g.block = n << 10; /* chunk size */
if (g.block < DICT)
bail("block size too small (must be >= 32K)", "");
if (n != g.block >> 10 ||
OUTPOOL(g.block) < g.block ||
(ssize_t)OUTPOOL(g.block) < 0 ||
g.block > (1UL << 29)) /* limited by append_len() */
bail("block size too large: ", arg);
new_opts();
}
else if (get == 2) {
n = num(arg);
g.procs = (int)n; /* # processes */
if (g.procs < 1)
bail("invalid number of processes: ", arg);
if ((size_t)g.procs != n || INBUFS(g.procs) < 1)
bail("too many processes: ", arg);
#ifdef NOTHREAD
if (g.procs > 1)
bail("compiled without threads", "");
#endif
new_opts();
}
else if (get == 3)
g.sufx = arg; /* gz suffix */
else if (get == 4)
g.zopts.numiterations = num(arg); /* optimization iterations */
else if (get == 5)
g.zopts.blocksplittingmax = num(arg); /* max block splits */
get = 0;
return 0;
}
/* neither an option nor parameter */
return 1;
}
/* catch termination signal */
local void cut_short(int sig)
{
(void)sig;
Trace(("termination by user"));
if (g.outd != -1 && g.outf != NULL)
unlink(g.outf);
log_dump();
_exit(1);
}
/* Process arguments, compress in the gzip format. Note that procs must be at
least two in order to provide a dictionary in one work unit for the other
work unit, and that size must be at least 32K to store a full dictionary. */
int main(int argc, char **argv)
{
int n; /* general index */
int noop; /* true to suppress option decoding */
unsigned long done; /* number of named files processed */
char *opts, *p; /* environment default options, marker */
/* initialize globals */
g.outf = NULL;
g.first = 1;
g.hname = NULL;
/* save pointer to program name for error messages */
p = strrchr(argv[0], '/');
p = p == NULL ? argv[0] : p + 1;
g.prog = *p ? p : "pigz";
/* prepare for interrupts and logging */
signal(SIGINT, cut_short);
#ifndef NOTHREAD
yarn_prefix = g.prog; /* prefix for yarn error messages */
yarn_abort = cut_short; /* call on thread error */
#endif
#ifdef DEBUG
gettimeofday(&start, NULL); /* starting time for log entries */
log_init(); /* initialize logging */
#endif
/* set all options to defaults */
defaults();
/* process user environment variable defaults in GZIP */
opts = getenv("GZIP");
if (opts != NULL) {
while (*opts) {
while (*opts == ' ' || *opts == '\t')
opts++;
p = opts;
while (*p && *p != ' ' && *p != '\t')
p++;
n = *p;
*p = 0;
if (option(opts))
bail("cannot provide files in GZIP environment variable", "");
opts = p + (n ? 1 : 0);
}
option(NULL);
}
/* process user environment variable defaults in PIGZ as well */
opts = getenv("PIGZ");
if (opts != NULL) {
while (*opts) {
while (*opts == ' ' || *opts == '\t')
opts++;
p = opts;
while (*p && *p != ' ' && *p != '\t')
p++;
n = *p;
*p = 0;
if (option(opts))
bail("cannot provide files in PIGZ environment variable", "");
opts = p + (n ? 1 : 0);
}
option(NULL);
}
/* decompress if named "unpigz" or "gunzip", to stdout if "*cat" */
if (strcmp(g.prog, "unpigz") == 0 || strcmp(g.prog, "gunzip") == 0) {
if (!g.decode)
g.headis >>= 2;
g.decode = 1;
}
if ((n = strlen(g.prog)) > 2 && strcmp(g.prog + n - 3, "cat") == 0) {
if (!g.decode)
g.headis >>= 2;
g.decode = 1;
g.pipeout = 1;
}
/* if no arguments and compressed data to or from a terminal, show help */
if (argc < 2 && isatty(g.decode ? 0 : 1))
help();
/* process command-line arguments, no options after "--" */
done = noop = 0;
for (n = 1; n < argc; n++)
if (noop == 0 && strcmp(argv[n], "--") == 0) {
noop = 1;
option(NULL);
}
else if (noop || option(argv[n])) { /* true if file name, process it */
if (done == 1 && g.pipeout && !g.decode && !g.list && g.form > 1)
complain("warning: output will be concatenated zip files -- "
"will not be able to extract");
process(strcmp(argv[n], "-") ? argv[n] : NULL);
done++;
}
option(NULL);
/* list stdin or compress stdin to stdout if no file names provided */
if (done == 0)
process(NULL);
/* done -- release resources, show log */
new_opts();
log_dump();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1466_0 |
crossvul-cpp_data_good_1569_1 | /*
Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com)
Copyright (C) 2009 RedHat 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <sys/utsname.h>
#include "internal_libreport.h"
// Locking logic:
//
// The directory is locked by creating a symlink named .lock inside it,
// whose value (where it "points to") is the pid of locking process.
// We use symlink, not an ordinary file, because symlink creation
// is an atomic operation.
//
// There are two cases where after .lock creation, we might discover
// that directory is not really free:
// * another process just created new directory, but didn't manage
// to lock it before us.
// * another process is deleting the directory, and we managed to sneak in
// and create .lock after it deleted all files (including .lock)
// but before it rmdir'ed the empty directory.
//
// Both these cases are detected by the fact that file named "time"
// is not present (it must be present in any valid dump dir).
// If after locking the dir we don't see time file, we remove the lock
// at once and back off. What happens in concurrent processes
// we interfered with?
// * "create new dump dir" process just re-tries locking.
// * "delete dump dir" process just retries rmdir.
//
// There is another case when we don't find time file:
// when the directory is not really a *dump* dir - user gave us
// an ordinary directory name by mistake.
// We detect it by bailing out of "lock, check time file; sleep
// and retry if it doesn't exist" loop using a counter.
//
// To make locking work reliably, it's important to set timeouts
// correctly. For example, dd_create should retry locking
// its newly-created directory much faster than dd_opendir
// tries to lock the directory it tries to open.
// How long to sleep between "symlink fails with EEXIST,
// readlink fails with ENOENT" tries. Someone just unlocked the dir.
// We never bail out in this case, we retry forever.
// The value can be really small:
#define SYMLINK_RETRY_USLEEP (10*1000)
// How long to sleep when lock file with valid pid is seen by dd_opendir
// (we are waiting for other process to unlock or die):
#define WAIT_FOR_OTHER_PROCESS_USLEEP (500*1000)
// How long to sleep when lock file with valid pid is seen by dd_create
// (some idiot jumped the gun and locked the dir we just created).
// Must not be the same as WAIT_FOR_OTHER_PROCESS_USLEEP (we depend on this)
// and should be small (we have the priority in locking, this is OUR dir):
#define CREATE_LOCK_USLEEP (10*1000)
// How long to sleep after we locked a dir, found no time file
// (either we are racing with someone, or it's not a dump dir)
// and unlocked it;
// and after how many tries to give up and declare it's not a dump dir:
#define NO_TIME_FILE_USLEEP (50*1000)
#define NO_TIME_FILE_COUNT 10
// How long to sleep after we unlocked an empty dir, but then rmdir failed
// (some idiot jumped the gun and locked the dir we are deleting);
// and after how many tries to give up:
#define RMDIR_FAIL_USLEEP (10*1000)
#define RMDIR_FAIL_COUNT 50
static char *load_text_file(const char *path, unsigned flags);
static void copy_file_from_chroot(struct dump_dir* dd, const char *name,
const char *chroot_dir, const char *file_path);
static bool isdigit_str(const char *str)
{
do
{
if (*str < '0' || *str > '9') return false;
str++;
} while (*str);
return true;
}
static bool exist_file_dir(const char *path)
{
struct stat buf;
if (stat(path, &buf) == 0)
{
if (S_ISDIR(buf.st_mode) || S_ISREG(buf.st_mode))
{
return true;
}
}
return false;
}
/* Returns value less than 0 if the file is not readable or
* if the file doesn't contain valid unixt time stamp.
*
* Any possible failure will be logged.
*/
static time_t parse_time_file(const char *filename)
{
/* Open input file, and parse it. */
int fd = open(filename, O_RDONLY | O_NOFOLLOW);
if (fd < 0)
{
VERB2 pwarn_msg("Can't open '%s'", filename);
return -1;
}
/* ~ maximal number of digits for positive time stamp string */
char time_buf[sizeof(time_t) * 3 + 1];
ssize_t rdsz = read(fd, time_buf, sizeof(time_buf));
/* Just reading, so no need to check the returned value. */
close(fd);
if (rdsz == -1)
{
VERB2 pwarn_msg("Can't read from '%s'", filename);
return -1;
}
/* approximate maximal number of digits in timestamp is sizeof(time_t)*3 */
/* buffer has this size + 1 byte for trailing '\0' */
/* if whole size of buffer was read then file is bigger */
/* than string representing maximal time stamp */
if (rdsz == sizeof(time_buf))
{
VERB2 warn_msg("File '%s' is too long to be valid unix "
"time stamp (max size %u)", filename, (int)sizeof(time_buf));
return -1;
}
/* Our tools don't put trailing newline into time file,
* but we allow such format too:
*/
if (rdsz > 0 && time_buf[rdsz - 1] == '\n')
rdsz--;
time_buf[rdsz] = '\0';
/* Note that on some architectures (x32) time_t is "long long" */
errno = 0; /* To distinguish success/failure after call */
char *endptr;
long long val = strtoll(time_buf, &endptr, /* base */ 10);
const long long MAX_TIME_T = (1ULL << (sizeof(time_t)*8 - 1)) - 1;
/* Check for various possible errors */
if (errno
|| (*endptr != '\0')
|| val >= MAX_TIME_T
|| !isdigit_str(time_buf) /* this filters out "-num", " num", "" */
) {
VERB2 pwarn_msg("File '%s' doesn't contain valid unix "
"time stamp ('%s')", filename, time_buf);
return -1;
}
/* If we got here, strtoll() successfully parsed a number */
return val;
}
/* Return values:
* -1: error (in this case, errno is 0 if error message is already logged)
* 0: failed to lock (someone else has it locked)
* 1: success
*/
int create_symlink_lockfile(const char* lock_file, const char* pid)
{
while (symlink(pid, lock_file) != 0)
{
if (errno != EEXIST)
{
if (errno != ENOENT && errno != ENOTDIR && errno != EACCES)
{
perror_msg("Can't create lock file '%s'", lock_file);
errno = 0;
}
return -1;
}
char pid_buf[sizeof(pid_t)*3 + 4];
ssize_t r = readlink(lock_file, pid_buf, sizeof(pid_buf) - 1);
if (r < 0)
{
if (errno == ENOENT)
{
/* Looks like lock_file was deleted */
usleep(SYMLINK_RETRY_USLEEP); /* avoid CPU eating loop */
continue;
}
perror_msg("Can't read lock file '%s'", lock_file);
errno = 0;
return -1;
}
pid_buf[r] = '\0';
if (strcmp(pid_buf, pid) == 0)
{
log("Lock file '%s' is already locked by us", lock_file);
return 0;
}
if (isdigit_str(pid_buf))
{
char pid_str[sizeof("/proc/") + sizeof(pid_buf)];
snprintf(pid_str, sizeof(pid_str), "/proc/%s", pid_buf);
if (access(pid_str, F_OK) == 0)
{
log("Lock file '%s' is locked by process %s", lock_file, pid_buf);
return 0;
}
log("Lock file '%s' was locked by process %s, but it crashed?", lock_file, pid_buf);
}
/* The file may be deleted by now by other process. Ignore ENOENT */
if (unlink(lock_file) != 0 && errno != ENOENT)
{
perror_msg("Can't remove stale lock file '%s'", lock_file);
errno = 0;
return -1;
}
}
log_info("Locked '%s'", lock_file);
return 1;
}
static const char *dd_check(struct dump_dir *dd)
{
unsigned dirname_len = strlen(dd->dd_dirname);
char filename_buf[FILENAME_MAX+1];
strcpy(filename_buf, dd->dd_dirname);
strcpy(filename_buf + dirname_len, "/"FILENAME_TIME);
dd->dd_time = parse_time_file(filename_buf);
if (dd->dd_time < 0)
{
log_warning("Missing file: "FILENAME_TIME);
return FILENAME_TIME;
}
strcpy(filename_buf + dirname_len, "/"FILENAME_TYPE);
dd->dd_type = load_text_file(filename_buf, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!dd->dd_type || (strlen(dd->dd_type) == 0))
{
log_warning("Missing or empty file: "FILENAME_TYPE);
return FILENAME_TYPE;
}
return NULL;
}
static int dd_lock(struct dump_dir *dd, unsigned sleep_usec, int flags)
{
if (dd->locked)
error_msg_and_die("Locking bug on '%s'", dd->dd_dirname);
char pid_buf[sizeof(long)*3 + 2];
snprintf(pid_buf, sizeof(pid_buf), "%lu", (long)getpid());
unsigned dirname_len = strlen(dd->dd_dirname);
char lock_buf[dirname_len + sizeof("/.lock")];
strcpy(lock_buf, dd->dd_dirname);
strcpy(lock_buf + dirname_len, "/.lock");
unsigned count = NO_TIME_FILE_COUNT;
retry:
while (1)
{
int r = create_symlink_lockfile(lock_buf, pid_buf);
if (r < 0)
return r; /* error */
if (r > 0)
break; /* locked successfully */
/* Other process has the lock, wait for it to go away */
usleep(sleep_usec);
}
/* Are we called by dd_opendir (as opposed to dd_create)? */
if (sleep_usec == WAIT_FOR_OTHER_PROCESS_USLEEP) /* yes */
{
const char *missing_file = dd_check(dd);
/* some of the required files don't exist. We managed to lock the directory
* which was just created by somebody else, or is almost deleted
* by delete_file_dir.
* Unlock and back off.
*/
if (missing_file)
{
xunlink(lock_buf);
log_warning("Unlocked '%s' (no or corrupted '%s' file)", lock_buf, missing_file);
if (--count == 0 || flags & DD_DONT_WAIT_FOR_LOCK)
{
errno = EISDIR; /* "this is an ordinary dir, not dump dir" */
return -1;
}
usleep(NO_TIME_FILE_USLEEP);
goto retry;
}
}
dd->locked = true;
return 0;
}
static void dd_unlock(struct dump_dir *dd)
{
if (dd->locked)
{
dd->locked = 0;
unsigned dirname_len = strlen(dd->dd_dirname);
char lock_buf[dirname_len + sizeof("/.lock")];
strcpy(lock_buf, dd->dd_dirname);
strcpy(lock_buf + dirname_len, "/.lock");
xunlink(lock_buf);
log_info("Unlocked '%s'", lock_buf);
}
}
static inline struct dump_dir *dd_init(void)
{
struct dump_dir* dd = (struct dump_dir*)xzalloc(sizeof(struct dump_dir));
dd->dd_time = -1;
return dd;
}
int dd_exist(const struct dump_dir *dd, const char *path)
{
if (!str_is_correct_filename(path))
error_msg_and_die("Cannot test existence. '%s' is not a valid file name", path);
char *full_path = concat_path_file(dd->dd_dirname, path);
int ret = exist_file_dir(full_path);
free(full_path);
return ret;
}
void dd_close(struct dump_dir *dd)
{
if (!dd)
return;
dd_unlock(dd);
if (dd->next_dir)
{
closedir(dd->next_dir);
/* free(dd->next_dir); - WRONG! */
}
free(dd->dd_type);
free(dd->dd_dirname);
free(dd);
}
static char* rm_trailing_slashes(const char *dir)
{
unsigned len = strlen(dir);
while (len != 0 && dir[len-1] == '/')
len--;
return xstrndup(dir, len);
}
struct dump_dir *dd_opendir(const char *dir, int flags)
{
struct dump_dir *dd = dd_init();
dir = dd->dd_dirname = rm_trailing_slashes(dir);
struct stat stat_buf;
if (stat(dir, &stat_buf) != 0)
goto cant_access;
/* & 0666 should remove the executable bit */
dd->mode = (stat_buf.st_mode & 0666);
errno = 0;
if (dd_lock(dd, WAIT_FOR_OTHER_PROCESS_USLEEP, flags) < 0)
{
if ((flags & DD_OPEN_READONLY) && errno == EACCES)
{
/* Directory is not writable. If it seems to be readable,
* return "read only" dd, not NULL */
if (stat(dir, &stat_buf) == 0
&& S_ISDIR(stat_buf.st_mode)
&& access(dir, R_OK) == 0
) {
if(dd_check(dd) != NULL)
{
dd_close(dd);
dd = NULL;
}
return dd;
}
}
if (errno == EISDIR)
{
/* EISDIR: dd_lock can lock the dir, but it sees no time file there,
* even after it retried many times. It must be an ordinary directory!
*
* Without this check, e.g. abrt-action-print happily prints any current
* directory when run without arguments, because its option -d DIR
* defaults to "."!
*/
error_msg("'%s' is not a problem directory", dir);
}
else
{
cant_access:
if (errno == ENOENT || errno == ENOTDIR)
{
if (!(flags & DD_FAIL_QUIETLY_ENOENT))
error_msg("'%s' does not exist", dir);
}
else
{
if (!(flags & DD_FAIL_QUIETLY_EACCES))
perror_msg("Can't access '%s'", dir);
}
}
dd_close(dd);
return NULL;
}
dd->dd_uid = (uid_t)-1L;
dd->dd_gid = (gid_t)-1L;
if (geteuid() == 0)
{
/* In case caller would want to create more files, he'll need uid:gid */
struct stat stat_buf;
if (stat(dir, &stat_buf) != 0 || !S_ISDIR(stat_buf.st_mode))
{
error_msg("Can't stat '%s', or it is not a directory", dir);
dd_close(dd);
return NULL;
}
dd->dd_uid = stat_buf.st_uid;
dd->dd_gid = stat_buf.st_gid;
}
return dd;
}
/* Create a fresh empty debug dump dir which is owned bu the calling user. If
* you want to create the directory with meaningful ownership you should
* consider using dd_create() function or you can modify the ownership
* afterwards by calling dd_reset_ownership() function.
*
* ABRT owns dump dir:
* We should not allow users to write new files or write into existing ones,
* but they should be able to read them.
*
* We set dir's gid to passwd(uid)->pw_gid parameter, and we set uid to
* abrt's user id. We do not allow write access to group. We can't set dir's
* uid to crashed applications's user uid because owner can modify dir's
* mode and ownership.
*
* Advantages:
* Safeness
*
* Disadvantages:
* This approach leads to stealing of directories because events requires
* write access to a dump directory and events are run under non root (abrt)
* user while reporting.
*
* This approach allows group members to see crashes of other members.
* Institutions like schools uses one common group for all students.
*
* User owns dump dir:
* We grant ownership of dump directories to the user (read/write access).
*
* We set set dir's uid to crashed applications's user uid, and we set gid to
* abrt's group id. We allow write access to group because we want to allow
* abrt binaries to process dump directories.
*
* Advantages:
* No disadvantages from the previous approach
*
* Disadvantages:
* In order to protect the system dump directories must be saved on
* noncritical filesystem (e.g. /tmp or /var/tmp).
*
*
* @param uid
* Crashed application's User Id
*
* We currently have only three callers:
* kernel oops hook: uid -> not saved, so everyone can steal and work with it
* this hook runs under 0:0
*
* ccpp hook: uid=uid of crashed user's binary
* this hook runs under 0:0
*
* create_dump_dir_from_problem_data() function:
* Currently known callers:
* abrt server: uid=uid of user's executable
* this runs under 0:0
* - clinets: python hook, ruby hook
* abrt dbus: uid=uid of user's executable
* this runs under 0:0
* - clients: setroubleshootd, abrt python
*/
struct dump_dir *dd_create_skeleton(const char *dir, uid_t uid, mode_t mode, int flags)
{
/* a little trick to copy read bits from file mode to exec bit of dir mode*/
mode_t dir_mode = mode | ((mode & 0444) >> 2);
struct dump_dir *dd = dd_init();
dd->mode = mode;
/* Unlike dd_opendir, can't use realpath: the directory doesn't exist yet,
* realpath will always return NULL. We don't really have to:
* dd_opendir(".") makes sense, dd_create(".") does not.
*/
dir = dd->dd_dirname = rm_trailing_slashes(dir);
const char *last_component = strrchr(dir, '/');
if (last_component)
last_component++;
else
last_component = dir;
if (dot_or_dotdot(last_component))
{
/* dd_create("."), dd_create(".."), dd_create("dir/."),
* dd_create("dir/..") and similar are madness, refuse them.
*/
error_msg("Bad dir name '%s'", dir);
dd_close(dd);
return NULL;
}
/* Was creating it with mode 0700 and user as the owner, but this allows
* the user to replace any file in the directory, changing security-sensitive data
* (e.g. "uid", "analyzer", "executable")
*/
int r;
if ((flags & DD_CREATE_PARENTS))
r = g_mkdir_with_parents(dd->dd_dirname, dir_mode);
else
r = mkdir(dd->dd_dirname, dir_mode);
if (r != 0)
{
perror_msg("Can't create directory '%s'", dir);
dd_close(dd);
return NULL;
}
if (dd_lock(dd, CREATE_LOCK_USLEEP, /*flags:*/ 0) < 0)
{
dd_close(dd);
return NULL;
}
/* mkdir's mode (above) can be affected by umask, fix it */
if (chmod(dir, dir_mode) == -1)
{
perror_msg("Can't change mode of '%s'", dir);
dd_close(dd);
return NULL;
}
dd->dd_uid = (uid_t)-1L;
dd->dd_gid = (gid_t)-1L;
if (uid != (uid_t)-1L)
{
dd->dd_uid = 0;
dd->dd_uid = 0;
#if DUMP_DIR_OWNED_BY_USER > 0
/* Check crashed application's uid */
struct passwd *pw = getpwuid(uid);
if (pw)
dd->dd_uid = pw->pw_uid;
else
error_msg("User %lu does not exist, using uid 0", (long)uid);
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (gr)
dd->dd_gid = gr->gr_gid;
else
error_msg("Group 'abrt' does not exist, using gid 0");
#else
/* Get ABRT's user uid */
struct passwd *pw = getpwnam("abrt");
if (pw)
dd->dd_uid = pw->pw_uid;
else
error_msg("User 'abrt' does not exist, using uid 0");
/* Get crashed application's gid */
pw = getpwuid(uid);
if (pw)
dd->dd_gid = pw->pw_gid;
else
error_msg("User %lu does not exist, using gid 0", (long)uid);
#endif
}
return dd;
}
/* Resets ownership of the given directory to UID and GID according to values
* in dd_create_skeleton().
*/
int dd_reset_ownership(struct dump_dir *dd)
{
const int r =lchown(dd->dd_dirname, dd->dd_uid, dd->dd_gid);
if (r < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dd->dd_dirname,
(long)dd->dd_uid, (long)dd->dd_gid);
}
return r;
}
/* Calls dd_create_skeleton() and dd_reset_ownership().
*/
struct dump_dir *dd_create(const char *dir, uid_t uid, mode_t mode)
{
struct dump_dir *dd = dd_create_skeleton(dir, uid, mode, DD_CREATE_PARENTS);
if (dd == NULL)
return NULL;
/* ignore results */
dd_reset_ownership(dd);
return dd;
}
void dd_create_basic_files(struct dump_dir *dd, uid_t uid, const char *chroot_dir)
{
char long_str[sizeof(long) * 3 + 2];
char *time_str = dd_load_text_ext(dd, FILENAME_TIME,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!time_str)
{
time_t t = time(NULL);
sprintf(long_str, "%lu", (long)t);
/* first occurrence */
dd_save_text(dd, FILENAME_TIME, long_str);
/* last occurrence */
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, long_str);
}
free(time_str);
/* it doesn't make sense to create the uid file if uid == -1 */
if (uid != (uid_t)-1L)
{
snprintf(long_str, sizeof(long_str), "%li", (long)uid);
dd_save_text(dd, FILENAME_UID, long_str);
}
struct utsname buf;
uname(&buf); /* never fails */
/* Check if files already exist in dumpdir as they might have
* more relevant information about the problem
*/
if (!dd_exist(dd, FILENAME_KERNEL))
dd_save_text(dd, FILENAME_KERNEL, buf.release);
if (!dd_exist(dd, FILENAME_ARCHITECTURE))
dd_save_text(dd, FILENAME_ARCHITECTURE, buf.machine);
if (!dd_exist(dd, FILENAME_HOSTNAME))
dd_save_text(dd, FILENAME_HOSTNAME, buf.nodename);
char *release = load_text_file("/etc/os-release",
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
if (release)
{
dd_save_text(dd, FILENAME_OS_INFO, release);
free(release);
}
if (chroot_dir)
copy_file_from_chroot(dd, FILENAME_OS_INFO_IN_ROOTDIR, chroot_dir, "/etc/os-release");
/* if release exists in dumpdir don't create it, but don't warn
* if it doesn't
* i.e: anaconda doesn't have /etc/{fedora,redhat}-release and trying to load it
* results in errors: rhbz#725857
*/
release = dd_load_text_ext(dd, FILENAME_OS_RELEASE,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!release)
{
release = load_text_file("/etc/system-release",
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
if (!release)
release = load_text_file("/etc/redhat-release",
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
if (!release)
release = load_text_file("/etc/SuSE-release", DD_OPEN_FOLLOW);
char *newline = strchr(release, '\n');
if (newline)
*newline = '\0';
dd_save_text(dd, FILENAME_OS_RELEASE, release);
if (chroot_dir)
copy_file_from_chroot(dd, FILENAME_OS_RELEASE_IN_ROOTDIR, chroot_dir, "/etc/system-release");
}
free(release);
}
void dd_sanitize_mode_and_owner(struct dump_dir *dd)
{
/* Don't sanitize if we aren't run under root:
* we assume that during file creation (by whatever means,
* even by "hostname >file" in abrt_event.conf)
* normal umask-based mode setting takes care of correct mode,
* and uid:gid is, of course, set to user's uid and gid.
*
* For root operating on /var/spool/abrt/USERS_PROBLEM, this isn't true:
* "hostname >file", for example, would create file OWNED BY ROOT!
* This routine resets mode and uid:gid for all such files.
*/
if (dd->dd_uid == (uid_t)-1)
return;
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
DIR *d = opendir(dd->dd_dirname);
if (!d)
return;
struct dirent *dent;
while ((dent = readdir(d)) != NULL)
{
if (dent->d_name[0] == '.') /* ".lock", ".", ".."? skip */
continue;
char *full_path = concat_path_file(dd->dd_dirname, dent->d_name);
struct stat statbuf;
if (lstat(full_path, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
{
if ((statbuf.st_mode & 0777) != dd->mode)
{
/* We open the file only for fchmod()
*
* We use fchmod() because chmod() changes the permissions of
* the file specified whose pathname is given in path, which
* is dereferenced if it is a symbolic link.
*/
int fd = open(full_path, O_RDONLY | O_NOFOLLOW, dd->mode);
if (fd >= 0)
{
if (fchmod(fd, dd->mode) != 0)
{
perror_msg("Can't change '%s' mode to 0%o", full_path,
(unsigned)dd->mode);
}
close(fd);
}
else
{
perror_msg("Can't open regular file '%s'", full_path);
}
}
if (statbuf.st_uid != dd->dd_uid || statbuf.st_gid != dd->dd_gid)
{
if (lchown(full_path, dd->dd_uid, dd->dd_gid) != 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", full_path,
(long)dd->dd_uid, (long)dd->dd_gid);
}
}
}
free(full_path);
}
closedir(d);
}
static int delete_file_dir(const char *dir, bool skip_lock_file)
{
DIR *d = opendir(dir);
if (!d)
{
/* The caller expects us to error out only if the directory
* still exists (not deleted). If directory
* *doesn't exist*, return 0 and clear errno.
*/
if (errno == ENOENT || errno == ENOTDIR)
{
errno = 0;
return 0;
}
return -1;
}
bool unlink_lock_file = false;
struct dirent *dent;
while ((dent = readdir(d)) != NULL)
{
if (dot_or_dotdot(dent->d_name))
continue;
if (skip_lock_file && strcmp(dent->d_name, ".lock") == 0)
{
unlink_lock_file = true;
continue;
}
char *full_path = concat_path_file(dir, dent->d_name);
if (unlink(full_path) == -1 && errno != ENOENT)
{
int err = 0;
if (errno == EISDIR)
{
errno = 0;
err = delete_file_dir(full_path, /*skip_lock_file:*/ false);
}
if (errno || err)
{
perror_msg("Can't remove '%s'", full_path);
free(full_path);
closedir(d);
return -1;
}
}
free(full_path);
}
closedir(d);
/* Here we know for sure that all files/subdirs we found via readdir
* were deleted successfully. If rmdir below fails, we assume someone
* is racing with us and created a new file.
*/
if (unlink_lock_file)
{
char *full_path = concat_path_file(dir, ".lock");
xunlink(full_path);
free(full_path);
unsigned cnt = RMDIR_FAIL_COUNT;
do {
if (rmdir(dir) == 0)
return 0;
/* Someone locked the dir after unlink, but before rmdir.
* This "someone" must be dd_lock().
* It detects this (by seeing that there is no time file)
* and backs off at once. So we need to just retry rmdir,
* with minimal sleep.
*/
usleep(RMDIR_FAIL_USLEEP);
} while (--cnt != 0);
}
int r = rmdir(dir);
if (r)
perror_msg("Can't remove directory '%s'", dir);
return r;
}
int dd_delete(struct dump_dir *dd)
{
if (!dd->locked)
{
error_msg("unlocked problem directory %s cannot be deleted", dd->dd_dirname);
return -1;
}
int r = delete_file_dir(dd->dd_dirname, /*skip_lock_file:*/ true);
dd->locked = 0; /* delete_file_dir already removed .lock */
dd_close(dd);
return r;
}
int dd_chown(struct dump_dir *dd, uid_t new_uid)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
struct stat statbuf;
if (!(stat(dd->dd_dirname, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)))
{
perror_msg("stat('%s')", dd->dd_dirname);
return 1;
}
struct passwd *pw = getpwuid(new_uid);
if (!pw)
{
error_msg("UID %ld is not found in user database", (long)new_uid);
return 1;
}
#if DUMP_DIR_OWNED_BY_USER > 0
uid_t owners_uid = pw->pw_uid;
gid_t groups_gid = statbuf.st_gid;
#else
uid_t owners_uid = statbuf.st_uid;
gid_t groups_gid = pw->pw_gid;
#endif
int chown_res = lchown(dd->dd_dirname, owners_uid, groups_gid);
if (chown_res)
perror_msg("lchown('%s')", dd->dd_dirname);
else
{
dd_init_next_file(dd);
char *full_name;
while (chown_res == 0 && dd_get_next_file(dd, /*short_name*/ NULL, &full_name))
{
log_debug("chowning %s", full_name);
chown_res = lchown(full_name, owners_uid, groups_gid);
if (chown_res)
perror_msg("lchown('%s')", full_name);
free(full_name);
}
}
return chown_res;
}
static char *load_text_file(const char *path, unsigned flags)
{
int fd = open(path, O_RDONLY | ((flags & DD_OPEN_FOLLOW) ? 0 : O_NOFOLLOW));
if (fd == -1)
{
if (!(flags & DD_FAIL_QUIETLY_ENOENT))
perror_msg("Can't open file '%s'", path);
return (flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE ? NULL : xstrdup(""));
}
/* Why? Because half a million read syscalls of one byte each isn't fun.
* FILE-based IO buffers reads.
*/
FILE *fp = fdopen(fd, "r");
if (!fp)
die_out_of_memory();
struct strbuf *buf_content = strbuf_new();
int oneline = 0;
int ch;
while ((ch = fgetc(fp)) != EOF)
{
//TODO? \r -> \n?
//TODO? strip trailing spaces/tabs?
if (ch == '\n')
oneline = (oneline << 1) | 1;
if (ch == '\0')
ch = ' ';
if (isspace(ch) || ch >= ' ') /* used !iscntrl, but it failed on unicode */
strbuf_append_char(buf_content, ch);
}
fclose(fp); /* this also closes fd */
char last = oneline != 0 ? buf_content->buf[buf_content->len - 1] : 0;
if (last == '\n')
{
/* If file contains exactly one '\n' and it is at the end, remove it.
* This enables users to use simple "echo blah >file" in order to create
* short string items in dump dirs.
*/
if (oneline == 1)
buf_content->buf[--buf_content->len] = '\0';
}
else /* last != '\n' */
{
/* Last line is unterminated, fix it */
/* Cases: */
/* oneline=0: "qwe" - DONT fix this! */
/* oneline=1: "qwe\nrty" - two lines in fact */
/* oneline>1: "qwe\nrty\uio" */
if (oneline >= 1)
strbuf_append_char(buf_content, '\n');
}
return strbuf_free_nobuf(buf_content);
}
static void copy_file_from_chroot(struct dump_dir* dd, const char *name, const char *chroot_dir, const char *file_path)
{
char *chrooted_name = concat_path_file(chroot_dir, file_path);
char *data = load_text_file(chrooted_name,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
free(chrooted_name);
if (data)
{
dd_save_text(dd, name, data);
free(data);
}
}
static bool save_binary_file(const char *path, const char* data, unsigned size, uid_t uid, gid_t gid, mode_t mode)
{
/* the mode is set by the caller, see dd_create() for security analysis */
unlink(path);
int fd = open(path, O_WRONLY | O_TRUNC | O_CREAT | O_NOFOLLOW, mode);
if (fd < 0)
{
perror_msg("Can't open file '%s'", path);
return false;
}
if (uid != (uid_t)-1L)
{
if (fchown(fd, uid, gid) == -1)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", path, (long)uid, (long)gid);
}
}
/* O_CREATE in the open() call above causes that the permissions of the
* created file are (mode & ~umask)
*
* This is true only if we did create file. We are not sure we created it
* in this case - it may exist already.
*/
if (fchmod(fd, mode) == -1)
{
perror_msg("Can't change mode of '%s'", path);
}
unsigned r = full_write(fd, data, size);
close(fd);
if (r != size)
{
error_msg("Can't save file '%s'", path);
return false;
}
return true;
}
char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)
{
// if (!dd->locked)
// error_msg_and_die("dump_dir is not opened"); /* bug */
if (!str_is_correct_filename(name))
{
error_msg("Cannot load text. '%s' is not a valid file name", name);
if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))
xfunc_die();
}
/* Compat with old abrt dumps. Remove in abrt-2.1 */
if (strcmp(name, "release") == 0)
name = FILENAME_OS_RELEASE;
char *full_path = concat_path_file(dd->dd_dirname, name);
char *ret = load_text_file(full_path, flags);
free(full_path);
return ret;
}
char* dd_load_text(const struct dump_dir *dd, const char *name)
{
return dd_load_text_ext(dd, name, /*flags:*/ 0);
}
void dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
if (!str_is_correct_filename(name))
error_msg_and_die("Cannot save text. '%s' is not a valid file name", name);
char *full_path = concat_path_file(dd->dd_dirname, name);
save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
free(full_path);
}
void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
if (!str_is_correct_filename(name))
error_msg_and_die("Cannot save binary. '%s' is not a valid file name", name);
char *full_path = concat_path_file(dd->dd_dirname, name);
save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
free(full_path);
}
long dd_get_item_size(struct dump_dir *dd, const char *name)
{
if (!str_is_correct_filename(name))
error_msg_and_die("Cannot get item size. '%s' is not a valid file name", name);
long size = -1;
char *iname = concat_path_file(dd->dd_dirname, name);
struct stat statbuf;
if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
size = statbuf.st_size;
else
{
if (errno == ENOENT)
size = 0;
else
perror_msg("Can't get size of file '%s'", iname);
}
free(iname);
return size;
}
int dd_delete_item(struct dump_dir *dd, const char *name)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
if (!str_is_correct_filename(name))
error_msg_and_die("Cannot delete item. '%s' is not a valid file name", name);
char *path = concat_path_file(dd->dd_dirname, name);
int res = unlink(path);
if (res < 0)
{
if (errno == ENOENT)
errno = res = 0;
else
perror_msg("Can't delete file '%s'", path);
}
free(path);
return res;
}
DIR *dd_init_next_file(struct dump_dir *dd)
{
// if (!dd->locked)
// error_msg_and_die("dump_dir is not opened"); /* bug */
if (dd->next_dir)
closedir(dd->next_dir);
dd->next_dir = opendir(dd->dd_dirname);
if (!dd->next_dir)
{
error_msg("Can't open directory '%s'", dd->dd_dirname);
}
return dd->next_dir;
}
int dd_get_next_file(struct dump_dir *dd, char **short_name, char **full_name)
{
if (dd->next_dir == NULL)
return 0;
struct dirent *dent;
while ((dent = readdir(dd->next_dir)) != NULL)
{
if (is_regular_file(dent, dd->dd_dirname))
{
if (short_name)
*short_name = xstrdup(dent->d_name);
if (full_name)
*full_name = concat_path_file(dd->dd_dirname, dent->d_name);
return 1;
}
}
closedir(dd->next_dir);
dd->next_dir = NULL;
return 0;
}
/* reported_to handling */
void add_reported_to(struct dump_dir *dd, const char *line)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
char *reported_to = dd_load_text_ext(dd, FILENAME_REPORTED_TO, DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (add_reported_to_data(&reported_to, line))
dd_save_text(dd, FILENAME_REPORTED_TO, reported_to);
free(reported_to);
}
report_result_t *find_in_reported_to(struct dump_dir *dd, const char *report_label)
{
char *reported_to = dd_load_text_ext(dd, FILENAME_REPORTED_TO,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!reported_to)
return NULL;
report_result_t *result = find_in_reported_to_data(reported_to, report_label);
free(reported_to);
return result;
}
GList *read_entire_reported_to(struct dump_dir *dd)
{
char *reported_to = dd_load_text_ext(dd, FILENAME_REPORTED_TO,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!reported_to)
return NULL;
GList *result = read_entire_reported_to_data(reported_to);
free(reported_to);
return result;
}
/* reported_to handling end */
int dd_rename(struct dump_dir *dd, const char *new_path)
{
if (!dd->locked)
{
error_msg("unlocked problem directory %s cannot be renamed", dd->dd_dirname);
return -1;
}
int res = rename(dd->dd_dirname, new_path);
if (res == 0)
{
free(dd->dd_dirname);
dd->dd_dirname = rm_trailing_slashes(new_path);
}
return res;
}
/* Utility function */
void delete_dump_dir(const char *dirname)
{
struct dump_dir *dd = dd_opendir(dirname, /*flags:*/ 0);
if (dd)
{
dd_delete(dd);
}
}
#if DUMP_DIR_OWNED_BY_USER == 0
static bool uid_in_group(uid_t uid, gid_t gid)
{
char **tmp;
struct passwd *pwd = getpwuid(uid);
if (!pwd)
return FALSE;
if (pwd->pw_gid == gid)
return TRUE;
struct group *grp = getgrgid(gid);
if (!(grp && grp->gr_mem))
return FALSE;
for (tmp = grp->gr_mem; *tmp != NULL; tmp++)
{
if (g_strcmp0(*tmp, pwd->pw_name) == 0)
{
log_debug("user %s belongs to group: %s", pwd->pw_name, grp->gr_name);
return TRUE;
}
}
log_info("user %s DOESN'T belong to group: %s", pwd->pw_name, grp->gr_name);
return FALSE;
}
#endif
int dump_dir_stat_for_uid(const char *dirname, uid_t uid)
{
struct stat statbuf;
if (stat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
{
log_debug("can't get stat of '%s': not a problem directory", dirname);
errno = ENOTDIR;
return -1;
}
errno = 0;
int ddstat = 0;
if (uid == 0 || (statbuf.st_mode & S_IROTH))
{
log_debug("directory '%s' is accessible by %ld uid", dirname, (long)uid);
ddstat |= DD_STAT_ACCESSIBLE_BY_UID;
}
#if DUMP_DIR_OWNED_BY_USER > 0
if (uid == statbuf.st_uid)
#else
if (uid_in_group(uid, statbuf.st_gid))
#endif
{
log_debug("%ld uid owns directory '%s'", (long)uid, dirname);
ddstat |= DD_STAT_ACCESSIBLE_BY_UID;
ddstat |= DD_STAT_OWNED_BY_UID;
}
return ddstat;
}
int dump_dir_accessible_by_uid(const char *dirname, uid_t uid)
{
int ddstat = dump_dir_stat_for_uid(dirname, uid);
if (ddstat >= 0)
return ddstat & DD_STAT_ACCESSIBLE_BY_UID;
VERB3 pwarn_msg("can't determine accessibility of '%s' by %ld uid", dirname, (long)uid);
return 0;
}
int dd_mark_as_notreportable(struct dump_dir *dd, const char *reason)
{
if (!dd->locked)
{
error_msg("dump_dir is not locked for writing");
return -1;
}
dd_save_text(dd, FILENAME_NOT_REPORTABLE, reason);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1569_1 |
crossvul-cpp_data_bad_1569_1 | /*
Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com)
Copyright (C) 2009 RedHat 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <sys/utsname.h>
#include "internal_libreport.h"
// Locking logic:
//
// The directory is locked by creating a symlink named .lock inside it,
// whose value (where it "points to") is the pid of locking process.
// We use symlink, not an ordinary file, because symlink creation
// is an atomic operation.
//
// There are two cases where after .lock creation, we might discover
// that directory is not really free:
// * another process just created new directory, but didn't manage
// to lock it before us.
// * another process is deleting the directory, and we managed to sneak in
// and create .lock after it deleted all files (including .lock)
// but before it rmdir'ed the empty directory.
//
// Both these cases are detected by the fact that file named "time"
// is not present (it must be present in any valid dump dir).
// If after locking the dir we don't see time file, we remove the lock
// at once and back off. What happens in concurrent processes
// we interfered with?
// * "create new dump dir" process just re-tries locking.
// * "delete dump dir" process just retries rmdir.
//
// There is another case when we don't find time file:
// when the directory is not really a *dump* dir - user gave us
// an ordinary directory name by mistake.
// We detect it by bailing out of "lock, check time file; sleep
// and retry if it doesn't exist" loop using a counter.
//
// To make locking work reliably, it's important to set timeouts
// correctly. For example, dd_create should retry locking
// its newly-created directory much faster than dd_opendir
// tries to lock the directory it tries to open.
// How long to sleep between "symlink fails with EEXIST,
// readlink fails with ENOENT" tries. Someone just unlocked the dir.
// We never bail out in this case, we retry forever.
// The value can be really small:
#define SYMLINK_RETRY_USLEEP (10*1000)
// How long to sleep when lock file with valid pid is seen by dd_opendir
// (we are waiting for other process to unlock or die):
#define WAIT_FOR_OTHER_PROCESS_USLEEP (500*1000)
// How long to sleep when lock file with valid pid is seen by dd_create
// (some idiot jumped the gun and locked the dir we just created).
// Must not be the same as WAIT_FOR_OTHER_PROCESS_USLEEP (we depend on this)
// and should be small (we have the priority in locking, this is OUR dir):
#define CREATE_LOCK_USLEEP (10*1000)
// How long to sleep after we locked a dir, found no time file
// (either we are racing with someone, or it's not a dump dir)
// and unlocked it;
// and after how many tries to give up and declare it's not a dump dir:
#define NO_TIME_FILE_USLEEP (50*1000)
#define NO_TIME_FILE_COUNT 10
// How long to sleep after we unlocked an empty dir, but then rmdir failed
// (some idiot jumped the gun and locked the dir we are deleting);
// and after how many tries to give up:
#define RMDIR_FAIL_USLEEP (10*1000)
#define RMDIR_FAIL_COUNT 50
static char *load_text_file(const char *path, unsigned flags);
static void copy_file_from_chroot(struct dump_dir* dd, const char *name,
const char *chroot_dir, const char *file_path);
static bool isdigit_str(const char *str)
{
do
{
if (*str < '0' || *str > '9') return false;
str++;
} while (*str);
return true;
}
static bool exist_file_dir(const char *path)
{
struct stat buf;
if (stat(path, &buf) == 0)
{
if (S_ISDIR(buf.st_mode) || S_ISREG(buf.st_mode))
{
return true;
}
}
return false;
}
/* Returns value less than 0 if the file is not readable or
* if the file doesn't contain valid unixt time stamp.
*
* Any possible failure will be logged.
*/
static time_t parse_time_file(const char *filename)
{
/* Open input file, and parse it. */
int fd = open(filename, O_RDONLY | O_NOFOLLOW);
if (fd < 0)
{
VERB2 pwarn_msg("Can't open '%s'", filename);
return -1;
}
/* ~ maximal number of digits for positive time stamp string */
char time_buf[sizeof(time_t) * 3 + 1];
ssize_t rdsz = read(fd, time_buf, sizeof(time_buf));
/* Just reading, so no need to check the returned value. */
close(fd);
if (rdsz == -1)
{
VERB2 pwarn_msg("Can't read from '%s'", filename);
return -1;
}
/* approximate maximal number of digits in timestamp is sizeof(time_t)*3 */
/* buffer has this size + 1 byte for trailing '\0' */
/* if whole size of buffer was read then file is bigger */
/* than string representing maximal time stamp */
if (rdsz == sizeof(time_buf))
{
VERB2 warn_msg("File '%s' is too long to be valid unix "
"time stamp (max size %u)", filename, (int)sizeof(time_buf));
return -1;
}
/* Our tools don't put trailing newline into time file,
* but we allow such format too:
*/
if (rdsz > 0 && time_buf[rdsz - 1] == '\n')
rdsz--;
time_buf[rdsz] = '\0';
/* Note that on some architectures (x32) time_t is "long long" */
errno = 0; /* To distinguish success/failure after call */
char *endptr;
long long val = strtoll(time_buf, &endptr, /* base */ 10);
const long long MAX_TIME_T = (1ULL << (sizeof(time_t)*8 - 1)) - 1;
/* Check for various possible errors */
if (errno
|| (*endptr != '\0')
|| val >= MAX_TIME_T
|| !isdigit_str(time_buf) /* this filters out "-num", " num", "" */
) {
VERB2 pwarn_msg("File '%s' doesn't contain valid unix "
"time stamp ('%s')", filename, time_buf);
return -1;
}
/* If we got here, strtoll() successfully parsed a number */
return val;
}
/* Return values:
* -1: error (in this case, errno is 0 if error message is already logged)
* 0: failed to lock (someone else has it locked)
* 1: success
*/
int create_symlink_lockfile(const char* lock_file, const char* pid)
{
while (symlink(pid, lock_file) != 0)
{
if (errno != EEXIST)
{
if (errno != ENOENT && errno != ENOTDIR && errno != EACCES)
{
perror_msg("Can't create lock file '%s'", lock_file);
errno = 0;
}
return -1;
}
char pid_buf[sizeof(pid_t)*3 + 4];
ssize_t r = readlink(lock_file, pid_buf, sizeof(pid_buf) - 1);
if (r < 0)
{
if (errno == ENOENT)
{
/* Looks like lock_file was deleted */
usleep(SYMLINK_RETRY_USLEEP); /* avoid CPU eating loop */
continue;
}
perror_msg("Can't read lock file '%s'", lock_file);
errno = 0;
return -1;
}
pid_buf[r] = '\0';
if (strcmp(pid_buf, pid) == 0)
{
log("Lock file '%s' is already locked by us", lock_file);
return 0;
}
if (isdigit_str(pid_buf))
{
char pid_str[sizeof("/proc/") + sizeof(pid_buf)];
snprintf(pid_str, sizeof(pid_str), "/proc/%s", pid_buf);
if (access(pid_str, F_OK) == 0)
{
log("Lock file '%s' is locked by process %s", lock_file, pid_buf);
return 0;
}
log("Lock file '%s' was locked by process %s, but it crashed?", lock_file, pid_buf);
}
/* The file may be deleted by now by other process. Ignore ENOENT */
if (unlink(lock_file) != 0 && errno != ENOENT)
{
perror_msg("Can't remove stale lock file '%s'", lock_file);
errno = 0;
return -1;
}
}
log_info("Locked '%s'", lock_file);
return 1;
}
static const char *dd_check(struct dump_dir *dd)
{
unsigned dirname_len = strlen(dd->dd_dirname);
char filename_buf[FILENAME_MAX+1];
strcpy(filename_buf, dd->dd_dirname);
strcpy(filename_buf + dirname_len, "/"FILENAME_TIME);
dd->dd_time = parse_time_file(filename_buf);
if (dd->dd_time < 0)
{
log_warning("Missing file: "FILENAME_TIME);
return FILENAME_TIME;
}
strcpy(filename_buf + dirname_len, "/"FILENAME_TYPE);
dd->dd_type = load_text_file(filename_buf, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!dd->dd_type || (strlen(dd->dd_type) == 0))
{
log_warning("Missing or empty file: "FILENAME_TYPE);
return FILENAME_TYPE;
}
return NULL;
}
static int dd_lock(struct dump_dir *dd, unsigned sleep_usec, int flags)
{
if (dd->locked)
error_msg_and_die("Locking bug on '%s'", dd->dd_dirname);
char pid_buf[sizeof(long)*3 + 2];
snprintf(pid_buf, sizeof(pid_buf), "%lu", (long)getpid());
unsigned dirname_len = strlen(dd->dd_dirname);
char lock_buf[dirname_len + sizeof("/.lock")];
strcpy(lock_buf, dd->dd_dirname);
strcpy(lock_buf + dirname_len, "/.lock");
unsigned count = NO_TIME_FILE_COUNT;
retry:
while (1)
{
int r = create_symlink_lockfile(lock_buf, pid_buf);
if (r < 0)
return r; /* error */
if (r > 0)
break; /* locked successfully */
/* Other process has the lock, wait for it to go away */
usleep(sleep_usec);
}
/* Are we called by dd_opendir (as opposed to dd_create)? */
if (sleep_usec == WAIT_FOR_OTHER_PROCESS_USLEEP) /* yes */
{
const char *missing_file = dd_check(dd);
/* some of the required files don't exist. We managed to lock the directory
* which was just created by somebody else, or is almost deleted
* by delete_file_dir.
* Unlock and back off.
*/
if (missing_file)
{
xunlink(lock_buf);
log_warning("Unlocked '%s' (no or corrupted '%s' file)", lock_buf, missing_file);
if (--count == 0 || flags & DD_DONT_WAIT_FOR_LOCK)
{
errno = EISDIR; /* "this is an ordinary dir, not dump dir" */
return -1;
}
usleep(NO_TIME_FILE_USLEEP);
goto retry;
}
}
dd->locked = true;
return 0;
}
static void dd_unlock(struct dump_dir *dd)
{
if (dd->locked)
{
dd->locked = 0;
unsigned dirname_len = strlen(dd->dd_dirname);
char lock_buf[dirname_len + sizeof("/.lock")];
strcpy(lock_buf, dd->dd_dirname);
strcpy(lock_buf + dirname_len, "/.lock");
xunlink(lock_buf);
log_info("Unlocked '%s'", lock_buf);
}
}
static inline struct dump_dir *dd_init(void)
{
struct dump_dir* dd = (struct dump_dir*)xzalloc(sizeof(struct dump_dir));
dd->dd_time = -1;
return dd;
}
int dd_exist(const struct dump_dir *dd, const char *path)
{
char *full_path = concat_path_file(dd->dd_dirname, path);
int ret = exist_file_dir(full_path);
free(full_path);
return ret;
}
void dd_close(struct dump_dir *dd)
{
if (!dd)
return;
dd_unlock(dd);
if (dd->next_dir)
{
closedir(dd->next_dir);
/* free(dd->next_dir); - WRONG! */
}
free(dd->dd_type);
free(dd->dd_dirname);
free(dd);
}
static char* rm_trailing_slashes(const char *dir)
{
unsigned len = strlen(dir);
while (len != 0 && dir[len-1] == '/')
len--;
return xstrndup(dir, len);
}
struct dump_dir *dd_opendir(const char *dir, int flags)
{
struct dump_dir *dd = dd_init();
dir = dd->dd_dirname = rm_trailing_slashes(dir);
struct stat stat_buf;
if (stat(dir, &stat_buf) != 0)
goto cant_access;
/* & 0666 should remove the executable bit */
dd->mode = (stat_buf.st_mode & 0666);
errno = 0;
if (dd_lock(dd, WAIT_FOR_OTHER_PROCESS_USLEEP, flags) < 0)
{
if ((flags & DD_OPEN_READONLY) && errno == EACCES)
{
/* Directory is not writable. If it seems to be readable,
* return "read only" dd, not NULL */
if (stat(dir, &stat_buf) == 0
&& S_ISDIR(stat_buf.st_mode)
&& access(dir, R_OK) == 0
) {
if(dd_check(dd) != NULL)
{
dd_close(dd);
dd = NULL;
}
return dd;
}
}
if (errno == EISDIR)
{
/* EISDIR: dd_lock can lock the dir, but it sees no time file there,
* even after it retried many times. It must be an ordinary directory!
*
* Without this check, e.g. abrt-action-print happily prints any current
* directory when run without arguments, because its option -d DIR
* defaults to "."!
*/
error_msg("'%s' is not a problem directory", dir);
}
else
{
cant_access:
if (errno == ENOENT || errno == ENOTDIR)
{
if (!(flags & DD_FAIL_QUIETLY_ENOENT))
error_msg("'%s' does not exist", dir);
}
else
{
if (!(flags & DD_FAIL_QUIETLY_EACCES))
perror_msg("Can't access '%s'", dir);
}
}
dd_close(dd);
return NULL;
}
dd->dd_uid = (uid_t)-1L;
dd->dd_gid = (gid_t)-1L;
if (geteuid() == 0)
{
/* In case caller would want to create more files, he'll need uid:gid */
struct stat stat_buf;
if (stat(dir, &stat_buf) != 0 || !S_ISDIR(stat_buf.st_mode))
{
error_msg("Can't stat '%s', or it is not a directory", dir);
dd_close(dd);
return NULL;
}
dd->dd_uid = stat_buf.st_uid;
dd->dd_gid = stat_buf.st_gid;
}
return dd;
}
/* Create a fresh empty debug dump dir which is owned bu the calling user. If
* you want to create the directory with meaningful ownership you should
* consider using dd_create() function or you can modify the ownership
* afterwards by calling dd_reset_ownership() function.
*
* ABRT owns dump dir:
* We should not allow users to write new files or write into existing ones,
* but they should be able to read them.
*
* We set dir's gid to passwd(uid)->pw_gid parameter, and we set uid to
* abrt's user id. We do not allow write access to group. We can't set dir's
* uid to crashed applications's user uid because owner can modify dir's
* mode and ownership.
*
* Advantages:
* Safeness
*
* Disadvantages:
* This approach leads to stealing of directories because events requires
* write access to a dump directory and events are run under non root (abrt)
* user while reporting.
*
* This approach allows group members to see crashes of other members.
* Institutions like schools uses one common group for all students.
*
* User owns dump dir:
* We grant ownership of dump directories to the user (read/write access).
*
* We set set dir's uid to crashed applications's user uid, and we set gid to
* abrt's group id. We allow write access to group because we want to allow
* abrt binaries to process dump directories.
*
* Advantages:
* No disadvantages from the previous approach
*
* Disadvantages:
* In order to protect the system dump directories must be saved on
* noncritical filesystem (e.g. /tmp or /var/tmp).
*
*
* @param uid
* Crashed application's User Id
*
* We currently have only three callers:
* kernel oops hook: uid -> not saved, so everyone can steal and work with it
* this hook runs under 0:0
*
* ccpp hook: uid=uid of crashed user's binary
* this hook runs under 0:0
*
* create_dump_dir_from_problem_data() function:
* Currently known callers:
* abrt server: uid=uid of user's executable
* this runs under 0:0
* - clinets: python hook, ruby hook
* abrt dbus: uid=uid of user's executable
* this runs under 0:0
* - clients: setroubleshootd, abrt python
*/
struct dump_dir *dd_create_skeleton(const char *dir, uid_t uid, mode_t mode, int flags)
{
/* a little trick to copy read bits from file mode to exec bit of dir mode*/
mode_t dir_mode = mode | ((mode & 0444) >> 2);
struct dump_dir *dd = dd_init();
dd->mode = mode;
/* Unlike dd_opendir, can't use realpath: the directory doesn't exist yet,
* realpath will always return NULL. We don't really have to:
* dd_opendir(".") makes sense, dd_create(".") does not.
*/
dir = dd->dd_dirname = rm_trailing_slashes(dir);
const char *last_component = strrchr(dir, '/');
if (last_component)
last_component++;
else
last_component = dir;
if (dot_or_dotdot(last_component))
{
/* dd_create("."), dd_create(".."), dd_create("dir/."),
* dd_create("dir/..") and similar are madness, refuse them.
*/
error_msg("Bad dir name '%s'", dir);
dd_close(dd);
return NULL;
}
/* Was creating it with mode 0700 and user as the owner, but this allows
* the user to replace any file in the directory, changing security-sensitive data
* (e.g. "uid", "analyzer", "executable")
*/
int r;
if ((flags & DD_CREATE_PARENTS))
r = g_mkdir_with_parents(dd->dd_dirname, dir_mode);
else
r = mkdir(dd->dd_dirname, dir_mode);
if (r != 0)
{
perror_msg("Can't create directory '%s'", dir);
dd_close(dd);
return NULL;
}
if (dd_lock(dd, CREATE_LOCK_USLEEP, /*flags:*/ 0) < 0)
{
dd_close(dd);
return NULL;
}
/* mkdir's mode (above) can be affected by umask, fix it */
if (chmod(dir, dir_mode) == -1)
{
perror_msg("Can't change mode of '%s'", dir);
dd_close(dd);
return NULL;
}
dd->dd_uid = (uid_t)-1L;
dd->dd_gid = (gid_t)-1L;
if (uid != (uid_t)-1L)
{
dd->dd_uid = 0;
dd->dd_uid = 0;
#if DUMP_DIR_OWNED_BY_USER > 0
/* Check crashed application's uid */
struct passwd *pw = getpwuid(uid);
if (pw)
dd->dd_uid = pw->pw_uid;
else
error_msg("User %lu does not exist, using uid 0", (long)uid);
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (gr)
dd->dd_gid = gr->gr_gid;
else
error_msg("Group 'abrt' does not exist, using gid 0");
#else
/* Get ABRT's user uid */
struct passwd *pw = getpwnam("abrt");
if (pw)
dd->dd_uid = pw->pw_uid;
else
error_msg("User 'abrt' does not exist, using uid 0");
/* Get crashed application's gid */
pw = getpwuid(uid);
if (pw)
dd->dd_gid = pw->pw_gid;
else
error_msg("User %lu does not exist, using gid 0", (long)uid);
#endif
}
return dd;
}
/* Resets ownership of the given directory to UID and GID according to values
* in dd_create_skeleton().
*/
int dd_reset_ownership(struct dump_dir *dd)
{
const int r =lchown(dd->dd_dirname, dd->dd_uid, dd->dd_gid);
if (r < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dd->dd_dirname,
(long)dd->dd_uid, (long)dd->dd_gid);
}
return r;
}
/* Calls dd_create_skeleton() and dd_reset_ownership().
*/
struct dump_dir *dd_create(const char *dir, uid_t uid, mode_t mode)
{
struct dump_dir *dd = dd_create_skeleton(dir, uid, mode, DD_CREATE_PARENTS);
if (dd == NULL)
return NULL;
/* ignore results */
dd_reset_ownership(dd);
return dd;
}
void dd_create_basic_files(struct dump_dir *dd, uid_t uid, const char *chroot_dir)
{
char long_str[sizeof(long) * 3 + 2];
char *time_str = dd_load_text_ext(dd, FILENAME_TIME,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!time_str)
{
time_t t = time(NULL);
sprintf(long_str, "%lu", (long)t);
/* first occurrence */
dd_save_text(dd, FILENAME_TIME, long_str);
/* last occurrence */
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, long_str);
}
free(time_str);
/* it doesn't make sense to create the uid file if uid == -1 */
if (uid != (uid_t)-1L)
{
snprintf(long_str, sizeof(long_str), "%li", (long)uid);
dd_save_text(dd, FILENAME_UID, long_str);
}
struct utsname buf;
uname(&buf); /* never fails */
/* Check if files already exist in dumpdir as they might have
* more relevant information about the problem
*/
if (!dd_exist(dd, FILENAME_KERNEL))
dd_save_text(dd, FILENAME_KERNEL, buf.release);
if (!dd_exist(dd, FILENAME_ARCHITECTURE))
dd_save_text(dd, FILENAME_ARCHITECTURE, buf.machine);
if (!dd_exist(dd, FILENAME_HOSTNAME))
dd_save_text(dd, FILENAME_HOSTNAME, buf.nodename);
char *release = load_text_file("/etc/os-release",
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
if (release)
{
dd_save_text(dd, FILENAME_OS_INFO, release);
free(release);
}
if (chroot_dir)
copy_file_from_chroot(dd, FILENAME_OS_INFO_IN_ROOTDIR, chroot_dir, "/etc/os-release");
/* if release exists in dumpdir don't create it, but don't warn
* if it doesn't
* i.e: anaconda doesn't have /etc/{fedora,redhat}-release and trying to load it
* results in errors: rhbz#725857
*/
release = dd_load_text_ext(dd, FILENAME_OS_RELEASE,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!release)
{
release = load_text_file("/etc/system-release",
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
if (!release)
release = load_text_file("/etc/redhat-release",
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
if (!release)
release = load_text_file("/etc/SuSE-release", DD_OPEN_FOLLOW);
char *newline = strchr(release, '\n');
if (newline)
*newline = '\0';
dd_save_text(dd, FILENAME_OS_RELEASE, release);
if (chroot_dir)
copy_file_from_chroot(dd, FILENAME_OS_RELEASE_IN_ROOTDIR, chroot_dir, "/etc/system-release");
}
free(release);
}
void dd_sanitize_mode_and_owner(struct dump_dir *dd)
{
/* Don't sanitize if we aren't run under root:
* we assume that during file creation (by whatever means,
* even by "hostname >file" in abrt_event.conf)
* normal umask-based mode setting takes care of correct mode,
* and uid:gid is, of course, set to user's uid and gid.
*
* For root operating on /var/spool/abrt/USERS_PROBLEM, this isn't true:
* "hostname >file", for example, would create file OWNED BY ROOT!
* This routine resets mode and uid:gid for all such files.
*/
if (dd->dd_uid == (uid_t)-1)
return;
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
DIR *d = opendir(dd->dd_dirname);
if (!d)
return;
struct dirent *dent;
while ((dent = readdir(d)) != NULL)
{
if (dent->d_name[0] == '.') /* ".lock", ".", ".."? skip */
continue;
char *full_path = concat_path_file(dd->dd_dirname, dent->d_name);
struct stat statbuf;
if (lstat(full_path, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
{
if ((statbuf.st_mode & 0777) != dd->mode)
{
/* We open the file only for fchmod()
*
* We use fchmod() because chmod() changes the permissions of
* the file specified whose pathname is given in path, which
* is dereferenced if it is a symbolic link.
*/
int fd = open(full_path, O_RDONLY | O_NOFOLLOW, dd->mode);
if (fd >= 0)
{
if (fchmod(fd, dd->mode) != 0)
{
perror_msg("Can't change '%s' mode to 0%o", full_path,
(unsigned)dd->mode);
}
close(fd);
}
else
{
perror_msg("Can't open regular file '%s'", full_path);
}
}
if (statbuf.st_uid != dd->dd_uid || statbuf.st_gid != dd->dd_gid)
{
if (lchown(full_path, dd->dd_uid, dd->dd_gid) != 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", full_path,
(long)dd->dd_uid, (long)dd->dd_gid);
}
}
}
free(full_path);
}
closedir(d);
}
static int delete_file_dir(const char *dir, bool skip_lock_file)
{
DIR *d = opendir(dir);
if (!d)
{
/* The caller expects us to error out only if the directory
* still exists (not deleted). If directory
* *doesn't exist*, return 0 and clear errno.
*/
if (errno == ENOENT || errno == ENOTDIR)
{
errno = 0;
return 0;
}
return -1;
}
bool unlink_lock_file = false;
struct dirent *dent;
while ((dent = readdir(d)) != NULL)
{
if (dot_or_dotdot(dent->d_name))
continue;
if (skip_lock_file && strcmp(dent->d_name, ".lock") == 0)
{
unlink_lock_file = true;
continue;
}
char *full_path = concat_path_file(dir, dent->d_name);
if (unlink(full_path) == -1 && errno != ENOENT)
{
int err = 0;
if (errno == EISDIR)
{
errno = 0;
err = delete_file_dir(full_path, /*skip_lock_file:*/ false);
}
if (errno || err)
{
perror_msg("Can't remove '%s'", full_path);
free(full_path);
closedir(d);
return -1;
}
}
free(full_path);
}
closedir(d);
/* Here we know for sure that all files/subdirs we found via readdir
* were deleted successfully. If rmdir below fails, we assume someone
* is racing with us and created a new file.
*/
if (unlink_lock_file)
{
char *full_path = concat_path_file(dir, ".lock");
xunlink(full_path);
free(full_path);
unsigned cnt = RMDIR_FAIL_COUNT;
do {
if (rmdir(dir) == 0)
return 0;
/* Someone locked the dir after unlink, but before rmdir.
* This "someone" must be dd_lock().
* It detects this (by seeing that there is no time file)
* and backs off at once. So we need to just retry rmdir,
* with minimal sleep.
*/
usleep(RMDIR_FAIL_USLEEP);
} while (--cnt != 0);
}
int r = rmdir(dir);
if (r)
perror_msg("Can't remove directory '%s'", dir);
return r;
}
int dd_delete(struct dump_dir *dd)
{
if (!dd->locked)
{
error_msg("unlocked problem directory %s cannot be deleted", dd->dd_dirname);
return -1;
}
int r = delete_file_dir(dd->dd_dirname, /*skip_lock_file:*/ true);
dd->locked = 0; /* delete_file_dir already removed .lock */
dd_close(dd);
return r;
}
int dd_chown(struct dump_dir *dd, uid_t new_uid)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
struct stat statbuf;
if (!(stat(dd->dd_dirname, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)))
{
perror_msg("stat('%s')", dd->dd_dirname);
return 1;
}
struct passwd *pw = getpwuid(new_uid);
if (!pw)
{
error_msg("UID %ld is not found in user database", (long)new_uid);
return 1;
}
#if DUMP_DIR_OWNED_BY_USER > 0
uid_t owners_uid = pw->pw_uid;
gid_t groups_gid = statbuf.st_gid;
#else
uid_t owners_uid = statbuf.st_uid;
gid_t groups_gid = pw->pw_gid;
#endif
int chown_res = lchown(dd->dd_dirname, owners_uid, groups_gid);
if (chown_res)
perror_msg("lchown('%s')", dd->dd_dirname);
else
{
dd_init_next_file(dd);
char *full_name;
while (chown_res == 0 && dd_get_next_file(dd, /*short_name*/ NULL, &full_name))
{
log_debug("chowning %s", full_name);
chown_res = lchown(full_name, owners_uid, groups_gid);
if (chown_res)
perror_msg("lchown('%s')", full_name);
free(full_name);
}
}
return chown_res;
}
static char *load_text_file(const char *path, unsigned flags)
{
int fd = open(path, O_RDONLY | ((flags & DD_OPEN_FOLLOW) ? 0 : O_NOFOLLOW));
if (fd == -1)
{
if (!(flags & DD_FAIL_QUIETLY_ENOENT))
perror_msg("Can't open file '%s'", path);
return (flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE ? NULL : xstrdup(""));
}
/* Why? Because half a million read syscalls of one byte each isn't fun.
* FILE-based IO buffers reads.
*/
FILE *fp = fdopen(fd, "r");
if (!fp)
die_out_of_memory();
struct strbuf *buf_content = strbuf_new();
int oneline = 0;
int ch;
while ((ch = fgetc(fp)) != EOF)
{
//TODO? \r -> \n?
//TODO? strip trailing spaces/tabs?
if (ch == '\n')
oneline = (oneline << 1) | 1;
if (ch == '\0')
ch = ' ';
if (isspace(ch) || ch >= ' ') /* used !iscntrl, but it failed on unicode */
strbuf_append_char(buf_content, ch);
}
fclose(fp); /* this also closes fd */
char last = oneline != 0 ? buf_content->buf[buf_content->len - 1] : 0;
if (last == '\n')
{
/* If file contains exactly one '\n' and it is at the end, remove it.
* This enables users to use simple "echo blah >file" in order to create
* short string items in dump dirs.
*/
if (oneline == 1)
buf_content->buf[--buf_content->len] = '\0';
}
else /* last != '\n' */
{
/* Last line is unterminated, fix it */
/* Cases: */
/* oneline=0: "qwe" - DONT fix this! */
/* oneline=1: "qwe\nrty" - two lines in fact */
/* oneline>1: "qwe\nrty\uio" */
if (oneline >= 1)
strbuf_append_char(buf_content, '\n');
}
return strbuf_free_nobuf(buf_content);
}
static void copy_file_from_chroot(struct dump_dir* dd, const char *name, const char *chroot_dir, const char *file_path)
{
char *chrooted_name = concat_path_file(chroot_dir, file_path);
char *data = load_text_file(chrooted_name,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_OPEN_FOLLOW);
free(chrooted_name);
if (data)
{
dd_save_text(dd, name, data);
free(data);
}
}
static bool save_binary_file(const char *path, const char* data, unsigned size, uid_t uid, gid_t gid, mode_t mode)
{
/* the mode is set by the caller, see dd_create() for security analysis */
unlink(path);
int fd = open(path, O_WRONLY | O_TRUNC | O_CREAT | O_NOFOLLOW, mode);
if (fd < 0)
{
perror_msg("Can't open file '%s'", path);
return false;
}
if (uid != (uid_t)-1L)
{
if (fchown(fd, uid, gid) == -1)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", path, (long)uid, (long)gid);
}
}
/* O_CREATE in the open() call above causes that the permissions of the
* created file are (mode & ~umask)
*
* This is true only if we did create file. We are not sure we created it
* in this case - it may exist already.
*/
if (fchmod(fd, mode) == -1)
{
perror_msg("Can't change mode of '%s'", path);
}
unsigned r = full_write(fd, data, size);
close(fd);
if (r != size)
{
error_msg("Can't save file '%s'", path);
return false;
}
return true;
}
char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)
{
// if (!dd->locked)
// error_msg_and_die("dump_dir is not opened"); /* bug */
/* Compat with old abrt dumps. Remove in abrt-2.1 */
if (strcmp(name, "release") == 0)
name = FILENAME_OS_RELEASE;
char *full_path = concat_path_file(dd->dd_dirname, name);
char *ret = load_text_file(full_path, flags);
free(full_path);
return ret;
}
char* dd_load_text(const struct dump_dir *dd, const char *name)
{
return dd_load_text_ext(dd, name, /*flags:*/ 0);
}
void dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
char *full_path = concat_path_file(dd->dd_dirname, name);
save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
free(full_path);
}
void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
char *full_path = concat_path_file(dd->dd_dirname, name);
save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
free(full_path);
}
long dd_get_item_size(struct dump_dir *dd, const char *name)
{
long size = -1;
char *iname = concat_path_file(dd->dd_dirname, name);
struct stat statbuf;
if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
size = statbuf.st_size;
else
{
if (errno == ENOENT)
size = 0;
else
perror_msg("Can't get size of file '%s'", iname);
}
free(iname);
return size;
}
int dd_delete_item(struct dump_dir *dd, const char *name)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
char *path = concat_path_file(dd->dd_dirname, name);
int res = unlink(path);
if (res < 0)
{
if (errno == ENOENT)
errno = res = 0;
else
perror_msg("Can't delete file '%s'", path);
}
free(path);
return res;
}
DIR *dd_init_next_file(struct dump_dir *dd)
{
// if (!dd->locked)
// error_msg_and_die("dump_dir is not opened"); /* bug */
if (dd->next_dir)
closedir(dd->next_dir);
dd->next_dir = opendir(dd->dd_dirname);
if (!dd->next_dir)
{
error_msg("Can't open directory '%s'", dd->dd_dirname);
}
return dd->next_dir;
}
int dd_get_next_file(struct dump_dir *dd, char **short_name, char **full_name)
{
if (dd->next_dir == NULL)
return 0;
struct dirent *dent;
while ((dent = readdir(dd->next_dir)) != NULL)
{
if (is_regular_file(dent, dd->dd_dirname))
{
if (short_name)
*short_name = xstrdup(dent->d_name);
if (full_name)
*full_name = concat_path_file(dd->dd_dirname, dent->d_name);
return 1;
}
}
closedir(dd->next_dir);
dd->next_dir = NULL;
return 0;
}
/* reported_to handling */
void add_reported_to(struct dump_dir *dd, const char *line)
{
if (!dd->locked)
error_msg_and_die("dump_dir is not opened"); /* bug */
char *reported_to = dd_load_text_ext(dd, FILENAME_REPORTED_TO, DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (add_reported_to_data(&reported_to, line))
dd_save_text(dd, FILENAME_REPORTED_TO, reported_to);
free(reported_to);
}
report_result_t *find_in_reported_to(struct dump_dir *dd, const char *report_label)
{
char *reported_to = dd_load_text_ext(dd, FILENAME_REPORTED_TO,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!reported_to)
return NULL;
report_result_t *result = find_in_reported_to_data(reported_to, report_label);
free(reported_to);
return result;
}
GList *read_entire_reported_to(struct dump_dir *dd)
{
char *reported_to = dd_load_text_ext(dd, FILENAME_REPORTED_TO,
DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE);
if (!reported_to)
return NULL;
GList *result = read_entire_reported_to_data(reported_to);
free(reported_to);
return result;
}
/* reported_to handling end */
int dd_rename(struct dump_dir *dd, const char *new_path)
{
if (!dd->locked)
{
error_msg("unlocked problem directory %s cannot be renamed", dd->dd_dirname);
return -1;
}
int res = rename(dd->dd_dirname, new_path);
if (res == 0)
{
free(dd->dd_dirname);
dd->dd_dirname = rm_trailing_slashes(new_path);
}
return res;
}
/* Utility function */
void delete_dump_dir(const char *dirname)
{
struct dump_dir *dd = dd_opendir(dirname, /*flags:*/ 0);
if (dd)
{
dd_delete(dd);
}
}
#if DUMP_DIR_OWNED_BY_USER == 0
static bool uid_in_group(uid_t uid, gid_t gid)
{
char **tmp;
struct passwd *pwd = getpwuid(uid);
if (!pwd)
return FALSE;
if (pwd->pw_gid == gid)
return TRUE;
struct group *grp = getgrgid(gid);
if (!(grp && grp->gr_mem))
return FALSE;
for (tmp = grp->gr_mem; *tmp != NULL; tmp++)
{
if (g_strcmp0(*tmp, pwd->pw_name) == 0)
{
log_debug("user %s belongs to group: %s", pwd->pw_name, grp->gr_name);
return TRUE;
}
}
log_info("user %s DOESN'T belong to group: %s", pwd->pw_name, grp->gr_name);
return FALSE;
}
#endif
int dump_dir_stat_for_uid(const char *dirname, uid_t uid)
{
struct stat statbuf;
if (stat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
{
log_debug("can't get stat of '%s': not a problem directory", dirname);
errno = ENOTDIR;
return -1;
}
errno = 0;
int ddstat = 0;
if (uid == 0 || (statbuf.st_mode & S_IROTH))
{
log_debug("directory '%s' is accessible by %ld uid", dirname, (long)uid);
ddstat |= DD_STAT_ACCESSIBLE_BY_UID;
}
#if DUMP_DIR_OWNED_BY_USER > 0
if (uid == statbuf.st_uid)
#else
if (uid_in_group(uid, statbuf.st_gid))
#endif
{
log_debug("%ld uid owns directory '%s'", (long)uid, dirname);
ddstat |= DD_STAT_ACCESSIBLE_BY_UID;
ddstat |= DD_STAT_OWNED_BY_UID;
}
return ddstat;
}
int dump_dir_accessible_by_uid(const char *dirname, uid_t uid)
{
int ddstat = dump_dir_stat_for_uid(dirname, uid);
if (ddstat >= 0)
return ddstat & DD_STAT_ACCESSIBLE_BY_UID;
VERB3 pwarn_msg("can't determine accessibility of '%s' by %ld uid", dirname, (long)uid);
return 0;
}
int dd_mark_as_notreportable(struct dump_dir *dd, const char *reason)
{
if (!dd->locked)
{
error_msg("dump_dir is not locked for writing");
return -1;
}
dd_save_text(dd, FILENAME_NOT_REPORTABLE, reason);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1569_1 |
crossvul-cpp_data_good_422_1 | #ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mspack.h>
#include <ctype.h>
#include <sys/stat.h>
#include <error.h>
#if HAVE_MKDIR
# if MKDIR_TAKES_ONE_ARG
# define mkdir(a, b) mkdir(a)
# endif
#else
# if HAVE__MKDIR
# define mkdir(a, b) _mkdir(a)
# else
# error "Don't know how to create a directory on this system."
# endif
#endif
mode_t user_umask;
/**
* Ensures that all directory components in a filepath exist. New directory
* components are created, if necessary.
*
* @param path the filepath to check
* @return non-zero if all directory components in a filepath exist, zero
* if components do not exist and cannot be created
*/
static int ensure_filepath(char *path) {
struct stat st_buf;
char *p;
int ok;
for (p = &path[1]; *p; p++) {
if (*p != '/') continue;
*p = '\0';
ok = (stat(path, &st_buf) == 0) && S_ISDIR(st_buf.st_mode);
if (!ok) ok = (mkdir(path, 0777 & ~user_umask) == 0);
*p = '/';
if (!ok) return 0;
}
return 1;
}
char *create_output_name(char *fname) {
char *out, *p;
if ((out = malloc(strlen(fname) + 1))) {
/* remove leading slashes */
while (*fname == '/' || *fname == '\\') fname++;
/* if that removes all characters, just call it "x" */
strcpy(out, (*fname) ? fname : "x");
/* change "../" to "xx/" */
for (p = out; *p; p++) {
if (p[0] == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\\')) {
p[0] = p[1] = 'x';
}
}
}
return out;
}
static int sortfunc(const void *a, const void *b) {
off_t diff =
((* ((struct mschmd_file **) a))->offset) -
((* ((struct mschmd_file **) b))->offset);
return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0);
}
int main(int argc, char *argv[]) {
struct mschm_decompressor *chmd;
struct mschmd_header *chm;
struct mschmd_file *file, **f;
unsigned int numf, i;
setbuf(stdout, NULL);
setbuf(stderr, NULL);
user_umask = umask(0); umask(user_umask);
MSPACK_SYS_SELFTEST(i);
if (i) return 0;
if ((chmd = mspack_create_chm_decompressor(NULL))) {
for (argv++; *argv; argv++) {
printf("%s\n", *argv);
if ((chm = chmd->open(chmd, *argv))) {
/* build an ordered list of files for maximum extraction speed */
for (numf=0, file=chm->files; file; file = file->next) numf++;
if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) {
for (i=0, file=chm->files; file; file = file->next) f[i++] = file;
qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc);
for (i = 0; i < numf; i++) {
char *outname = create_output_name(f[i]->filename);
printf("Extracting %s\n", outname);
ensure_filepath(outname);
if (chmd->extract(chmd, f[i], outname)) {
printf("%s: extract error on \"%s\": %s\n",
*argv, f[i]->filename, ERROR(chmd));
}
free(outname);
}
free(f);
}
chmd->close(chmd, chm);
}
else {
printf("%s: can't open -- %s\n", *argv, ERROR(chmd));
}
}
mspack_destroy_chm_decompressor(chmd);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_422_1 |
crossvul-cpp_data_good_1520_4 | /*-
* Copyright (c) 2003-2010 Tim Kientzle
* Copyright (c) 2012 Michihiro NAKAJIMA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "archive_platform.h"
__FBSDID("$FreeBSD$");
#if !defined(_WIN32) || defined(__CYGWIN__)
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_ACL_H
#include <sys/acl.h>
#endif
#ifdef HAVE_SYS_EXTATTR_H
#include <sys/extattr.h>
#endif
#if defined(HAVE_SYS_XATTR_H)
#include <sys/xattr.h>
#elif defined(HAVE_ATTR_XATTR_H)
#include <attr/xattr.h>
#endif
#ifdef HAVE_SYS_EA_H
#include <sys/ea.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_UTIME_H
#include <sys/utime.h>
#endif
#ifdef HAVE_COPYFILE_H
#include <copyfile.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#ifdef HAVE_LINUX_FS_H
#include <linux/fs.h> /* for Linux file flags */
#endif
/*
* Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
* As the include guards don't agree, the order of include is important.
*/
#ifdef HAVE_LINUX_EXT2_FS_H
#include <linux/ext2_fs.h> /* for Linux file flags */
#endif
#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
#include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#include <stdio.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_UTIME_H
#include <utime.h>
#endif
#ifdef F_GETTIMES /* Tru64 specific */
#include <sys/fcntl1.h>
#endif
#if __APPLE__
#include <TargetConditionals.h>
#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
#include <quarantine.h>
#define HAVE_QUARANTINE 1
#endif
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
/* TODO: Support Mac OS 'quarantine' feature. This is really just a
* standard tag to mark files that have been downloaded as "tainted".
* On Mac OS, we should mark the extracted files as tainted if the
* archive being read was tainted. Windows has a similar feature; we
* should investigate ways to support this generically. */
#include "archive.h"
#include "archive_acl_private.h"
#include "archive_string.h"
#include "archive_endian.h"
#include "archive_entry.h"
#include "archive_private.h"
#include "archive_write_disk_private.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
struct fixup_entry {
struct fixup_entry *next;
struct archive_acl acl;
mode_t mode;
int64_t atime;
int64_t birthtime;
int64_t mtime;
int64_t ctime;
unsigned long atime_nanos;
unsigned long birthtime_nanos;
unsigned long mtime_nanos;
unsigned long ctime_nanos;
unsigned long fflags_set;
size_t mac_metadata_size;
void *mac_metadata;
int fixup; /* bitmask of what needs fixing */
char *name;
};
/*
* We use a bitmask to track which operations remain to be done for
* this file. In particular, this helps us avoid unnecessary
* operations when it's possible to take care of one step as a
* side-effect of another. For example, mkdir() can specify the mode
* for the newly-created object but symlink() cannot. This means we
* can skip chmod() if mkdir() succeeded, but we must explicitly
* chmod() if we're trying to create a directory that already exists
* (mkdir() failed) or if we're restoring a symlink. Similarly, we
* need to verify UID/GID before trying to restore SUID/SGID bits;
* that verification can occur explicitly through a stat() call or
* implicitly because of a successful chown() call.
*/
#define TODO_MODE_FORCE 0x40000000
#define TODO_MODE_BASE 0x20000000
#define TODO_SUID 0x10000000
#define TODO_SUID_CHECK 0x08000000
#define TODO_SGID 0x04000000
#define TODO_SGID_CHECK 0x02000000
#define TODO_APPLEDOUBLE 0x01000000
#define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
#define TODO_TIMES ARCHIVE_EXTRACT_TIME
#define TODO_OWNER ARCHIVE_EXTRACT_OWNER
#define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
#define TODO_ACLS ARCHIVE_EXTRACT_ACL
#define TODO_XATTR ARCHIVE_EXTRACT_XATTR
#define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA
#define TODO_HFS_COMPRESSION ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED
struct archive_write_disk {
struct archive archive;
mode_t user_umask;
struct fixup_entry *fixup_list;
struct fixup_entry *current_fixup;
int64_t user_uid;
int skip_file_set;
int64_t skip_file_dev;
int64_t skip_file_ino;
time_t start_time;
int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid);
void (*cleanup_gid)(void *private);
void *lookup_gid_data;
int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid);
void (*cleanup_uid)(void *private);
void *lookup_uid_data;
/*
* Full path of last file to satisfy symlink checks.
*/
struct archive_string path_safe;
/*
* Cached stat data from disk for the current entry.
* If this is valid, pst points to st. Otherwise,
* pst is null.
*/
struct stat st;
struct stat *pst;
/* Information about the object being restored right now. */
struct archive_entry *entry; /* Entry being extracted. */
char *name; /* Name of entry, possibly edited. */
struct archive_string _name_data; /* backing store for 'name' */
/* Tasks remaining for this object. */
int todo;
/* Tasks deferred until end-of-archive. */
int deferred;
/* Options requested by the client. */
int flags;
/* Handle for the file we're restoring. */
int fd;
/* Current offset for writing data to the file. */
int64_t offset;
/* Last offset actually written to disk. */
int64_t fd_offset;
/* Total bytes actually written to files. */
int64_t total_bytes_written;
/* Maximum size of file, -1 if unknown. */
int64_t filesize;
/* Dir we were in before this restore; only for deep paths. */
int restore_pwd;
/* Mode we should use for this entry; affected by _PERM and umask. */
mode_t mode;
/* UID/GID to use in restoring this entry. */
int64_t uid;
int64_t gid;
/*
* HFS+ Compression.
*/
/* Xattr "com.apple.decmpfs". */
uint32_t decmpfs_attr_size;
unsigned char *decmpfs_header_p;
/* ResourceFork set options used for fsetxattr. */
int rsrc_xattr_options;
/* Xattr "com.apple.ResourceFork". */
unsigned char *resource_fork;
size_t resource_fork_allocated_size;
unsigned int decmpfs_block_count;
uint32_t *decmpfs_block_info;
/* Buffer for compressed data. */
unsigned char *compressed_buffer;
size_t compressed_buffer_size;
size_t compressed_buffer_remaining;
/* The offset of the ResourceFork where compressed data will
* be placed. */
uint32_t compressed_rsrc_position;
uint32_t compressed_rsrc_position_v;
/* Buffer for uncompressed data. */
char *uncompressed_buffer;
size_t block_remaining_bytes;
size_t file_remaining_bytes;
#ifdef HAVE_ZLIB_H
z_stream stream;
int stream_valid;
int decmpfs_compression_level;
#endif
};
/*
* Default mode for dirs created automatically (will be modified by umask).
* Note that POSIX specifies 0777 for implicitly-created dirs, "modified
* by the process' file creation mask."
*/
#define DEFAULT_DIR_MODE 0777
/*
* Dir modes are restored in two steps: During the extraction, the permissions
* in the archive are modified to match the following limits. During
* the post-extract fixup pass, the permissions from the archive are
* applied.
*/
#define MINIMUM_DIR_MODE 0700
#define MAXIMUM_DIR_MODE 0775
/*
* Maxinum uncompressed size of a decmpfs block.
*/
#define MAX_DECMPFS_BLOCK_SIZE (64 * 1024)
/*
* HFS+ compression type.
*/
#define CMP_XATTR 3/* Compressed data in xattr. */
#define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */
/*
* HFS+ compression resource fork.
*/
#define RSRC_H_SIZE 260 /* Base size of Resource fork header. */
#define RSRC_F_SIZE 50 /* Size of Resource fork footer. */
/* Size to write compressed data to resource fork. */
#define COMPRESSED_W_SIZE (64 * 1024)
/* decmpfs difinitions. */
#define MAX_DECMPFS_XATTR_SIZE 3802
#ifndef DECMPFS_XATTR_NAME
#define DECMPFS_XATTR_NAME "com.apple.decmpfs"
#endif
#define DECMPFS_MAGIC 0x636d7066
#define DECMPFS_COMPRESSION_MAGIC 0
#define DECMPFS_COMPRESSION_TYPE 4
#define DECMPFS_UNCOMPRESSED_SIZE 8
#define DECMPFS_HEADER_SIZE 16
#define HFS_BLOCKS(s) ((s) >> 12)
static int check_symlinks(struct archive_write_disk *);
static int create_filesystem_object(struct archive_write_disk *);
static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
static void edit_deep_directories(struct archive_write_disk *ad);
#endif
static int cleanup_pathname(struct archive_write_disk *);
static int create_dir(struct archive_write_disk *, char *);
static int create_parent_dir(struct archive_write_disk *, char *);
static ssize_t hfs_write_data_block(struct archive_write_disk *,
const char *, size_t);
static int fixup_appledouble(struct archive_write_disk *, const char *);
static int older(struct stat *, struct archive_entry *);
static int restore_entry(struct archive_write_disk *);
static int set_mac_metadata(struct archive_write_disk *, const char *,
const void *, size_t);
static int set_xattrs(struct archive_write_disk *);
static int set_fflags(struct archive_write_disk *);
static int set_fflags_platform(struct archive_write_disk *, int fd,
const char *name, mode_t mode,
unsigned long fflags_set, unsigned long fflags_clear);
static int set_ownership(struct archive_write_disk *);
static int set_mode(struct archive_write_disk *, int mode);
static int set_time(int, int, const char *, time_t, long, time_t, long);
static int set_times(struct archive_write_disk *, int, int, const char *,
time_t, long, time_t, long, time_t, long, time_t, long);
static int set_times_from_entry(struct archive_write_disk *);
static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
static ssize_t write_data_block(struct archive_write_disk *,
const char *, size_t);
static struct archive_vtable *archive_write_disk_vtable(void);
static int _archive_write_disk_close(struct archive *);
static int _archive_write_disk_free(struct archive *);
static int _archive_write_disk_header(struct archive *, struct archive_entry *);
static int64_t _archive_write_disk_filter_bytes(struct archive *, int);
static int _archive_write_disk_finish_entry(struct archive *);
static ssize_t _archive_write_disk_data(struct archive *, const void *, size_t);
static ssize_t _archive_write_disk_data_block(struct archive *, const void *, size_t, int64_t);
static int
lazy_stat(struct archive_write_disk *a)
{
if (a->pst != NULL) {
/* Already have stat() data available. */
return (ARCHIVE_OK);
}
#ifdef HAVE_FSTAT
if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
a->pst = &a->st;
return (ARCHIVE_OK);
}
#endif
/*
* XXX At this point, symlinks should not be hit, otherwise
* XXX a race occurred. Do we want to check explicitly for that?
*/
if (lstat(a->name, &a->st) == 0) {
a->pst = &a->st;
return (ARCHIVE_OK);
}
archive_set_error(&a->archive, errno, "Couldn't stat file");
return (ARCHIVE_WARN);
}
static struct archive_vtable *
archive_write_disk_vtable(void)
{
static struct archive_vtable av;
static int inited = 0;
if (!inited) {
av.archive_close = _archive_write_disk_close;
av.archive_filter_bytes = _archive_write_disk_filter_bytes;
av.archive_free = _archive_write_disk_free;
av.archive_write_header = _archive_write_disk_header;
av.archive_write_finish_entry
= _archive_write_disk_finish_entry;
av.archive_write_data = _archive_write_disk_data;
av.archive_write_data_block = _archive_write_disk_data_block;
inited = 1;
}
return (&av);
}
static int64_t
_archive_write_disk_filter_bytes(struct archive *_a, int n)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
(void)n; /* UNUSED */
if (n == -1 || n == 0)
return (a->total_bytes_written);
return (-1);
}
int
archive_write_disk_set_options(struct archive *_a, int flags)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
a->flags = flags;
return (ARCHIVE_OK);
}
/*
* Extract this entry to disk.
*
* TODO: Validate hardlinks. According to the standards, we're
* supposed to check each extracted hardlink and squawk if it refers
* to a file that we didn't restore. I'm not entirely convinced this
* is a good idea, but more importantly: Is there any way to validate
* hardlinks without keeping a complete list of filenames from the
* entire archive?? Ugh.
*
*/
static int
_archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
struct fixup_entry *fe;
int ret, r;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
"archive_write_disk_header");
archive_clear_error(&a->archive);
if (a->archive.state & ARCHIVE_STATE_DATA) {
r = _archive_write_disk_finish_entry(&a->archive);
if (r == ARCHIVE_FATAL)
return (r);
}
/* Set up for this particular entry. */
a->pst = NULL;
a->current_fixup = NULL;
a->deferred = 0;
if (a->entry) {
archive_entry_free(a->entry);
a->entry = NULL;
}
a->entry = archive_entry_clone(entry);
a->fd = -1;
a->fd_offset = 0;
a->offset = 0;
a->restore_pwd = -1;
a->uid = a->user_uid;
a->mode = archive_entry_mode(a->entry);
if (archive_entry_size_is_set(a->entry))
a->filesize = archive_entry_size(a->entry);
else
a->filesize = -1;
archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
a->name = a->_name_data.s;
archive_clear_error(&a->archive);
/*
* Clean up the requested path. This is necessary for correct
* dir restores; the dir restore logic otherwise gets messed
* up by nonsense like "dir/.".
*/
ret = cleanup_pathname(a);
if (ret != ARCHIVE_OK)
return (ret);
/*
* Query the umask so we get predictable mode settings.
* This gets done on every call to _write_header in case the
* user edits their umask during the extraction for some
* reason.
*/
umask(a->user_umask = umask(0));
/* Figure out what we need to do for this entry. */
a->todo = TODO_MODE_BASE;
if (a->flags & ARCHIVE_EXTRACT_PERM) {
a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
/*
* SGID requires an extra "check" step because we
* cannot easily predict the GID that the system will
* assign. (Different systems assign GIDs to files
* based on a variety of criteria, including process
* credentials and the gid of the enclosing
* directory.) We can only restore the SGID bit if
* the file has the right GID, and we only know the
* GID if we either set it (see set_ownership) or if
* we've actually called stat() on the file after it
* was restored. Since there are several places at
* which we might verify the GID, we need a TODO bit
* to keep track.
*/
if (a->mode & S_ISGID)
a->todo |= TODO_SGID | TODO_SGID_CHECK;
/*
* Verifying the SUID is simpler, but can still be
* done in multiple ways, hence the separate "check" bit.
*/
if (a->mode & S_ISUID)
a->todo |= TODO_SUID | TODO_SUID_CHECK;
} else {
/*
* User didn't request full permissions, so don't
* restore SUID, SGID bits and obey umask.
*/
a->mode &= ~S_ISUID;
a->mode &= ~S_ISGID;
a->mode &= ~S_ISVTX;
a->mode &= ~a->user_umask;
}
if (a->flags & ARCHIVE_EXTRACT_OWNER)
a->todo |= TODO_OWNER;
if (a->flags & ARCHIVE_EXTRACT_TIME)
a->todo |= TODO_TIMES;
if (a->flags & ARCHIVE_EXTRACT_ACL) {
if (archive_entry_filetype(a->entry) == AE_IFDIR)
a->deferred |= TODO_ACLS;
else
a->todo |= TODO_ACLS;
}
if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
if (archive_entry_filetype(a->entry) == AE_IFDIR)
a->deferred |= TODO_MAC_METADATA;
else
a->todo |= TODO_MAC_METADATA;
}
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
unsigned long set, clear;
archive_entry_fflags(a->entry, &set, &clear);
if ((set & ~clear) & UF_COMPRESSED) {
a->todo |= TODO_HFS_COMPRESSION;
a->decmpfs_block_count = (unsigned)-1;
}
}
if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
(a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
a->todo |= TODO_HFS_COMPRESSION;
a->decmpfs_block_count = (unsigned)-1;
}
{
const char *p;
/* Check if the current file name is a type of the
* resource fork file. */
p = strrchr(a->name, '/');
if (p == NULL)
p = a->name;
else
p++;
if (p[0] == '.' && p[1] == '_') {
/* Do not compress "._XXX" files. */
a->todo &= ~TODO_HFS_COMPRESSION;
if (a->filesize > 0)
a->todo |= TODO_APPLEDOUBLE;
}
}
#endif
if (a->flags & ARCHIVE_EXTRACT_XATTR)
a->todo |= TODO_XATTR;
if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
a->todo |= TODO_FFLAGS;
if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
ret = check_symlinks(a);
if (ret != ARCHIVE_OK)
return (ret);
}
#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
/* If path exceeds PATH_MAX, shorten the path. */
edit_deep_directories(a);
#endif
ret = restore_entry(a);
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
/*
* Check if the filesystem the file is restoring on supports
* HFS+ Compression. If not, cancel HFS+ Compression.
*/
if (a->todo | TODO_HFS_COMPRESSION) {
/*
* NOTE: UF_COMPRESSED is ignored even if the filesystem
* supports HFS+ Compression because the file should
* have at least an extended attriute "com.apple.decmpfs"
* before the flag is set to indicate that the file have
* been compressed. If hte filesystem does not support
* HFS+ Compression the system call will fail.
*/
if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
a->todo &= ~TODO_HFS_COMPRESSION;
}
#endif
/*
* TODO: There are rumours that some extended attributes must
* be restored before file data is written. If this is true,
* then we either need to write all extended attributes both
* before and after restoring the data, or find some rule for
* determining which must go first and which last. Due to the
* many ways people are using xattrs, this may prove to be an
* intractable problem.
*/
#ifdef HAVE_FCHDIR
/* If we changed directory above, restore it here. */
if (a->restore_pwd >= 0) {
r = fchdir(a->restore_pwd);
if (r != 0) {
archive_set_error(&a->archive, errno, "chdir() failure");
ret = ARCHIVE_FATAL;
}
close(a->restore_pwd);
a->restore_pwd = -1;
}
#endif
/*
* Fixup uses the unedited pathname from archive_entry_pathname(),
* because it is relative to the base dir and the edited path
* might be relative to some intermediate dir as a result of the
* deep restore logic.
*/
if (a->deferred & TODO_MODE) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->fixup |= TODO_MODE_BASE;
fe->mode = a->mode;
}
if ((a->deferred & TODO_TIMES)
&& (archive_entry_mtime_is_set(entry)
|| archive_entry_atime_is_set(entry))) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->mode = a->mode;
fe->fixup |= TODO_TIMES;
if (archive_entry_atime_is_set(entry)) {
fe->atime = archive_entry_atime(entry);
fe->atime_nanos = archive_entry_atime_nsec(entry);
} else {
/* If atime is unset, use start time. */
fe->atime = a->start_time;
fe->atime_nanos = 0;
}
if (archive_entry_mtime_is_set(entry)) {
fe->mtime = archive_entry_mtime(entry);
fe->mtime_nanos = archive_entry_mtime_nsec(entry);
} else {
/* If mtime is unset, use start time. */
fe->mtime = a->start_time;
fe->mtime_nanos = 0;
}
if (archive_entry_birthtime_is_set(entry)) {
fe->birthtime = archive_entry_birthtime(entry);
fe->birthtime_nanos = archive_entry_birthtime_nsec(entry);
} else {
/* If birthtime is unset, use mtime. */
fe->birthtime = fe->mtime;
fe->birthtime_nanos = fe->mtime_nanos;
}
}
if (a->deferred & TODO_ACLS) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->fixup |= TODO_ACLS;
archive_acl_copy(&fe->acl, archive_entry_acl(entry));
}
if (a->deferred & TODO_MAC_METADATA) {
const void *metadata;
size_t metadata_size;
metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
if (metadata != NULL && metadata_size > 0) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->mac_metadata = malloc(metadata_size);
if (fe->mac_metadata != NULL) {
memcpy(fe->mac_metadata, metadata, metadata_size);
fe->mac_metadata_size = metadata_size;
fe->fixup |= TODO_MAC_METADATA;
}
}
}
if (a->deferred & TODO_FFLAGS) {
fe = current_fixup(a, archive_entry_pathname(entry));
if (fe == NULL)
return (ARCHIVE_FATAL);
fe->fixup |= TODO_FFLAGS;
/* TODO: Complete this.. defer fflags from below. */
}
/* We've created the object and are ready to pour data into it. */
if (ret >= ARCHIVE_WARN)
a->archive.state = ARCHIVE_STATE_DATA;
/*
* If it's not open, tell our client not to try writing.
* In particular, dirs, links, etc, don't get written to.
*/
if (a->fd < 0) {
archive_entry_set_size(entry, 0);
a->filesize = 0;
}
return (ret);
}
int
archive_write_disk_set_skip_file(struct archive *_a, int64_t d, int64_t i)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
a->skip_file_set = 1;
a->skip_file_dev = d;
a->skip_file_ino = i;
return (ARCHIVE_OK);
}
static ssize_t
write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
{
uint64_t start_size = size;
ssize_t bytes_written = 0;
ssize_t block_size = 0, bytes_to_write;
if (size == 0)
return (ARCHIVE_OK);
if (a->filesize == 0 || a->fd < 0) {
archive_set_error(&a->archive, 0,
"Attempt to write to an empty file");
return (ARCHIVE_WARN);
}
if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
#if HAVE_STRUCT_STAT_ST_BLKSIZE
int r;
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
block_size = a->pst->st_blksize;
#else
/* XXX TODO XXX Is there a more appropriate choice here ? */
/* This needn't match the filesystem allocation size. */
block_size = 16*1024;
#endif
}
/* If this write would run beyond the file size, truncate it. */
if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
start_size = size = (size_t)(a->filesize - a->offset);
/* Write the data. */
while (size > 0) {
if (block_size == 0) {
bytes_to_write = size;
} else {
/* We're sparsifying the file. */
const char *p, *end;
int64_t block_end;
/* Skip leading zero bytes. */
for (p = buff, end = buff + size; p < end; ++p) {
if (*p != '\0')
break;
}
a->offset += p - buff;
size -= p - buff;
buff = p;
if (size == 0)
break;
/* Calculate next block boundary after offset. */
block_end
= (a->offset / block_size + 1) * block_size;
/* If the adjusted write would cross block boundary,
* truncate it to the block boundary. */
bytes_to_write = size;
if (a->offset + bytes_to_write > block_end)
bytes_to_write = block_end - a->offset;
}
/* Seek if necessary to the specified offset. */
if (a->offset != a->fd_offset) {
if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
archive_set_error(&a->archive, errno,
"Seek failed");
return (ARCHIVE_FATAL);
}
a->fd_offset = a->offset;
}
bytes_written = write(a->fd, buff, bytes_to_write);
if (bytes_written < 0) {
archive_set_error(&a->archive, errno, "Write failed");
return (ARCHIVE_WARN);
}
buff += bytes_written;
size -= bytes_written;
a->total_bytes_written += bytes_written;
a->offset += bytes_written;
a->fd_offset = a->offset;
}
return (start_size - size);
}
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
&& defined(HAVE_ZLIB_H)
/*
* Set UF_COMPRESSED file flag.
* This have to be called after hfs_write_decmpfs() because if the
* file does not have "com.apple.decmpfs" xattr the flag is ignored.
*/
static int
hfs_set_compressed_fflag(struct archive_write_disk *a)
{
int r;
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
a->st.st_flags |= UF_COMPRESSED;
if (fchflags(a->fd, a->st.st_flags) != 0) {
archive_set_error(&a->archive, errno,
"Failed to set UF_COMPRESSED file flag");
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
/*
* HFS+ Compression decmpfs
*
* +------------------------------+ +0
* | Magic(LE 4 bytes) |
* +------------------------------+
* | Type(LE 4 bytes) |
* +------------------------------+
* | Uncompressed size(LE 8 bytes)|
* +------------------------------+ +16
* | |
* | Compressed data |
* | (Placed only if Type == 3) |
* | |
* +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE
*
* Type is 3: decmpfs has compressed data.
* Type is 4: Resource Fork has compressed data.
*/
/*
* Write "com.apple.decmpfs"
*/
static int
hfs_write_decmpfs(struct archive_write_disk *a)
{
int r;
uint32_t compression_type;
r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
a->decmpfs_attr_size, 0, 0);
if (r < 0) {
archive_set_error(&a->archive, errno,
"Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
compression_type = archive_le32dec(
&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
if (compression_type == CMP_RESOURCE_FORK)
fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
XATTR_SHOWCOMPRESSION);
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
/*
* HFS+ Compression Resource Fork
*
* +-----------------------------+
* | Header(260 bytes) |
* +-----------------------------+
* | Block count(LE 4 bytes) |
* +-----------------------------+ --+
* +-- | Offset (LE 4 bytes) | |
* | | [distance from Block count] | | Block 0
* | +-----------------------------+ |
* | | Compressed size(LE 4 bytes) | |
* | +-----------------------------+ --+
* | | |
* | | .................. |
* | | |
* | +-----------------------------+ --+
* | | Offset (LE 4 bytes) | |
* | +-----------------------------+ | Block (Block count -1)
* | | Compressed size(LE 4 bytes) | |
* +-> +-----------------------------+ --+
* | Compressed data(n bytes) | Block 0
* +-----------------------------+
* | |
* | .................. |
* | |
* +-----------------------------+
* | Compressed data(n bytes) | Block (Block count -1)
* +-----------------------------+
* | Footer(50 bytes) |
* +-----------------------------+
*
*/
/*
* Write the header of "com.apple.ResourceFork"
*/
static int
hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
size_t bytes, uint32_t position)
{
int ret;
ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
position, a->rsrc_xattr_options);
if (ret < 0) {
archive_set_error(&a->archive, errno,
"Cannot restore xattr: %s at %u pos %u bytes",
XATTR_RESOURCEFORK_NAME,
(unsigned)position,
(unsigned)bytes);
return (ARCHIVE_WARN);
}
a->rsrc_xattr_options &= ~XATTR_CREATE;
return (ARCHIVE_OK);
}
static int
hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
{
int ret;
ret = hfs_write_resource_fork(a, a->compressed_buffer,
bytes_compressed, a->compressed_rsrc_position);
if (ret == ARCHIVE_OK)
a->compressed_rsrc_position += bytes_compressed;
return (ret);
}
static int
hfs_write_resource_fork_header(struct archive_write_disk *a)
{
unsigned char *buff;
uint32_t rsrc_bytes;
uint32_t rsrc_header_bytes;
/*
* Write resource fork header + block info.
*/
buff = a->resource_fork;
rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
rsrc_header_bytes =
RSRC_H_SIZE + /* Header base size. */
4 + /* Block count. */
(a->decmpfs_block_count * 8);/* Block info */
archive_be32enc(buff, 0x100);
archive_be32enc(buff + 4, rsrc_bytes);
archive_be32enc(buff + 8, rsrc_bytes - 256);
archive_be32enc(buff + 12, 0x32);
memset(buff + 16, 0, 240);
archive_be32enc(buff + 256, rsrc_bytes - 260);
return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
}
static size_t
hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
{
static const char rsrc_footer[RSRC_F_SIZE] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm',
'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00
};
if (buff_size < sizeof(rsrc_footer))
return (0);
memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
return (sizeof(rsrc_footer));
}
static int
hfs_reset_compressor(struct archive_write_disk *a)
{
int ret;
if (a->stream_valid)
ret = deflateReset(&a->stream);
else
ret = deflateInit(&a->stream, a->decmpfs_compression_level);
if (ret != Z_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to initialize compressor");
return (ARCHIVE_FATAL);
} else
a->stream_valid = 1;
return (ARCHIVE_OK);
}
static int
hfs_decompress(struct archive_write_disk *a)
{
uint32_t *block_info;
unsigned int block_count;
uint32_t data_pos, data_size;
ssize_t r;
ssize_t bytes_written, bytes_to_write;
unsigned char *b;
block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
block_count = archive_le32dec(block_info++);
while (block_count--) {
data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
data_size = archive_le32dec(block_info++);
r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
a->compressed_buffer, data_size, data_pos, 0);
if (r != data_size) {
archive_set_error(&a->archive,
(r < 0)?errno:ARCHIVE_ERRNO_MISC,
"Failed to read resource fork");
return (ARCHIVE_WARN);
}
if (a->compressed_buffer[0] == 0xff) {
bytes_to_write = data_size -1;
b = a->compressed_buffer + 1;
} else {
uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
int zr;
zr = uncompress((Bytef *)a->uncompressed_buffer,
&dest_len, a->compressed_buffer, data_size);
if (zr != Z_OK) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Failed to decompress resource fork");
return (ARCHIVE_WARN);
}
bytes_to_write = dest_len;
b = (unsigned char *)a->uncompressed_buffer;
}
do {
bytes_written = write(a->fd, b, bytes_to_write);
if (bytes_written < 0) {
archive_set_error(&a->archive, errno,
"Write failed");
return (ARCHIVE_WARN);
}
bytes_to_write -= bytes_written;
b += bytes_written;
} while (bytes_to_write > 0);
}
r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
if (r == -1) {
archive_set_error(&a->archive, errno,
"Failed to remove resource fork");
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
static int
hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
size_t size)
{
unsigned char *buffer_compressed;
size_t bytes_compressed;
size_t bytes_used;
int ret;
ret = hfs_reset_compressor(a);
if (ret != ARCHIVE_OK)
return (ret);
if (a->compressed_buffer == NULL) {
size_t block_size;
block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
+ compressBound(MAX_DECMPFS_BLOCK_SIZE);
a->compressed_buffer = malloc(block_size);
if (a->compressed_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Resource Fork");
return (ARCHIVE_FATAL);
}
a->compressed_buffer_size = block_size;
a->compressed_buffer_remaining = block_size;
}
buffer_compressed = a->compressed_buffer +
a->compressed_buffer_size - a->compressed_buffer_remaining;
a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
a->stream.avail_in = size;
a->stream.next_out = buffer_compressed;
a->stream.avail_out = a->compressed_buffer_remaining;
do {
ret = deflate(&a->stream, Z_FINISH);
switch (ret) {
case Z_OK:
case Z_STREAM_END:
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to compress data");
return (ARCHIVE_FAILED);
}
} while (ret == Z_OK);
bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
/*
* If the compressed size is larger than the original size,
* throw away compressed data, use uncompressed data instead.
*/
if (bytes_compressed > size) {
buffer_compressed[0] = 0xFF;/* uncompressed marker. */
memcpy(buffer_compressed + 1, buff, size);
bytes_compressed = size + 1;
}
a->compressed_buffer_remaining -= bytes_compressed;
/*
* If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
* and the block count in the file is only one, store compressed
* data to decmpfs xattr instead of the resource fork.
*/
if (a->decmpfs_block_count == 1 &&
(a->decmpfs_attr_size + bytes_compressed)
<= MAX_DECMPFS_XATTR_SIZE) {
archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
CMP_XATTR);
memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
buffer_compressed, bytes_compressed);
a->decmpfs_attr_size += bytes_compressed;
a->compressed_buffer_remaining = a->compressed_buffer_size;
/*
* Finish HFS+ Compression.
* - Write the decmpfs xattr.
* - Set the UF_COMPRESSED file flag.
*/
ret = hfs_write_decmpfs(a);
if (ret == ARCHIVE_OK)
ret = hfs_set_compressed_fflag(a);
return (ret);
}
/* Update block info. */
archive_le32enc(a->decmpfs_block_info++,
a->compressed_rsrc_position_v - RSRC_H_SIZE);
archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
a->compressed_rsrc_position_v += bytes_compressed;
/*
* Write the compressed data to the resource fork.
*/
bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
while (bytes_used >= COMPRESSED_W_SIZE) {
ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
if (ret != ARCHIVE_OK)
return (ret);
bytes_used -= COMPRESSED_W_SIZE;
if (bytes_used > COMPRESSED_W_SIZE)
memmove(a->compressed_buffer,
a->compressed_buffer + COMPRESSED_W_SIZE,
bytes_used);
else
memcpy(a->compressed_buffer,
a->compressed_buffer + COMPRESSED_W_SIZE,
bytes_used);
}
a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
/*
* If the current block is the last block, write the remaining
* compressed data and the resource fork footer.
*/
if (a->file_remaining_bytes == 0) {
size_t rsrc_size;
int64_t bk;
/* Append the resource footer. */
rsrc_size = hfs_set_resource_fork_footer(
a->compressed_buffer + bytes_used,
a->compressed_buffer_remaining);
ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
a->compressed_buffer_remaining = a->compressed_buffer_size;
/* If the compressed size is not enouph smaller than
* the uncompressed size. cancel HFS+ compression.
* TODO: study a behavior of ditto utility and improve
* the condition to fall back into no HFS+ compression. */
bk = HFS_BLOCKS(a->compressed_rsrc_position);
bk += bk >> 7;
if (bk > HFS_BLOCKS(a->filesize))
return hfs_decompress(a);
/*
* Write the resourcefork header.
*/
if (ret == ARCHIVE_OK)
ret = hfs_write_resource_fork_header(a);
/*
* Finish HFS+ Compression.
* - Write the decmpfs xattr.
* - Set the UF_COMPRESSED file flag.
*/
if (ret == ARCHIVE_OK)
ret = hfs_write_decmpfs(a);
if (ret == ARCHIVE_OK)
ret = hfs_set_compressed_fflag(a);
}
return (ret);
}
static ssize_t
hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
size_t size)
{
const char *buffer_to_write;
size_t bytes_to_write;
int ret;
if (a->decmpfs_block_count == (unsigned)-1) {
void *new_block;
size_t new_size;
unsigned int block_count;
if (a->decmpfs_header_p == NULL) {
new_block = malloc(MAX_DECMPFS_XATTR_SIZE
+ sizeof(uint32_t));
if (new_block == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for decmpfs");
return (ARCHIVE_FATAL);
}
a->decmpfs_header_p = new_block;
}
a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
DECMPFS_MAGIC);
archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
CMP_RESOURCE_FORK);
archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
a->filesize);
/* Calculate a block count of the file. */
block_count =
(a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
MAX_DECMPFS_BLOCK_SIZE;
/*
* Allocate buffer for resource fork.
* Set up related pointers;
*/
new_size =
RSRC_H_SIZE + /* header */
4 + /* Block count */
(block_count * sizeof(uint32_t) * 2) +
RSRC_F_SIZE; /* footer */
if (new_size > a->resource_fork_allocated_size) {
new_block = realloc(a->resource_fork, new_size);
if (new_block == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for ResourceFork");
return (ARCHIVE_FATAL);
}
a->resource_fork_allocated_size = new_size;
a->resource_fork = new_block;
}
/* Allocate uncompressed buffer */
if (a->uncompressed_buffer == NULL) {
new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
if (new_block == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for decmpfs");
return (ARCHIVE_FATAL);
}
a->uncompressed_buffer = new_block;
}
a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
a->file_remaining_bytes = a->filesize;
a->compressed_buffer_remaining = a->compressed_buffer_size;
/*
* Set up a resource fork.
*/
a->rsrc_xattr_options = XATTR_CREATE;
/* Get the position where we are going to set a bunch
* of block info. */
a->decmpfs_block_info =
(uint32_t *)(a->resource_fork + RSRC_H_SIZE);
/* Set the block count to the resource fork. */
archive_le32enc(a->decmpfs_block_info++, block_count);
/* Get the position where we are goint to set compressed
* data. */
a->compressed_rsrc_position =
RSRC_H_SIZE + 4 + (block_count * 8);
a->compressed_rsrc_position_v = a->compressed_rsrc_position;
a->decmpfs_block_count = block_count;
}
/* Ignore redundant bytes. */
if (a->file_remaining_bytes == 0)
return ((ssize_t)size);
/* Do not overrun a block size. */
if (size > a->block_remaining_bytes)
bytes_to_write = a->block_remaining_bytes;
else
bytes_to_write = size;
/* Do not overrun the file size. */
if (bytes_to_write > a->file_remaining_bytes)
bytes_to_write = a->file_remaining_bytes;
/* For efficiency, if a copy length is full of the uncompressed
* buffer size, do not copy writing data to it. */
if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
buffer_to_write = buff;
else {
memcpy(a->uncompressed_buffer +
MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
buff, bytes_to_write);
buffer_to_write = a->uncompressed_buffer;
}
a->block_remaining_bytes -= bytes_to_write;
a->file_remaining_bytes -= bytes_to_write;
if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
ret = hfs_drive_compressor(a, buffer_to_write,
MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
if (ret < 0)
return (ret);
a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
}
/* Ignore redundant bytes. */
if (a->file_remaining_bytes == 0)
return ((ssize_t)size);
return (bytes_to_write);
}
static ssize_t
hfs_write_data_block(struct archive_write_disk *a, const char *buff,
size_t size)
{
uint64_t start_size = size;
ssize_t bytes_written = 0;
ssize_t bytes_to_write;
if (size == 0)
return (ARCHIVE_OK);
if (a->filesize == 0 || a->fd < 0) {
archive_set_error(&a->archive, 0,
"Attempt to write to an empty file");
return (ARCHIVE_WARN);
}
/* If this write would run beyond the file size, truncate it. */
if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
start_size = size = (size_t)(a->filesize - a->offset);
/* Write the data. */
while (size > 0) {
bytes_to_write = size;
/* Seek if necessary to the specified offset. */
if (a->offset < a->fd_offset) {
/* Can't support backword move. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Seek failed");
return (ARCHIVE_FATAL);
} else if (a->offset > a->fd_offset) {
int64_t skip = a->offset - a->fd_offset;
char nullblock[1024];
memset(nullblock, 0, sizeof(nullblock));
while (skip > 0) {
if (skip > (int64_t)sizeof(nullblock))
bytes_written = hfs_write_decmpfs_block(
a, nullblock, sizeof(nullblock));
else
bytes_written = hfs_write_decmpfs_block(
a, nullblock, skip);
if (bytes_written < 0) {
archive_set_error(&a->archive, errno,
"Write failed");
return (ARCHIVE_WARN);
}
skip -= bytes_written;
}
a->fd_offset = a->offset;
}
bytes_written =
hfs_write_decmpfs_block(a, buff, bytes_to_write);
if (bytes_written < 0)
return (bytes_written);
buff += bytes_written;
size -= bytes_written;
a->total_bytes_written += bytes_written;
a->offset += bytes_written;
a->fd_offset = a->offset;
}
return (start_size - size);
}
#else
static ssize_t
hfs_write_data_block(struct archive_write_disk *a, const char *buff,
size_t size)
{
return (write_data_block(a, buff, size));
}
#endif
static ssize_t
_archive_write_disk_data_block(struct archive *_a,
const void *buff, size_t size, int64_t offset)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
ssize_t r;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_DATA, "archive_write_data_block");
a->offset = offset;
if (a->todo & TODO_HFS_COMPRESSION)
r = hfs_write_data_block(a, buff, size);
else
r = write_data_block(a, buff, size);
if (r < ARCHIVE_OK)
return (r);
if ((size_t)r < size) {
archive_set_error(&a->archive, 0,
"Write request too large");
return (ARCHIVE_WARN);
}
#if ARCHIVE_VERSION_NUMBER < 3999000
return (ARCHIVE_OK);
#else
return (size);
#endif
}
static ssize_t
_archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_DATA, "archive_write_data");
if (a->todo & TODO_HFS_COMPRESSION)
return (hfs_write_data_block(a, buff, size));
return (write_data_block(a, buff, size));
}
static int
_archive_write_disk_finish_entry(struct archive *_a)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
int ret = ARCHIVE_OK;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
"archive_write_finish_entry");
if (a->archive.state & ARCHIVE_STATE_HEADER)
return (ARCHIVE_OK);
archive_clear_error(&a->archive);
/* Pad or truncate file to the right size. */
if (a->fd < 0) {
/* There's no file. */
} else if (a->filesize < 0) {
/* File size is unknown, so we can't set the size. */
} else if (a->fd_offset == a->filesize) {
/* Last write ended at exactly the filesize; we're done. */
/* Hopefully, this is the common case. */
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
} else if (a->todo & TODO_HFS_COMPRESSION) {
char null_d[1024];
ssize_t r;
if (a->file_remaining_bytes)
memset(null_d, 0, sizeof(null_d));
while (a->file_remaining_bytes) {
if (a->file_remaining_bytes > sizeof(null_d))
r = hfs_write_data_block(
a, null_d, sizeof(null_d));
else
r = hfs_write_data_block(
a, null_d, a->file_remaining_bytes);
if (r < 0)
return ((int)r);
}
#endif
} else {
#if HAVE_FTRUNCATE
if (ftruncate(a->fd, a->filesize) == -1 &&
a->filesize == 0) {
archive_set_error(&a->archive, errno,
"File size could not be restored");
return (ARCHIVE_FAILED);
}
#endif
/*
* Not all platforms implement the XSI option to
* extend files via ftruncate. Stat() the file again
* to see what happened.
*/
a->pst = NULL;
if ((ret = lazy_stat(a)) != ARCHIVE_OK)
return (ret);
/* We can use lseek()/write() to extend the file if
* ftruncate didn't work or isn't available. */
if (a->st.st_size < a->filesize) {
const char nul = '\0';
if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
archive_set_error(&a->archive, errno,
"Seek failed");
return (ARCHIVE_FATAL);
}
if (write(a->fd, &nul, 1) < 0) {
archive_set_error(&a->archive, errno,
"Write to restore size failed");
return (ARCHIVE_FATAL);
}
a->pst = NULL;
}
}
/* Restore metadata. */
/*
* This is specific to Mac OS X.
* If the current file is an AppleDouble file, it should be
* linked with the data fork file and remove it.
*/
if (a->todo & TODO_APPLEDOUBLE) {
int r2 = fixup_appledouble(a, a->name);
if (r2 == ARCHIVE_EOF) {
/* The current file has been successfully linked
* with the data fork file and removed. So there
* is nothing to do on the current file. */
goto finish_metadata;
}
if (r2 < ret) ret = r2;
}
/*
* Look up the "real" UID only if we're going to need it.
* TODO: the TODO_SGID condition can be dropped here, can't it?
*/
if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
a->uid = archive_write_disk_uid(&a->archive,
archive_entry_uname(a->entry),
archive_entry_uid(a->entry));
}
/* Look up the "real" GID only if we're going to need it. */
/* TODO: the TODO_SUID condition can be dropped here, can't it? */
if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
a->gid = archive_write_disk_gid(&a->archive,
archive_entry_gname(a->entry),
archive_entry_gid(a->entry));
}
/*
* Restore ownership before set_mode tries to restore suid/sgid
* bits. If we set the owner, we know what it is and can skip
* a stat() call to examine the ownership of the file on disk.
*/
if (a->todo & TODO_OWNER) {
int r2 = set_ownership(a);
if (r2 < ret) ret = r2;
}
/*
* set_mode must precede ACLs on systems such as Solaris and
* FreeBSD where setting the mode implicitly clears extended ACLs
*/
if (a->todo & TODO_MODE) {
int r2 = set_mode(a, a->mode);
if (r2 < ret) ret = r2;
}
/*
* Security-related extended attributes (such as
* security.capability on Linux) have to be restored last,
* since they're implicitly removed by other file changes.
*/
if (a->todo & TODO_XATTR) {
int r2 = set_xattrs(a);
if (r2 < ret) ret = r2;
}
/*
* Some flags prevent file modification; they must be restored after
* file contents are written.
*/
if (a->todo & TODO_FFLAGS) {
int r2 = set_fflags(a);
if (r2 < ret) ret = r2;
}
/*
* Time must follow most other metadata;
* otherwise atime will get changed.
*/
if (a->todo & TODO_TIMES) {
int r2 = set_times_from_entry(a);
if (r2 < ret) ret = r2;
}
/*
* Mac extended metadata includes ACLs.
*/
if (a->todo & TODO_MAC_METADATA) {
const void *metadata;
size_t metadata_size;
metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
if (metadata != NULL && metadata_size > 0) {
int r2 = set_mac_metadata(a, archive_entry_pathname(
a->entry), metadata, metadata_size);
if (r2 < ret) ret = r2;
}
}
/*
* ACLs must be restored after timestamps because there are
* ACLs that prevent attribute changes (including time).
*/
if (a->todo & TODO_ACLS) {
int r2 = archive_write_disk_set_acls(&a->archive, a->fd,
archive_entry_pathname(a->entry),
archive_entry_acl(a->entry));
if (r2 < ret) ret = r2;
}
finish_metadata:
/* If there's an fd, we can close it now. */
if (a->fd >= 0) {
close(a->fd);
a->fd = -1;
}
/* If there's an entry, we can release it now. */
if (a->entry) {
archive_entry_free(a->entry);
a->entry = NULL;
}
a->archive.state = ARCHIVE_STATE_HEADER;
return (ret);
}
int
archive_write_disk_set_group_lookup(struct archive *_a,
void *private_data,
int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid),
void (*cleanup_gid)(void *private))
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
(a->cleanup_gid)(a->lookup_gid_data);
a->lookup_gid = lookup_gid;
a->cleanup_gid = cleanup_gid;
a->lookup_gid_data = private_data;
return (ARCHIVE_OK);
}
int
archive_write_disk_set_user_lookup(struct archive *_a,
void *private_data,
int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
void (*cleanup_uid)(void *private))
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
(a->cleanup_uid)(a->lookup_uid_data);
a->lookup_uid = lookup_uid;
a->cleanup_uid = cleanup_uid;
a->lookup_uid_data = private_data;
return (ARCHIVE_OK);
}
int64_t
archive_write_disk_gid(struct archive *_a, const char *name, int64_t id)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_gid");
if (a->lookup_gid)
return (a->lookup_gid)(a->lookup_gid_data, name, id);
return (id);
}
int64_t
archive_write_disk_uid(struct archive *_a, const char *name, int64_t id)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY, "archive_write_disk_uid");
if (a->lookup_uid)
return (a->lookup_uid)(a->lookup_uid_data, name, id);
return (id);
}
/*
* Create a new archive_write_disk object and initialize it with global state.
*/
struct archive *
archive_write_disk_new(void)
{
struct archive_write_disk *a;
a = (struct archive_write_disk *)malloc(sizeof(*a));
if (a == NULL)
return (NULL);
memset(a, 0, sizeof(*a));
a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
/* We're ready to write a header immediately. */
a->archive.state = ARCHIVE_STATE_HEADER;
a->archive.vtable = archive_write_disk_vtable();
a->start_time = time(NULL);
/* Query and restore the umask. */
umask(a->user_umask = umask(0));
#ifdef HAVE_GETEUID
a->user_uid = geteuid();
#endif /* HAVE_GETEUID */
if (archive_string_ensure(&a->path_safe, 512) == NULL) {
free(a);
return (NULL);
}
#ifdef HAVE_ZLIB_H
a->decmpfs_compression_level = 5;
#endif
return (&a->archive);
}
/*
* If pathname is longer than PATH_MAX, chdir to a suitable
* intermediate dir and edit the path down to a shorter suffix. Note
* that this routine never returns an error; if the chdir() attempt
* fails for any reason, we just go ahead with the long pathname. The
* object creation is likely to fail, but any error will get handled
* at that time.
*/
#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
static void
edit_deep_directories(struct archive_write_disk *a)
{
int ret;
char *tail = a->name;
/* If path is short, avoid the open() below. */
if (strlen(tail) <= PATH_MAX)
return;
/* Try to record our starting dir. */
a->restore_pwd = open(".", O_RDONLY | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(a->restore_pwd);
if (a->restore_pwd < 0)
return;
/* As long as the path is too long... */
while (strlen(tail) > PATH_MAX) {
/* Locate a dir prefix shorter than PATH_MAX. */
tail += PATH_MAX - 8;
while (tail > a->name && *tail != '/')
tail--;
/* Exit if we find a too-long path component. */
if (tail <= a->name)
return;
/* Create the intermediate dir and chdir to it. */
*tail = '\0'; /* Terminate dir portion */
ret = create_dir(a, a->name);
if (ret == ARCHIVE_OK && chdir(a->name) != 0)
ret = ARCHIVE_FAILED;
*tail = '/'; /* Restore the / we removed. */
if (ret != ARCHIVE_OK)
return;
tail++;
/* The chdir() succeeded; we've now shortened the path. */
a->name = tail;
}
return;
}
#endif
/*
* The main restore function.
*/
static int
restore_entry(struct archive_write_disk *a)
{
int ret = ARCHIVE_OK, en;
if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
/*
* TODO: Fix this. Apparently, there are platforms
* that still allow root to hose the entire filesystem
* by unlinking a dir. The S_ISDIR() test above
* prevents us from using unlink() here if the new
* object is a dir, but that doesn't mean the old
* object isn't a dir.
*/
if (unlink(a->name) == 0) {
/* We removed it, reset cached stat. */
a->pst = NULL;
} else if (errno == ENOENT) {
/* File didn't exist, that's just as good. */
} else if (rmdir(a->name) == 0) {
/* It was a dir, but now it's gone. */
a->pst = NULL;
} else {
/* We tried, but couldn't get rid of it. */
archive_set_error(&a->archive, errno,
"Could not unlink");
return(ARCHIVE_FAILED);
}
}
/* Try creating it first; if this fails, we'll try to recover. */
en = create_filesystem_object(a);
if ((en == ENOTDIR || en == ENOENT)
&& !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
/* If the parent dir doesn't exist, try creating it. */
create_parent_dir(a, a->name);
/* Now try to create the object again. */
en = create_filesystem_object(a);
}
if ((en == EISDIR || en == EEXIST)
&& (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
/* If we're not overwriting, we're done. */
archive_entry_unset_size(a->entry);
return (ARCHIVE_OK);
}
/*
* Some platforms return EISDIR if you call
* open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
* return EEXIST. POSIX is ambiguous, requiring EISDIR
* for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
* on an existing item.
*/
if (en == EISDIR) {
/* A dir is in the way of a non-dir, rmdir it. */
if (rmdir(a->name) != 0) {
archive_set_error(&a->archive, errno,
"Can't remove already-existing dir");
return (ARCHIVE_FAILED);
}
a->pst = NULL;
/* Try again. */
en = create_filesystem_object(a);
} else if (en == EEXIST) {
/*
* We know something is in the way, but we don't know what;
* we need to find out before we go any further.
*/
int r = 0;
/*
* The SECURE_SYMLINKS logic has already removed a
* symlink to a dir if the client wants that. So
* follow the symlink if we're creating a dir.
*/
if (S_ISDIR(a->mode))
r = stat(a->name, &a->st);
/*
* If it's not a dir (or it's a broken symlink),
* then don't follow it.
*/
if (r != 0 || !S_ISDIR(a->mode))
r = lstat(a->name, &a->st);
if (r != 0) {
archive_set_error(&a->archive, errno,
"Can't stat existing object");
return (ARCHIVE_FAILED);
}
/*
* NO_OVERWRITE_NEWER doesn't apply to directories.
*/
if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
&& !S_ISDIR(a->st.st_mode)) {
if (!older(&(a->st), a->entry)) {
archive_entry_unset_size(a->entry);
return (ARCHIVE_OK);
}
}
/* If it's our archive, we're done. */
if (a->skip_file_set &&
a->st.st_dev == (dev_t)a->skip_file_dev &&
a->st.st_ino == (ino_t)a->skip_file_ino) {
archive_set_error(&a->archive, 0,
"Refusing to overwrite archive");
return (ARCHIVE_FAILED);
}
if (!S_ISDIR(a->st.st_mode)) {
/* A non-dir is in the way, unlink it. */
if (unlink(a->name) != 0) {
archive_set_error(&a->archive, errno,
"Can't unlink already-existing object");
return (ARCHIVE_FAILED);
}
a->pst = NULL;
/* Try again. */
en = create_filesystem_object(a);
} else if (!S_ISDIR(a->mode)) {
/* A dir is in the way of a non-dir, rmdir it. */
if (rmdir(a->name) != 0) {
archive_set_error(&a->archive, errno,
"Can't replace existing directory with non-directory");
return (ARCHIVE_FAILED);
}
/* Try again. */
en = create_filesystem_object(a);
} else {
/*
* There's a dir in the way of a dir. Don't
* waste time with rmdir()/mkdir(), just fix
* up the permissions on the existing dir.
* Note that we don't change perms on existing
* dirs unless _EXTRACT_PERM is specified.
*/
if ((a->mode != a->st.st_mode)
&& (a->todo & TODO_MODE_FORCE))
a->deferred |= (a->todo & TODO_MODE);
/* Ownership doesn't need deferred fixup. */
en = 0; /* Forget the EEXIST. */
}
}
if (en) {
/* Everything failed; give up here. */
archive_set_error(&a->archive, en, "Can't create '%s'",
a->name);
return (ARCHIVE_FAILED);
}
a->pst = NULL; /* Cached stat data no longer valid. */
return (ret);
}
/*
* Returns 0 if creation succeeds, or else returns errno value from
* the failed system call. Note: This function should only ever perform
* a single system call.
*/
static int
create_filesystem_object(struct archive_write_disk *a)
{
/* Create the entry. */
const char *linkname;
mode_t final_mode, mode;
int r;
/* We identify hard/symlinks according to the link names. */
/* Since link(2) and symlink(2) don't handle modes, we're done here. */
linkname = archive_entry_hardlink(a->entry);
if (linkname != NULL) {
#if !HAVE_LINK
return (EPERM);
#else
r = link(linkname, a->name) ? errno : 0;
/*
* New cpio and pax formats allow hardlink entries
* to carry data, so we may have to open the file
* for hardlink entries.
*
* If the hardlink was successfully created and
* the archive doesn't have carry data for it,
* consider it to be non-authoritative for meta data.
* This is consistent with GNU tar and BSD pax.
* If the hardlink does carry data, let the last
* archive entry decide ownership.
*/
if (r == 0 && a->filesize <= 0) {
a->todo = 0;
a->deferred = 0;
} else if (r == 0 && a->filesize > 0) {
a->fd = open(a->name,
O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(a->fd);
if (a->fd < 0)
r = errno;
}
return (r);
#endif
}
linkname = archive_entry_symlink(a->entry);
if (linkname != NULL) {
#if HAVE_SYMLINK
return symlink(linkname, a->name) ? errno : 0;
#else
return (EPERM);
#endif
}
/*
* The remaining system calls all set permissions, so let's
* try to take advantage of that to avoid an extra chmod()
* call. (Recall that umask is set to zero right now!)
*/
/* Mode we want for the final restored object (w/o file type bits). */
final_mode = a->mode & 07777;
/*
* The mode that will actually be restored in this step. Note
* that SUID, SGID, etc, require additional work to ensure
* security, so we never restore them at this point.
*/
mode = final_mode & 0777 & ~a->user_umask;
switch (a->mode & AE_IFMT) {
default:
/* POSIX requires that we fall through here. */
/* FALLTHROUGH */
case AE_IFREG:
a->fd = open(a->name,
O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
__archive_ensure_cloexec_flag(a->fd);
r = (a->fd < 0);
break;
case AE_IFCHR:
#ifdef HAVE_MKNOD
/* Note: we use AE_IFCHR for the case label, and
* S_IFCHR for the mknod() call. This is correct. */
r = mknod(a->name, mode | S_IFCHR,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a char device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFBLK:
#ifdef HAVE_MKNOD
r = mknod(a->name, mode | S_IFBLK,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a block device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFDIR:
mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
r = mkdir(a->name, mode);
if (r == 0) {
/* Defer setting dir times. */
a->deferred |= (a->todo & TODO_TIMES);
a->todo &= ~TODO_TIMES;
/* Never use an immediate chmod(). */
/* We can't avoid the chmod() entirely if EXTRACT_PERM
* because of SysV SGID inheritance. */
if ((mode != final_mode)
|| (a->flags & ARCHIVE_EXTRACT_PERM))
a->deferred |= (a->todo & TODO_MODE);
a->todo &= ~TODO_MODE;
}
break;
case AE_IFIFO:
#ifdef HAVE_MKFIFO
r = mkfifo(a->name, mode);
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a fifo. */
return (EINVAL);
#endif /* HAVE_MKFIFO */
}
/* All the system calls above set errno on failure. */
if (r)
return (errno);
/* If we managed to set the final mode, we've avoided a chmod(). */
if (mode == final_mode)
a->todo &= ~TODO_MODE;
return (0);
}
/*
* Cleanup function for archive_extract. Mostly, this involves processing
* the fixup list, which is used to address a number of problems:
* * Dir permissions might prevent us from restoring a file in that
* dir, so we restore the dir with minimum 0700 permissions first,
* then correct the mode at the end.
* * Similarly, the act of restoring a file touches the directory
* and changes the timestamp on the dir, so we have to touch-up dir
* timestamps at the end as well.
* * Some file flags can interfere with the restore by, for example,
* preventing the creation of hardlinks to those files.
* * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
*
* Note that tar/cpio do not require that archives be in a particular
* order; there is no way to know when the last file has been restored
* within a directory, so there's no way to optimize the memory usage
* here by fixing up the directory any earlier than the
* end-of-archive.
*
* XXX TODO: Directory ACLs should be restored here, for the same
* reason we set directory perms here. XXX
*/
static int
_archive_write_disk_close(struct archive *_a)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
struct fixup_entry *next, *p;
int ret;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
"archive_write_disk_close");
ret = _archive_write_disk_finish_entry(&a->archive);
/* Sort dir list so directories are fixed up in depth-first order. */
p = sort_dir_list(a->fixup_list);
while (p != NULL) {
a->pst = NULL; /* Mark stat cache as out-of-date. */
if (p->fixup & TODO_TIMES) {
set_times(a, -1, p->mode, p->name,
p->atime, p->atime_nanos,
p->birthtime, p->birthtime_nanos,
p->mtime, p->mtime_nanos,
p->ctime, p->ctime_nanos);
}
if (p->fixup & TODO_MODE_BASE)
chmod(p->name, p->mode);
if (p->fixup & TODO_ACLS)
archive_write_disk_set_acls(&a->archive,
-1, p->name, &p->acl);
if (p->fixup & TODO_FFLAGS)
set_fflags_platform(a, -1, p->name,
p->mode, p->fflags_set, 0);
if (p->fixup & TODO_MAC_METADATA)
set_mac_metadata(a, p->name, p->mac_metadata,
p->mac_metadata_size);
next = p->next;
archive_acl_clear(&p->acl);
free(p->mac_metadata);
free(p->name);
free(p);
p = next;
}
a->fixup_list = NULL;
return (ret);
}
static int
_archive_write_disk_free(struct archive *_a)
{
struct archive_write_disk *a;
int ret;
if (_a == NULL)
return (ARCHIVE_OK);
archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
a = (struct archive_write_disk *)_a;
ret = _archive_write_disk_close(&a->archive);
archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
if (a->entry)
archive_entry_free(a->entry);
archive_string_free(&a->_name_data);
archive_string_free(&a->archive.error_string);
archive_string_free(&a->path_safe);
a->archive.magic = 0;
__archive_clean(&a->archive);
free(a->decmpfs_header_p);
free(a->resource_fork);
free(a->compressed_buffer);
free(a->uncompressed_buffer);
#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
&& defined(HAVE_ZLIB_H)
if (a->stream_valid) {
switch (deflateEnd(&a->stream)) {
case Z_OK:
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to clean up compressor");
ret = ARCHIVE_FATAL;
break;
}
}
#endif
free(a);
return (ret);
}
/*
* Simple O(n log n) merge sort to order the fixup list. In
* particular, we want to restore dir timestamps depth-first.
*/
static struct fixup_entry *
sort_dir_list(struct fixup_entry *p)
{
struct fixup_entry *a, *b, *t;
if (p == NULL)
return (NULL);
/* A one-item list is already sorted. */
if (p->next == NULL)
return (p);
/* Step 1: split the list. */
t = p;
a = p->next->next;
while (a != NULL) {
/* Step a twice, t once. */
a = a->next;
if (a != NULL)
a = a->next;
t = t->next;
}
/* Now, t is at the mid-point, so break the list here. */
b = t->next;
t->next = NULL;
a = p;
/* Step 2: Recursively sort the two sub-lists. */
a = sort_dir_list(a);
b = sort_dir_list(b);
/* Step 3: Merge the returned lists. */
/* Pick the first element for the merged list. */
if (strcmp(a->name, b->name) > 0) {
t = p = a;
a = a->next;
} else {
t = p = b;
b = b->next;
}
/* Always put the later element on the list first. */
while (a != NULL && b != NULL) {
if (strcmp(a->name, b->name) > 0) {
t->next = a;
a = a->next;
} else {
t->next = b;
b = b->next;
}
t = t->next;
}
/* Only one list is non-empty, so just splice it on. */
if (a != NULL)
t->next = a;
if (b != NULL)
t->next = b;
return (p);
}
/*
* Returns a new, initialized fixup entry.
*
* TODO: Reduce the memory requirements for this list by using a tree
* structure rather than a simple list of names.
*/
static struct fixup_entry *
new_fixup(struct archive_write_disk *a, const char *pathname)
{
struct fixup_entry *fe;
fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
if (fe == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for a fixup");
return (NULL);
}
fe->next = a->fixup_list;
a->fixup_list = fe;
fe->fixup = 0;
fe->name = strdup(pathname);
return (fe);
}
/*
* Returns a fixup structure for the current entry.
*/
static struct fixup_entry *
current_fixup(struct archive_write_disk *a, const char *pathname)
{
if (a->current_fixup == NULL)
a->current_fixup = new_fixup(a, pathname);
return (a->current_fixup);
}
/* TODO: Make this work. */
/*
* TODO: The deep-directory support bypasses this; disable deep directory
* support if we're doing symlink checks.
*/
/*
* TODO: Someday, integrate this with the deep dir support; they both
* scan the path and both can be optimized by comparing against other
* recent paths.
*/
/* TODO: Extend this to support symlinks on Windows Vista and later. */
static int
check_symlinks(struct archive_write_disk *a)
{
#if !defined(HAVE_LSTAT)
/* Platform doesn't have lstat, so we can't look for symlinks. */
(void)a; /* UNUSED */
return (ARCHIVE_OK);
#else
char *pn;
char c;
int r;
struct stat st;
/*
* Guard against symlink tricks. Reject any archive entry whose
* destination would be altered by a symlink.
*/
/* Whatever we checked last time doesn't need to be re-checked. */
pn = a->name;
if (archive_strlen(&(a->path_safe)) > 0) {
char *p = a->path_safe.s;
while ((*pn != '\0') && (*p == *pn))
++p, ++pn;
}
c = pn[0];
/* Keep going until we've checked the entire name. */
while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
/* Skip the next path element. */
while (*pn != '\0' && *pn != '/')
++pn;
c = pn[0];
pn[0] = '\0';
/* Check that we haven't hit a symlink. */
r = lstat(a->name, &st);
if (r != 0) {
/* We've hit a dir that doesn't exist; stop now. */
if (errno == ENOENT)
break;
} else if (S_ISLNK(st.st_mode)) {
if (c == '\0') {
/*
* Last element is symlink; remove it
* so we can overwrite it with the
* item being extracted.
*/
if (unlink(a->name)) {
archive_set_error(&a->archive, errno,
"Could not remove symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
a->pst = NULL;
/*
* Even if we did remove it, a warning
* is in order. The warning is silly,
* though, if we're just replacing one
* symlink with another symlink.
*/
if (!S_ISLNK(a->mode)) {
archive_set_error(&a->archive, 0,
"Removing symlink %s",
a->name);
}
/* Symlink gone. No more problem! */
pn[0] = c;
return (0);
} else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
/* User asked us to remove problems. */
if (unlink(a->name) != 0) {
archive_set_error(&a->archive, 0,
"Cannot remove intervening symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
a->pst = NULL;
} else {
archive_set_error(&a->archive, 0,
"Cannot extract through symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
}
}
pn[0] = c;
/* We've checked and/or cleaned the whole path, so remember it. */
archive_strcpy(&a->path_safe, a->name);
return (ARCHIVE_OK);
#endif
}
#if defined(__CYGWIN__)
/*
* 1. Convert a path separator from '\' to '/' .
* We shouldn't check multibyte character directly because some
* character-set have been using the '\' character for a part of
* its multibyte character code.
* 2. Replace unusable characters in Windows with underscore('_').
* See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
*/
static void
cleanup_pathname_win(struct archive_write_disk *a)
{
wchar_t wc;
char *p;
size_t alen, l;
int mb, complete, utf8;
alen = 0;
mb = 0;
complete = 1;
utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
for (p = a->name; *p != '\0'; p++) {
++alen;
if (*p == '\\') {
/* If previous byte is smaller than 128,
* this is not second byte of multibyte characters,
* so we can replace '\' with '/'. */
if (utf8 || !mb)
*p = '/';
else
complete = 0;/* uncompleted. */
} else if (*(unsigned char *)p > 127)
mb = 1;
else
mb = 0;
/* Rewrite the path name if its next character is unusable. */
if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
*p == '<' || *p == '>' || *p == '|')
*p = '_';
}
if (complete)
return;
/*
* Convert path separator in wide-character.
*/
p = a->name;
while (*p != '\0' && alen) {
l = mbtowc(&wc, p, alen);
if (l == (size_t)-1) {
while (*p != '\0') {
if (*p == '\\')
*p = '/';
++p;
}
break;
}
if (l == 1 && wc == L'\\')
*p = '/';
p += l;
alen -= l;
}
}
#endif
/*
* Canonicalize the pathname. In particular, this strips duplicate
* '/' characters, '.' elements, and trailing '/'. It also raises an
* error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
* set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
* is set) if the path is absolute.
*/
static int
cleanup_pathname(struct archive_write_disk *a)
{
char *dest, *src;
char separator = '\0';
dest = src = a->name;
if (*src == '\0') {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/') {
if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Path is absolute");
return (ARCHIVE_FAILED);
}
separator = *src++;
}
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == a->name) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
/*
* Create the parent directory of the specified path, assuming path
* is already in mutable storage.
*/
static int
create_parent_dir(struct archive_write_disk *a, char *path)
{
char *slash;
int r;
/* Remove tail element to obtain parent name. */
slash = strrchr(path, '/');
if (slash == NULL)
return (ARCHIVE_OK);
*slash = '\0';
r = create_dir(a, path);
*slash = '/';
return (r);
}
/*
* Create the specified dir, recursing to create parents as necessary.
*
* Returns ARCHIVE_OK if the path exists when we're done here.
* Otherwise, returns ARCHIVE_FAILED.
* Assumes path is in mutable storage; path is unchanged on exit.
*/
static int
create_dir(struct archive_write_disk *a, char *path)
{
struct stat st;
struct fixup_entry *le;
char *slash, *base;
mode_t mode_final, mode;
int r;
/* Check for special names and just skip them. */
slash = strrchr(path, '/');
if (slash == NULL)
base = path;
else
base = slash + 1;
if (base[0] == '\0' ||
(base[0] == '.' && base[1] == '\0') ||
(base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
/* Don't bother trying to create null path, '.', or '..'. */
if (slash != NULL) {
*slash = '\0';
r = create_dir(a, path);
*slash = '/';
return (r);
}
return (ARCHIVE_OK);
}
/*
* Yes, this should be stat() and not lstat(). Using lstat()
* here loses the ability to extract through symlinks. Also note
* that this should not use the a->st cache.
*/
if (stat(path, &st) == 0) {
if (S_ISDIR(st.st_mode))
return (ARCHIVE_OK);
if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
archive_set_error(&a->archive, EEXIST,
"Can't create directory '%s'", path);
return (ARCHIVE_FAILED);
}
if (unlink(path) != 0) {
archive_set_error(&a->archive, errno,
"Can't create directory '%s': "
"Conflicting file cannot be removed",
path);
return (ARCHIVE_FAILED);
}
} else if (errno != ENOENT && errno != ENOTDIR) {
/* Stat failed? */
archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
return (ARCHIVE_FAILED);
} else if (slash != NULL) {
*slash = '\0';
r = create_dir(a, path);
*slash = '/';
if (r != ARCHIVE_OK)
return (r);
}
/*
* Mode we want for the final restored directory. Per POSIX,
* implicitly-created dirs must be created obeying the umask.
* There's no mention whether this is different for privileged
* restores (which the rest of this code handles by pretending
* umask=0). I've chosen here to always obey the user's umask for
* implicit dirs, even if _EXTRACT_PERM was specified.
*/
mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
/* Mode we want on disk during the restore process. */
mode = mode_final;
mode |= MINIMUM_DIR_MODE;
mode &= MAXIMUM_DIR_MODE;
if (mkdir(path, mode) == 0) {
if (mode != mode_final) {
le = new_fixup(a, path);
if (le == NULL)
return (ARCHIVE_FATAL);
le->fixup |=TODO_MODE_BASE;
le->mode = mode_final;
}
return (ARCHIVE_OK);
}
/*
* Without the following check, a/b/../b/c/d fails at the
* second visit to 'b', so 'd' can't be created. Note that we
* don't add it to the fixup list here, as it's already been
* added.
*/
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
return (ARCHIVE_OK);
archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
path);
return (ARCHIVE_FAILED);
}
/*
* Note: Although we can skip setting the user id if the desired user
* id matches the current user, we cannot skip setting the group, as
* many systems set the gid based on the containing directory. So
* we have to perform a chown syscall if we want to set the SGID
* bit. (The alternative is to stat() and then possibly chown(); it's
* more efficient to skip the stat() and just always chown().) Note
* that a successful chown() here clears the TODO_SGID_CHECK bit, which
* allows set_mode to skip the stat() check for the GID.
*/
static int
set_ownership(struct archive_write_disk *a)
{
#ifndef __CYGWIN__
/* unfortunately, on win32 there is no 'root' user with uid 0,
so we just have to try the chown and see if it works */
/* If we know we can't change it, don't bother trying. */
if (a->user_uid != 0 && a->user_uid != a->uid) {
archive_set_error(&a->archive, errno,
"Can't set UID=%jd", (intmax_t)a->uid);
return (ARCHIVE_WARN);
}
#endif
#ifdef HAVE_FCHOWN
/* If we have an fd, we can avoid a race. */
if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
/* We've set owner and know uid/gid are correct. */
a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
return (ARCHIVE_OK);
}
#endif
/* We prefer lchown() but will use chown() if that's all we have. */
/* Of course, if we have neither, this will always fail. */
#ifdef HAVE_LCHOWN
if (lchown(a->name, a->uid, a->gid) == 0) {
/* We've set owner and know uid/gid are correct. */
a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
return (ARCHIVE_OK);
}
#elif HAVE_CHOWN
if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
/* We've set owner and know uid/gid are correct. */
a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
return (ARCHIVE_OK);
}
#endif
archive_set_error(&a->archive, errno,
"Can't set user=%jd/group=%jd for %s",
(intmax_t)a->uid, (intmax_t)a->gid, a->name);
return (ARCHIVE_WARN);
}
/*
* Note: Returns 0 on success, non-zero on failure.
*/
static int
set_time(int fd, int mode, const char *name,
time_t atime, long atime_nsec,
time_t mtime, long mtime_nsec)
{
/* Select the best implementation for this platform. */
#if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
/*
* utimensat() and futimens() are defined in
* POSIX.1-2008. They support ns resolution and setting times
* on fds and symlinks.
*/
struct timespec ts[2];
(void)mode; /* UNUSED */
ts[0].tv_sec = atime;
ts[0].tv_nsec = atime_nsec;
ts[1].tv_sec = mtime;
ts[1].tv_nsec = mtime_nsec;
if (fd >= 0)
return futimens(fd, ts);
return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
#elif HAVE_UTIMES
/*
* The utimes()-family functions support µs-resolution and
* setting times fds and symlinks. utimes() is documented as
* LEGACY by POSIX, futimes() and lutimes() are not described
* in POSIX.
*/
struct timeval times[2];
times[0].tv_sec = atime;
times[0].tv_usec = atime_nsec / 1000;
times[1].tv_sec = mtime;
times[1].tv_usec = mtime_nsec / 1000;
#ifdef HAVE_FUTIMES
if (fd >= 0)
return (futimes(fd, times));
#else
(void)fd; /* UNUSED */
#endif
#ifdef HAVE_LUTIMES
(void)mode; /* UNUSED */
return (lutimes(name, times));
#else
if (S_ISLNK(mode))
return (0);
return (utimes(name, times));
#endif
#elif defined(HAVE_UTIME)
/*
* utime() is POSIX-standard but only supports 1s resolution and
* does not support fds or symlinks.
*/
struct utimbuf times;
(void)fd; /* UNUSED */
(void)name; /* UNUSED */
(void)atime_nsec; /* UNUSED */
(void)mtime_nsec; /* UNUSED */
times.actime = atime;
times.modtime = mtime;
if (S_ISLNK(mode))
return (ARCHIVE_OK);
return (utime(name, ×));
#else
/*
* We don't know how to set the time on this platform.
*/
(void)fd; /* UNUSED */
(void)mode; /* UNUSED */
(void)name; /* UNUSED */
(void)atime_nsec; /* UNUSED */
(void)mtime_nsec; /* UNUSED */
return (ARCHIVE_WARN);
#endif
}
#ifdef F_SETTIMES
static int
set_time_tru64(int fd, int mode, const char *name,
time_t atime, long atime_nsec,
time_t mtime, long mtime_nsec,
time_t ctime, long ctime_nsec)
{
struct attr_timbuf tstamp;
tstamp.atime.tv_sec = atime;
tstamp.mtime.tv_sec = mtime;
tstamp.ctime.tv_sec = ctime;
#if defined (__hpux) && defined (__ia64)
tstamp.atime.tv_nsec = atime_nsec;
tstamp.mtime.tv_nsec = mtime_nsec;
tstamp.ctime.tv_nsec = ctime_nsec;
#else
tstamp.atime.tv_usec = atime_nsec / 1000;
tstamp.mtime.tv_usec = mtime_nsec / 1000;
tstamp.ctime.tv_usec = ctime_nsec / 1000;
#endif
return (fcntl(fd,F_SETTIMES,&tstamp));
}
#endif /* F_SETTIMES */
static int
set_times(struct archive_write_disk *a,
int fd, int mode, const char *name,
time_t atime, long atime_nanos,
time_t birthtime, long birthtime_nanos,
time_t mtime, long mtime_nanos,
time_t cctime, long ctime_nanos)
{
/* Note: set_time doesn't use libarchive return conventions!
* It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */
int r1 = 0, r2 = 0;
#ifdef F_SETTIMES
/*
* on Tru64 try own fcntl first which can restore even the
* ctime, fall back to default code path below if it fails
* or if we are not running as root
*/
if (a->user_uid == 0 &&
set_time_tru64(fd, mode, name,
atime, atime_nanos, mtime,
mtime_nanos, cctime, ctime_nanos) == 0) {
return (ARCHIVE_OK);
}
#else /* Tru64 */
(void)cctime; /* UNUSED */
(void)ctime_nanos; /* UNUSED */
#endif /* Tru64 */
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
/*
* If you have struct stat.st_birthtime, we assume BSD
* birthtime semantics, in which {f,l,}utimes() updates
* birthtime to earliest mtime. So we set the time twice,
* first using the birthtime, then using the mtime. If
* birthtime == mtime, this isn't necessary, so we skip it.
* If birthtime > mtime, then this won't work, so we skip it.
*/
if (birthtime < mtime
|| (birthtime == mtime && birthtime_nanos < mtime_nanos))
r1 = set_time(fd, mode, name,
atime, atime_nanos,
birthtime, birthtime_nanos);
#else
(void)birthtime; /* UNUSED */
(void)birthtime_nanos; /* UNUSED */
#endif
r2 = set_time(fd, mode, name,
atime, atime_nanos,
mtime, mtime_nanos);
if (r1 != 0 || r2 != 0) {
archive_set_error(&a->archive, errno,
"Can't restore time");
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
static int
set_times_from_entry(struct archive_write_disk *a)
{
time_t atime, birthtime, mtime, cctime;
long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
/* Suitable defaults. */
atime = birthtime = mtime = cctime = a->start_time;
atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
/* If no time was provided, we're done. */
if (!archive_entry_atime_is_set(a->entry)
#if HAVE_STRUCT_STAT_ST_BIRTHTIME
&& !archive_entry_birthtime_is_set(a->entry)
#endif
&& !archive_entry_mtime_is_set(a->entry))
return (ARCHIVE_OK);
if (archive_entry_atime_is_set(a->entry)) {
atime = archive_entry_atime(a->entry);
atime_nsec = archive_entry_atime_nsec(a->entry);
}
if (archive_entry_birthtime_is_set(a->entry)) {
birthtime = archive_entry_birthtime(a->entry);
birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
}
if (archive_entry_mtime_is_set(a->entry)) {
mtime = archive_entry_mtime(a->entry);
mtime_nsec = archive_entry_mtime_nsec(a->entry);
}
if (archive_entry_ctime_is_set(a->entry)) {
cctime = archive_entry_ctime(a->entry);
ctime_nsec = archive_entry_ctime_nsec(a->entry);
}
return set_times(a, a->fd, a->mode, a->name,
atime, atime_nsec,
birthtime, birthtime_nsec,
mtime, mtime_nsec,
cctime, ctime_nsec);
}
static int
set_mode(struct archive_write_disk *a, int mode)
{
int r = ARCHIVE_OK;
mode &= 07777; /* Strip off file type bits. */
if (a->todo & TODO_SGID_CHECK) {
/*
* If we don't know the GID is right, we must stat()
* to verify it. We can't just check the GID of this
* process, since systems sometimes set GID from
* the enclosing dir or based on ACLs.
*/
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
if (a->pst->st_gid != a->gid) {
mode &= ~ S_ISGID;
if (a->flags & ARCHIVE_EXTRACT_OWNER) {
/*
* This is only an error if you
* requested owner restore. If you
* didn't, we'll try to restore
* sgid/suid, but won't consider it a
* problem if we can't.
*/
archive_set_error(&a->archive, -1,
"Can't restore SGID bit");
r = ARCHIVE_WARN;
}
}
/* While we're here, double-check the UID. */
if (a->pst->st_uid != a->uid
&& (a->todo & TODO_SUID)) {
mode &= ~ S_ISUID;
if (a->flags & ARCHIVE_EXTRACT_OWNER) {
archive_set_error(&a->archive, -1,
"Can't restore SUID bit");
r = ARCHIVE_WARN;
}
}
a->todo &= ~TODO_SGID_CHECK;
a->todo &= ~TODO_SUID_CHECK;
} else if (a->todo & TODO_SUID_CHECK) {
/*
* If we don't know the UID is right, we can just check
* the user, since all systems set the file UID from
* the process UID.
*/
if (a->user_uid != a->uid) {
mode &= ~ S_ISUID;
if (a->flags & ARCHIVE_EXTRACT_OWNER) {
archive_set_error(&a->archive, -1,
"Can't make file SUID");
r = ARCHIVE_WARN;
}
}
a->todo &= ~TODO_SUID_CHECK;
}
if (S_ISLNK(a->mode)) {
#ifdef HAVE_LCHMOD
/*
* If this is a symlink, use lchmod(). If the
* platform doesn't support lchmod(), just skip it. A
* platform that doesn't provide a way to set
* permissions on symlinks probably ignores
* permissions on symlinks, so a failure here has no
* impact.
*/
if (lchmod(a->name, mode) != 0) {
switch (errno) {
case ENOTSUP:
case ENOSYS:
#if ENOTSUP != EOPNOTSUPP
case EOPNOTSUPP:
#endif
/*
* if lchmod is defined but the platform
* doesn't support it, silently ignore
* error
*/
break;
default:
archive_set_error(&a->archive, errno,
"Can't set permissions to 0%o", (int)mode);
r = ARCHIVE_WARN;
}
}
#endif
} else if (!S_ISDIR(a->mode)) {
/*
* If it's not a symlink and not a dir, then use
* fchmod() or chmod(), depending on whether we have
* an fd. Dirs get their perms set during the
* post-extract fixup, which is handled elsewhere.
*/
#ifdef HAVE_FCHMOD
if (a->fd >= 0) {
if (fchmod(a->fd, mode) != 0) {
archive_set_error(&a->archive, errno,
"Can't set permissions to 0%o", (int)mode);
r = ARCHIVE_WARN;
}
} else
#endif
/* If this platform lacks fchmod(), then
* we'll just use chmod(). */
if (chmod(a->name, mode) != 0) {
archive_set_error(&a->archive, errno,
"Can't set permissions to 0%o", (int)mode);
r = ARCHIVE_WARN;
}
}
return (r);
}
static int
set_fflags(struct archive_write_disk *a)
{
struct fixup_entry *le;
unsigned long set, clear;
int r;
int critical_flags;
mode_t mode = archive_entry_mode(a->entry);
/*
* Make 'critical_flags' hold all file flags that can't be
* immediately restored. For example, on BSD systems,
* SF_IMMUTABLE prevents hardlinks from being created, so
* should not be set until after any hardlinks are created. To
* preserve some semblance of portability, this uses #ifdef
* extensively. Ugly, but it works.
*
* Yes, Virginia, this does create a security race. It's mitigated
* somewhat by the practice of creating dirs 0700 until the extract
* is done, but it would be nice if we could do more than that.
* People restoring critical file systems should be wary of
* other programs that might try to muck with files as they're
* being restored.
*/
/* Hopefully, the compiler will optimize this mess into a constant. */
critical_flags = 0;
#ifdef SF_IMMUTABLE
critical_flags |= SF_IMMUTABLE;
#endif
#ifdef UF_IMMUTABLE
critical_flags |= UF_IMMUTABLE;
#endif
#ifdef SF_APPEND
critical_flags |= SF_APPEND;
#endif
#ifdef UF_APPEND
critical_flags |= UF_APPEND;
#endif
#ifdef EXT2_APPEND_FL
critical_flags |= EXT2_APPEND_FL;
#endif
#ifdef EXT2_IMMUTABLE_FL
critical_flags |= EXT2_IMMUTABLE_FL;
#endif
if (a->todo & TODO_FFLAGS) {
archive_entry_fflags(a->entry, &set, &clear);
/*
* The first test encourages the compiler to eliminate
* all of this if it's not necessary.
*/
if ((critical_flags != 0) && (set & critical_flags)) {
le = current_fixup(a, a->name);
if (le == NULL)
return (ARCHIVE_FATAL);
le->fixup |= TODO_FFLAGS;
le->fflags_set = set;
/* Store the mode if it's not already there. */
if ((le->fixup & TODO_MODE) == 0)
le->mode = mode;
} else {
r = set_fflags_platform(a, a->fd,
a->name, mode, set, clear);
if (r != ARCHIVE_OK)
return (r);
}
}
return (ARCHIVE_OK);
}
#if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
/*
* BSD reads flags using stat() and sets them with one of {f,l,}chflags()
*/
static int
set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
mode_t mode, unsigned long set, unsigned long clear)
{
int r;
(void)mode; /* UNUSED */
if (set == 0 && clear == 0)
return (ARCHIVE_OK);
/*
* XXX Is the stat here really necessary? Or can I just use
* the 'set' flags directly? In particular, I'm not sure
* about the correct approach if we're overwriting an existing
* file that already has flags on it. XXX
*/
if ((r = lazy_stat(a)) != ARCHIVE_OK)
return (r);
a->st.st_flags &= ~clear;
a->st.st_flags |= set;
#ifdef HAVE_FCHFLAGS
/* If platform has fchflags() and we were given an fd, use it. */
if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
return (ARCHIVE_OK);
#endif
/*
* If we can't use the fd to set the flags, we'll use the
* pathname to set flags. We prefer lchflags() but will use
* chflags() if we must.
*/
#ifdef HAVE_LCHFLAGS
if (lchflags(name, a->st.st_flags) == 0)
return (ARCHIVE_OK);
#elif defined(HAVE_CHFLAGS)
if (S_ISLNK(a->st.st_mode)) {
archive_set_error(&a->archive, errno,
"Can't set file flags on symlink.");
return (ARCHIVE_WARN);
}
if (chflags(name, a->st.st_flags) == 0)
return (ARCHIVE_OK);
#endif
archive_set_error(&a->archive, errno,
"Failed to set file flags");
return (ARCHIVE_WARN);
}
#elif defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)
/*
* Linux uses ioctl() to read and write file flags.
*/
static int
set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
mode_t mode, unsigned long set, unsigned long clear)
{
int ret;
int myfd = fd;
int newflags, oldflags;
int sf_mask = 0;
if (set == 0 && clear == 0)
return (ARCHIVE_OK);
/* Only regular files and dirs can have flags. */
if (!S_ISREG(mode) && !S_ISDIR(mode))
return (ARCHIVE_OK);
/* If we weren't given an fd, open it ourselves. */
if (myfd < 0) {
myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(myfd);
}
if (myfd < 0)
return (ARCHIVE_OK);
/*
* Linux has no define for the flags that are only settable by
* the root user. This code may seem a little complex, but
* there seem to be some Linux systems that lack these
* defines. (?) The code below degrades reasonably gracefully
* if sf_mask is incomplete.
*/
#ifdef EXT2_IMMUTABLE_FL
sf_mask |= EXT2_IMMUTABLE_FL;
#endif
#ifdef EXT2_APPEND_FL
sf_mask |= EXT2_APPEND_FL;
#endif
/*
* XXX As above, this would be way simpler if we didn't have
* to read the current flags from disk. XXX
*/
ret = ARCHIVE_OK;
/* Read the current file flags. */
if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) < 0)
goto fail;
/* Try setting the flags as given. */
newflags = (oldflags & ~clear) | set;
if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
goto cleanup;
if (errno != EPERM)
goto fail;
/* If we couldn't set all the flags, try again with a subset. */
newflags &= ~sf_mask;
oldflags &= sf_mask;
newflags |= oldflags;
if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
goto cleanup;
/* We couldn't set the flags, so report the failure. */
fail:
archive_set_error(&a->archive, errno,
"Failed to set file flags");
ret = ARCHIVE_WARN;
cleanup:
if (fd < 0)
close(myfd);
return (ret);
}
#else
/*
* Of course, some systems have neither BSD chflags() nor Linux' flags
* support through ioctl().
*/
static int
set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
mode_t mode, unsigned long set, unsigned long clear)
{
(void)a; /* UNUSED */
(void)fd; /* UNUSED */
(void)name; /* UNUSED */
(void)mode; /* UNUSED */
(void)set; /* UNUSED */
(void)clear; /* UNUSED */
return (ARCHIVE_OK);
}
#endif /* __linux */
#ifndef HAVE_COPYFILE_H
/* Default is to simply drop Mac extended metadata. */
static int
set_mac_metadata(struct archive_write_disk *a, const char *pathname,
const void *metadata, size_t metadata_size)
{
(void)a; /* UNUSED */
(void)pathname; /* UNUSED */
(void)metadata; /* UNUSED */
(void)metadata_size; /* UNUSED */
return (ARCHIVE_OK);
}
static int
fixup_appledouble(struct archive_write_disk *a, const char *pathname)
{
(void)a; /* UNUSED */
(void)pathname; /* UNUSED */
return (ARCHIVE_OK);
}
#else
/*
* On Mac OS, we use copyfile() to unpack the metadata and
* apply it to the target file.
*/
#if defined(HAVE_SYS_XATTR_H)
static int
copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
{
ssize_t xattr_size;
char *xattr_names = NULL, *xattr_val = NULL;
int ret = ARCHIVE_OK, xattr_i;
xattr_size = flistxattr(tmpfd, NULL, 0, 0);
if (xattr_size == -1) {
archive_set_error(&a->archive, errno,
"Failed to read metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
xattr_names = malloc(xattr_size);
if (xattr_names == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for metadata(xattr)");
ret = ARCHIVE_FATAL;
goto exit_xattr;
}
xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
if (xattr_size == -1) {
archive_set_error(&a->archive, errno,
"Failed to read metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
for (xattr_i = 0; xattr_i < xattr_size;
xattr_i += strlen(xattr_names + xattr_i) + 1) {
char *xattr_val_saved;
ssize_t s;
int f;
s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
if (s == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
xattr_val_saved = xattr_val;
xattr_val = realloc(xattr_val, s);
if (xattr_val == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
free(xattr_val_saved);
goto exit_xattr;
}
s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
if (s == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
if (f == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(xattr)");
ret = ARCHIVE_WARN;
goto exit_xattr;
}
}
exit_xattr:
free(xattr_names);
free(xattr_val);
return (ret);
}
#endif
static int
copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
{
acl_t acl, dfacl = NULL;
int acl_r, ret = ARCHIVE_OK;
acl = acl_get_fd(tmpfd);
if (acl == NULL) {
if (errno == ENOENT)
/* There are not any ACLs. */
return (ret);
archive_set_error(&a->archive, errno,
"Failed to get metadata(acl)");
ret = ARCHIVE_WARN;
goto exit_acl;
}
dfacl = acl_dup(acl);
acl_r = acl_set_fd(dffd, dfacl);
if (acl_r == -1) {
archive_set_error(&a->archive, errno,
"Failed to get metadata(acl)");
ret = ARCHIVE_WARN;
goto exit_acl;
}
exit_acl:
if (acl)
acl_free(acl);
if (dfacl)
acl_free(dfacl);
return (ret);
}
static int
create_tempdatafork(struct archive_write_disk *a, const char *pathname)
{
struct archive_string tmpdatafork;
int tmpfd;
archive_string_init(&tmpdatafork);
archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
tmpfd = mkstemp(tmpdatafork.s);
if (tmpfd < 0) {
archive_set_error(&a->archive, errno,
"Failed to mkstemp");
archive_string_free(&tmpdatafork);
return (-1);
}
if (copyfile(pathname, tmpdatafork.s, 0,
COPYFILE_UNPACK | COPYFILE_NOFOLLOW
| COPYFILE_ACL | COPYFILE_XATTR) < 0) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
close(tmpfd);
tmpfd = -1;
}
unlink(tmpdatafork.s);
archive_string_free(&tmpdatafork);
return (tmpfd);
}
static int
copy_metadata(struct archive_write_disk *a, const char *metadata,
const char *datafork, int datafork_compressed)
{
int ret = ARCHIVE_OK;
if (datafork_compressed) {
int dffd, tmpfd;
tmpfd = create_tempdatafork(a, metadata);
if (tmpfd == -1)
return (ARCHIVE_WARN);
/*
* Do not open the data fork compressed by HFS+ compression
* with at least a writing mode(O_RDWR or O_WRONLY). it
* makes the data fork uncompressed.
*/
dffd = open(datafork, 0);
if (dffd == -1) {
archive_set_error(&a->archive, errno,
"Failed to open the data fork for metadata");
close(tmpfd);
return (ARCHIVE_WARN);
}
#if defined(HAVE_SYS_XATTR_H)
ret = copy_xattrs(a, tmpfd, dffd);
if (ret == ARCHIVE_OK)
#endif
ret = copy_acls(a, tmpfd, dffd);
close(tmpfd);
close(dffd);
} else {
if (copyfile(metadata, datafork, 0,
COPYFILE_UNPACK | COPYFILE_NOFOLLOW
| COPYFILE_ACL | COPYFILE_XATTR) < 0) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
ret = ARCHIVE_WARN;
}
}
return (ret);
}
static int
set_mac_metadata(struct archive_write_disk *a, const char *pathname,
const void *metadata, size_t metadata_size)
{
struct archive_string tmp;
ssize_t written;
int fd;
int ret = ARCHIVE_OK;
/* This would be simpler if copyfile() could just accept the
* metadata as a block of memory; then we could sidestep this
* silly dance of writing the data to disk just so that
* copyfile() can read it back in again. */
archive_string_init(&tmp);
archive_strcpy(&tmp, pathname);
archive_strcat(&tmp, ".XXXXXX");
fd = mkstemp(tmp.s);
if (fd < 0) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
archive_string_free(&tmp);
return (ARCHIVE_WARN);
}
written = write(fd, metadata, metadata_size);
close(fd);
if ((size_t)written != metadata_size) {
archive_set_error(&a->archive, errno,
"Failed to restore metadata");
ret = ARCHIVE_WARN;
} else {
int compressed;
#if defined(UF_COMPRESSED)
if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
(ret = lazy_stat(a)) == ARCHIVE_OK)
compressed = a->st.st_flags & UF_COMPRESSED;
else
#endif
compressed = 0;
ret = copy_metadata(a, tmp.s, pathname, compressed);
}
unlink(tmp.s);
archive_string_free(&tmp);
return (ret);
}
static int
fixup_appledouble(struct archive_write_disk *a, const char *pathname)
{
char buff[8];
struct stat st;
const char *p;
struct archive_string datafork;
int fd = -1, ret = ARCHIVE_OK;
archive_string_init(&datafork);
/* Check if the current file name is a type of the resource
* fork file. */
p = strrchr(pathname, '/');
if (p == NULL)
p = pathname;
else
p++;
if (p[0] != '.' || p[1] != '_')
goto skip_appledouble;
/*
* Check if the data fork file exists.
*
* TODO: Check if this write disk object has handled it.
*/
archive_strncpy(&datafork, pathname, p - pathname);
archive_strcat(&datafork, p + 2);
if (lstat(datafork.s, &st) == -1 ||
(st.st_mode & AE_IFMT) != AE_IFREG)
goto skip_appledouble;
/*
* Check if the file is in the AppleDouble form.
*/
fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(fd);
if (fd == -1) {
archive_set_error(&a->archive, errno,
"Failed to open a restoring file");
ret = ARCHIVE_WARN;
goto skip_appledouble;
}
if (read(fd, buff, 8) == -1) {
archive_set_error(&a->archive, errno,
"Failed to read a restoring file");
close(fd);
ret = ARCHIVE_WARN;
goto skip_appledouble;
}
close(fd);
/* Check AppleDouble Magic Code. */
if (archive_be32dec(buff) != 0x00051607)
goto skip_appledouble;
/* Check AppleDouble Version. */
if (archive_be32dec(buff+4) != 0x00020000)
goto skip_appledouble;
ret = copy_metadata(a, pathname, datafork.s,
#if defined(UF_COMPRESSED)
st.st_flags & UF_COMPRESSED);
#else
0);
#endif
if (ret == ARCHIVE_OK) {
unlink(pathname);
ret = ARCHIVE_EOF;
}
skip_appledouble:
archive_string_free(&datafork);
return (ret);
}
#endif
#if HAVE_LSETXATTR || HAVE_LSETEA
/*
* Restore extended attributes - Linux and AIX implementations:
* AIX' ea interface is syntaxwise identical to the Linux xattr interface.
*/
static int
set_xattrs(struct archive_write_disk *a)
{
struct archive_entry *entry = a->entry;
static int warning_done = 0;
int ret = ARCHIVE_OK;
int i = archive_entry_xattr_reset(entry);
while (i--) {
const char *name;
const void *value;
size_t size;
archive_entry_xattr_next(entry, &name, &value, &size);
if (name != NULL &&
strncmp(name, "xfsroot.", 8) != 0 &&
strncmp(name, "system.", 7) != 0) {
int e;
#if HAVE_FSETXATTR
if (a->fd >= 0)
e = fsetxattr(a->fd, name, value, size, 0);
else
#elif HAVE_FSETEA
if (a->fd >= 0)
e = fsetea(a->fd, name, value, size, 0);
else
#endif
{
#if HAVE_LSETXATTR
e = lsetxattr(archive_entry_pathname(entry),
name, value, size, 0);
#elif HAVE_LSETEA
e = lsetea(archive_entry_pathname(entry),
name, value, size, 0);
#endif
}
if (e == -1) {
if (errno == ENOTSUP || errno == ENOSYS) {
if (!warning_done) {
warning_done = 1;
archive_set_error(&a->archive, errno,
"Cannot restore extended "
"attributes on this file "
"system");
}
} else
archive_set_error(&a->archive, errno,
"Failed to set extended attribute");
ret = ARCHIVE_WARN;
}
} else {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid extended attribute encountered");
ret = ARCHIVE_WARN;
}
}
return (ret);
}
#elif HAVE_EXTATTR_SET_FILE && HAVE_DECL_EXTATTR_NAMESPACE_USER
/*
* Restore extended attributes - FreeBSD implementation
*/
static int
set_xattrs(struct archive_write_disk *a)
{
struct archive_entry *entry = a->entry;
static int warning_done = 0;
int ret = ARCHIVE_OK;
int i = archive_entry_xattr_reset(entry);
while (i--) {
const char *name;
const void *value;
size_t size;
archive_entry_xattr_next(entry, &name, &value, &size);
if (name != NULL) {
int e;
int namespace;
if (strncmp(name, "user.", 5) == 0) {
/* "user." attributes go to user namespace */
name += 5;
namespace = EXTATTR_NAMESPACE_USER;
} else {
/* Warn about other extended attributes. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Can't restore extended attribute ``%s''",
name);
ret = ARCHIVE_WARN;
continue;
}
errno = 0;
#if HAVE_EXTATTR_SET_FD
if (a->fd >= 0)
e = extattr_set_fd(a->fd, namespace, name, value, size);
else
#endif
/* TODO: should we use extattr_set_link() instead? */
{
e = extattr_set_file(archive_entry_pathname(entry),
namespace, name, value, size);
}
if (e != (int)size) {
if (errno == ENOTSUP || errno == ENOSYS) {
if (!warning_done) {
warning_done = 1;
archive_set_error(&a->archive, errno,
"Cannot restore extended "
"attributes on this file "
"system");
}
} else {
archive_set_error(&a->archive, errno,
"Failed to set extended attribute");
}
ret = ARCHIVE_WARN;
}
}
}
return (ret);
}
#else
/*
* Restore extended attributes - stub implementation for unsupported systems
*/
static int
set_xattrs(struct archive_write_disk *a)
{
static int warning_done = 0;
/* If there aren't any extended attributes, then it's okay not
* to extract them, otherwise, issue a single warning. */
if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
warning_done = 1;
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Cannot restore extended attributes on this system");
return (ARCHIVE_WARN);
}
/* Warning was already emitted; suppress further warnings. */
return (ARCHIVE_OK);
}
#endif
/*
* Test if file on disk is older than entry.
*/
static int
older(struct stat *st, struct archive_entry *entry)
{
/* First, test the seconds and return if we have a definite answer. */
/* Definitely older. */
if (st->st_mtime < archive_entry_mtime(entry))
return (1);
/* Definitely younger. */
if (st->st_mtime > archive_entry_mtime(entry))
return (0);
/* If this platform supports fractional seconds, try those. */
#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
/* Definitely older. */
if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
/* Definitely older. */
if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_MTIME_N
/* older. */
if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_UMTIME
/* older. */
if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
return (1);
#elif HAVE_STRUCT_STAT_ST_MTIME_USEC
/* older. */
if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
return (1);
#else
/* This system doesn't have high-res timestamps. */
#endif
/* Same age or newer, so not older. */
return (0);
}
#endif /* !_WIN32 || __CYGWIN__ */
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1520_4 |
crossvul-cpp_data_good_1570_1 | /*
* Utility routines.
*
* Copyright (C) 2001 Erik Andersen
*
* 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, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "internal_libreport.h"
/* Concatenate path and filename to new allocated buffer.
* Add '/' only as needed (no duplicate // are produced).
* If path is NULL, it is assumed to be "/".
* filename should not be NULL.
*/
char *concat_path_file(const char *path, const char *filename)
{
if (!path)
path = "";
const char *end = path + strlen(path);
while (*filename == '/')
filename++;
return xasprintf("%s%s%s", path, (end != path && end[-1] != '/' ? "/" : ""), filename);
}
char *concat_path_basename(const char *path, const char *filename)
{
char *abspath = realpath(filename, NULL);
char *base = strrchr((abspath ? abspath : filename), '/');
/* If realpath failed and filename is malicious (say, "/foo/.."),
* we may end up tricked into doing some bad things. Don't allow that.
*/
char buf[sizeof("tmp-"LIBREPORT_ISO_DATE_STRING_SAMPLE"-%lu")];
if (base && base[1] != '\0' && base[1] != '.')
{
/* We have a slash and it's not "foo/" or "foo/.<something>" */
base++;
}
else
{
sprintf(buf, "tmp-%s-%lu", iso_date_string(NULL), (long)getpid());
base = buf;
}
char *name = concat_path_file(path, base);
free(abspath);
return name;
}
bool str_is_correct_filename(const char *str)
{
#define NOT_PRINTABLE(c) (c < ' ' || c == 0x7f)
if (NOT_PRINTABLE(*str) || *str == '/' || *str == '\0')
return false;
++str;
if (NOT_PRINTABLE(*str) || *str =='/' || (*str == '\0' && *(str-1) == '.'))
return false;
++str;
if (NOT_PRINTABLE(*str) || *str =='/' || (*str == '\0' && *(str-1) == '.' && *(str-2) == '.'))
return false;
++str;
for (unsigned i = 0; *str != '\0' && i < 61; ++str, ++i)
if (NOT_PRINTABLE(*str) || *str == '/')
return false;
return *str == '\0';
#undef NOT_PRINTABLE
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1570_1 |
crossvul-cpp_data_good_3514_0 | /*
* $Id: device-linux.c,v 1.28 2011/02/06 03:41:38 reubenhwk Exp $
*
* Authors:
* Lars Fenneberg <lf@elemental.net>
*
* This software is Copyright 1996,1997 by the above mentioned author(s),
* All Rights Reserved.
*
* The license which is distributed with this software in the file COPYRIGHT
* applies to this software. If your distribution is missing this file, you
* may request it from <pekkas@netcore.fi>.
*
*/
#include "config.h"
#include "includes.h"
#include "radvd.h"
#include "defaults.h"
#include "pathnames.h" /* for PATH_PROC_NET_IF_INET6 */
#ifndef IPV6_ADDR_LINKLOCAL
#define IPV6_ADDR_LINKLOCAL 0x0020U
#endif
/*
* this function gets the hardware type and address of an interface,
* determines the link layer token length and checks it against
* the defined prefixes
*/
int
setup_deviceinfo(struct Interface *iface)
{
struct ifreq ifr;
struct AdvPrefix *prefix;
char zero[sizeof(iface->if_addr)];
strncpy(ifr.ifr_name, iface->Name, IFNAMSIZ-1);
ifr.ifr_name[IFNAMSIZ-1] = '\0';
if (ioctl(sock, SIOCGIFMTU, &ifr) < 0) {
flog(LOG_ERR, "ioctl(SIOCGIFMTU) failed for %s: %s",
iface->Name, strerror(errno));
return (-1);
}
dlog(LOG_DEBUG, 3, "mtu for %s is %d", iface->Name, ifr.ifr_mtu);
iface->if_maxmtu = ifr.ifr_mtu;
if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
{
flog(LOG_ERR, "ioctl(SIOCGIFHWADDR) failed for %s: %s",
iface->Name, strerror(errno));
return (-1);
}
dlog(LOG_DEBUG, 3, "hardware type for %s is %d", iface->Name,
ifr.ifr_hwaddr.sa_family);
switch(ifr.ifr_hwaddr.sa_family)
{
case ARPHRD_ETHER:
iface->if_hwaddr_len = 48;
iface->if_prefix_len = 64;
break;
#ifdef ARPHRD_FDDI
case ARPHRD_FDDI:
iface->if_hwaddr_len = 48;
iface->if_prefix_len = 64;
break;
#endif /* ARPHDR_FDDI */
#ifdef ARPHRD_ARCNET
case ARPHRD_ARCNET:
iface->if_hwaddr_len = 8;
iface->if_prefix_len = -1;
iface->if_maxmtu = -1;
break;
#endif /* ARPHDR_ARCNET */
default:
iface->if_hwaddr_len = -1;
iface->if_prefix_len = -1;
iface->if_maxmtu = -1;
break;
}
dlog(LOG_DEBUG, 3, "link layer token length for %s is %d", iface->Name,
iface->if_hwaddr_len);
dlog(LOG_DEBUG, 3, "prefix length for %s is %d", iface->Name,
iface->if_prefix_len);
if (iface->if_hwaddr_len != -1) {
unsigned int if_hwaddr_len_bytes = (iface->if_hwaddr_len + 7) >> 3;
if (if_hwaddr_len_bytes > sizeof(iface->if_hwaddr)) {
flog(LOG_ERR, "address length %d too big for %s", if_hwaddr_len_bytes, iface->Name);
return(-2);
}
memcpy(iface->if_hwaddr, ifr.ifr_hwaddr.sa_data, if_hwaddr_len_bytes);
memset(zero, 0, sizeof(zero));
if (!memcmp(iface->if_hwaddr, zero, if_hwaddr_len_bytes))
flog(LOG_WARNING, "WARNING, MAC address on %s is all zero!",
iface->Name);
}
prefix = iface->AdvPrefixList;
while (prefix)
{
if ((iface->if_prefix_len != -1) &&
(iface->if_prefix_len != prefix->PrefixLen))
{
flog(LOG_WARNING, "prefix length should be %d for %s",
iface->if_prefix_len, iface->Name);
}
prefix = prefix->next;
}
return (0);
}
/*
* this function extracts the link local address and interface index
* from PATH_PROC_NET_IF_INET6. Note: 'sock' unused in Linux.
*/
int setup_linklocal_addr(struct Interface *iface)
{
FILE *fp;
char str_addr[40];
unsigned int plen, scope, dad_status, if_idx;
char devname[IFNAMSIZ];
if ((fp = fopen(PATH_PROC_NET_IF_INET6, "r")) == NULL)
{
flog(LOG_ERR, "can't open %s: %s", PATH_PROC_NET_IF_INET6,
strerror(errno));
return (-1);
}
while (fscanf(fp, "%32s %x %02x %02x %02x %15s\n",
str_addr, &if_idx, &plen, &scope, &dad_status,
devname) != EOF)
{
if (scope == IPV6_ADDR_LINKLOCAL &&
strcmp(devname, iface->Name) == 0)
{
struct in6_addr addr;
unsigned int ap;
int i;
for (i=0; i<16; i++)
{
sscanf(str_addr + i * 2, "%02x", &ap);
addr.s6_addr[i] = (unsigned char)ap;
}
memcpy(&iface->if_addr, &addr, sizeof(iface->if_addr));
iface->if_index = if_idx;
fclose(fp);
return 0;
}
}
flog(LOG_ERR, "no linklocal address configured for %s", iface->Name);
fclose(fp);
return (-1);
}
int setup_allrouters_membership(struct Interface *iface)
{
struct ipv6_mreq mreq;
memset(&mreq, 0, sizeof(mreq));
mreq.ipv6mr_interface = iface->if_index;
/* ipv6-allrouters: ff02::2 */
mreq.ipv6mr_multiaddr.s6_addr32[0] = htonl(0xFF020000);
mreq.ipv6mr_multiaddr.s6_addr32[3] = htonl(0x2);
if (setsockopt(sock, SOL_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
{
/* linux-2.6.12-bk4 returns error with HUP signal but keep listening */
if (errno != EADDRINUSE)
{
flog(LOG_ERR, "can't join ipv6-allrouters on %s", iface->Name);
return (-1);
}
}
return (0);
}
int check_allrouters_membership(struct Interface *iface)
{
#define ALL_ROUTERS_MCAST "ff020000000000000000000000000002"
FILE *fp;
unsigned int if_idx, allrouters_ok=0;
char addr[32+1];
char buffer[301] = {""}, *str;
int ret=0;
if ((fp = fopen(PATH_PROC_NET_IGMP6, "r")) == NULL)
{
flog(LOG_ERR, "can't open %s: %s", PATH_PROC_NET_IGMP6,
strerror(errno));
return (-1);
}
str = fgets(buffer, 300, fp);
while (str && (ret = sscanf(str, "%u %*s %32[0-9A-Fa-f]", &if_idx, addr)) ) {
if (ret == 2) {
if (iface->if_index == if_idx) {
if (strncmp(addr, ALL_ROUTERS_MCAST, sizeof(addr)) == 0){
allrouters_ok = 1;
break;
}
}
}
str = fgets(buffer, 300, fp);
}
fclose(fp);
if (!allrouters_ok) {
flog(LOG_WARNING, "resetting ipv6-allrouters membership on %s", iface->Name);
setup_allrouters_membership(iface);
}
return(0);
}
/* note: also called from the root context */
int
set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
/* No path traversal */
if (strstr(name, "..") || strchr(name, '/'))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
int
set_interface_linkmtu(const char *iface, uint32_t mtu)
{
if (privsep_enabled())
return privsep_interface_linkmtu(iface, mtu);
return set_interface_var(iface,
PROC_SYS_IP6_LINKMTU, "LinkMTU",
mtu);
}
int
set_interface_curhlim(const char *iface, uint8_t hlim)
{
if (privsep_enabled())
return privsep_interface_curhlim(iface, hlim);
return set_interface_var(iface,
PROC_SYS_IP6_CURHLIM, "CurHopLimit",
hlim);
}
int
set_interface_reachtime(const char *iface, uint32_t rtime)
{
int ret;
if (privsep_enabled())
return privsep_interface_reachtime(iface, rtime);
ret = set_interface_var(iface,
PROC_SYS_IP6_BASEREACHTIME_MS,
NULL,
rtime);
if (ret)
ret = set_interface_var(iface,
PROC_SYS_IP6_BASEREACHTIME,
"BaseReachableTimer",
rtime / 1000); /* sec */
return ret;
}
int
set_interface_retranstimer(const char *iface, uint32_t rettimer)
{
int ret;
if (privsep_enabled())
return privsep_interface_retranstimer(iface, rettimer);
ret = set_interface_var(iface,
PROC_SYS_IP6_RETRANSTIMER_MS,
NULL,
rettimer);
if (ret)
ret = set_interface_var(iface,
PROC_SYS_IP6_RETRANSTIMER,
"RetransTimer",
rettimer / 1000 * USER_HZ); /* XXX user_hz */
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_3514_0 |
crossvul-cpp_data_bad_1569_0 | /*
Copyright (C) 2010 ABRT team
Copyright (C) 2010 RedHat 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "internal_libreport.h"
#include <errno.h>
#define NEW_PD_SUFFIX ".new"
static struct dump_dir *try_dd_create(const char *base_dir_name, const char *dir_name, uid_t uid)
{
char *path = concat_path_file(base_dir_name, dir_name);
struct dump_dir *dd = dd_create(path, uid, DEFAULT_DUMP_DIR_MODE);
free(path);
return dd;
}
struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name)
{
INITIALIZE_LIBREPORT();
char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER);
if (!type)
{
error_msg(_("Missing required item: '%s'"), FILENAME_ANALYZER);
return NULL;
}
uid_t uid = (uid_t)-1L;
char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);
if (uid_str)
{
char *endptr;
errno = 0;
long val = strtol(uid_str, &endptr, 10);
if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val)
{
error_msg(_("uid value is not valid: '%s'"), uid_str);
return NULL;
}
uid = (uid_t)val;
}
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0)
{
perror_msg("gettimeofday()");
return NULL;
}
char *problem_id = xasprintf("%s-%s.%ld-%lu"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid());
log_info("Saving to %s/%s with uid %d", base_dir_name, problem_id, uid);
struct dump_dir *dd;
if (base_dir_name)
dd = try_dd_create(base_dir_name, problem_id, uid);
else
{
/* Try /var/run/abrt */
dd = try_dd_create(LOCALSTATEDIR"/run/abrt", problem_id, uid);
/* Try $HOME/tmp */
if (!dd)
{
char *home = getenv("HOME");
if (home && home[0])
{
home = concat_path_file(home, "tmp");
/*mkdir(home, 0777); - do we want this? */
dd = try_dd_create(home, problem_id, uid);
free(home);
}
}
//TODO: try user's home dir obtained by getpwuid(getuid())?
/* Try system temporary directory */
if (!dd)
dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid);
}
if (!dd) /* try_dd_create() already emitted the error message */
goto ret;
GHashTableIter iter;
char *name;
struct problem_item *value;
g_hash_table_iter_init(&iter, problem_data);
while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))
{
if (value->flags & CD_FLAG_BIN)
{
char *dest = concat_path_file(dd->dd_dirname, name);
log_info("copying '%s' to '%s'", value->content, dest);
off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH);
if (copied < 0)
error_msg("Can't copy %s to %s", value->content, dest);
else
log_info("copied %li bytes", (unsigned long)copied);
free(dest);
continue;
}
/* only files should contain '/' and those are handled earlier */
if (name[0] == '.' || strchr(name, '/'))
{
error_msg("Problem data field name contains disallowed chars: '%s'", name);
continue;
}
dd_save_text(dd, name, value->content);
}
/* need to create basic files AFTER we save the pd to dump_dir
* otherwise we can't skip already created files like in case when
* reporting from anaconda where we can't read /etc/{system,redhat}-release
* and os_release is taken from anaconda
*/
dd_create_basic_files(dd, uid, NULL);
problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0';
char* new_path = concat_path_file(base_dir_name, problem_id);
log_info("Renaming from '%s' to '%s'", dd->dd_dirname, new_path);
dd_rename(dd, new_path);
ret:
free(problem_id);
return dd;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1569_0 |
crossvul-cpp_data_bad_1466_0 | /* pigz.c -- parallel implementation of gzip
* Copyright (C) 2007-2015 Mark Adler
* Version 2.3.2 xx Jan 2015 Mark Adler
*/
/*
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Mark Adler
madler@alumni.caltech.edu
Mark accepts donations for providing this software. Donations are not
required or expected. Any amount that you feel is appropriate would be
appreciated. You can use this link:
https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=536055
*/
/* Version history:
1.0 17 Jan 2007 First version, pipe only
1.1 28 Jan 2007 Avoid void * arithmetic (some compilers don't get that)
Add note about requiring zlib 1.2.3
Allow compression level 0 (no compression)
Completely rewrite parallelism -- add a write thread
Use deflateSetDictionary() to make use of history
Tune argument defaults to best performance on four cores
1.2.1 1 Feb 2007 Add long command line options, add all gzip options
Add debugging options
1.2.2 19 Feb 2007 Add list (--list) function
Process file names on command line, write .gz output
Write name and time in gzip header, set output file time
Implement all command line options except --recursive
Add --keep option to prevent deleting input files
Add thread tracing information with -vv used
Copy crc32_combine() from zlib (shared libraries issue)
1.3 25 Feb 2007 Implement --recursive
Expand help to show all options
Show help if no arguments or output piping are provided
Process options in GZIP environment variable
Add progress indicator to write thread if --verbose
1.4 4 Mar 2007 Add --independent to facilitate damaged file recovery
Reallocate jobs for new --blocksize or --processes
Do not delete original if writing to stdout
Allow --processes 1, which does no threading
Add NOTHREAD define to compile without threads
Incorporate license text from zlib in source code
1.5 25 Mar 2007 Reinitialize jobs for new compression level
Copy attributes and owner from input file to output file
Add decompression and testing
Add -lt (or -ltv) to show all entries and proper lengths
Add decompression, testing, listing of LZW (.Z) files
Only generate and show trace log if DEBUG defined
Take "-" argument to mean read file from stdin
1.6 30 Mar 2007 Add zlib stream compression (--zlib), and decompression
1.7 29 Apr 2007 Decompress first entry of a zip file (if deflated)
Avoid empty deflate blocks at end of deflate stream
Show zlib check value (Adler-32) when listing
Don't complain when decompressing empty file
Warn about trailing junk for gzip and zlib streams
Make listings consistent, ignore gzip extra flags
Add zip stream compression (--zip)
1.8 13 May 2007 Document --zip option in help output
2.0 19 Oct 2008 Complete rewrite of thread usage and synchronization
Use polling threads and a pool of memory buffers
Remove direct pthread library use, hide in yarn.c
2.0.1 20 Oct 2008 Check version of zlib at compile time, need >= 1.2.3
2.1 24 Oct 2008 Decompress with read, write, inflate, and check threads
Remove spurious use of ctime_r(), ctime() more portable
Change application of job->calc lock to be a semaphore
Detect size of off_t at run time to select %lu vs. %llu
#define large file support macro even if not __linux__
Remove _LARGEFILE64_SOURCE, _FILE_OFFSET_BITS is enough
Detect file-too-large error and report, blame build
Replace check combination routines with those from zlib
2.1.1 28 Oct 2008 Fix a leak for files with an integer number of blocks
Update for yarn 1.1 (yarn_prefix and yarn_abort)
2.1.2 30 Oct 2008 Work around use of beta zlib in production systems
2.1.3 8 Nov 2008 Don't use zlib combination routines, put back in pigz
2.1.4 9 Nov 2008 Fix bug when decompressing very short files
2.1.5 20 Jul 2009 Added 2008, 2009 to --license statement
Allow numeric parameter immediately after -p or -b
Enforce parameter after -p, -b, -s, before other options
Enforce numeric parameters to have only numeric digits
Try to determine the number of processors for -p default
Fix --suffix short option to be -S to match gzip [Bloch]
Decompress if executable named "unpigz" [Amundsen]
Add a little bit of testing to Makefile
2.1.6 17 Jan 2010 Added pigz.spec to distribution for RPM systems [Brown]
Avoid some compiler warnings
Process symbolic links if piping to stdout [Hoffstätte]
Decompress if executable named "gunzip" [Hoffstätte]
Allow ".tgz" suffix [Chernookiy]
Fix adler32 comparison on .zz files
2.1.7 17 Dec 2011 Avoid unused parameter warning in reenter()
Don't assume 2's complement ints in compress_thread()
Replicate gzip -cdf cat-like behavior
Replicate gzip -- option to suppress option decoding
Test output from make test instead of showing it
Updated pigz.spec to install unpigz, pigz.1 [Obermaier]
Add PIGZ environment variable [Mueller]
Replicate gzip suffix search when decoding or listing
Fix bug in load() to set in_left to zero on end of file
Do not check suffix when input file won't be modified
Decompress to stdout if name is "*cat" [Hayasaka]
Write data descriptor signature to be like Info-ZIP
Update and sort options list in help
Use CC variable for compiler in Makefile
Exit with code 2 if a warning has been issued
Fix thread synchronization problem when tracing
Change macro name MAX to MAX2 to avoid library conflicts
Determine number of processors on HP-UX [Lloyd]
2.2 31 Dec 2011 Check for expansion bound busting (e.g. modified zlib)
Make the "threads" list head global variable volatile
Fix construction and printing of 32-bit check values
Add --rsyncable functionality
2.2.1 1 Jan 2012 Fix bug in --rsyncable buffer management
2.2.2 1 Jan 2012 Fix another bug in --rsyncable buffer management
2.2.3 15 Jan 2012 Remove volatile in yarn.c
Reduce the number of input buffers
Change initial rsyncable hash to comparison value
Improve the efficiency of arriving at a byte boundary
Add thread portability #defines from yarn.c
Have rsyncable compression be independent of threading
Fix bug where constructed dictionaries not being used
2.2.4 11 Mar 2012 Avoid some return value warnings
Improve the portability of printing the off_t type
Check for existence of compress binary before using
Update zlib version checking to 1.2.6 for new functions
Fix bug in zip (-K) output
Fix license in pigz.spec
Remove thread portability #defines in pigz.c
2.2.5 28 Jul 2012 Avoid race condition in free_pool()
Change suffix to .tar when decompressing or listing .tgz
Print name of executable in error messages
Show help properly when the name is unpigz or gunzip
Fix permissions security problem before output is closed
2.3 3 Mar 2013 Don't complain about missing suffix on stdout
Put all global variables in a structure for readability
Do not decompress concatenated zlib streams (just gzip)
Add option for compression level 11 to use zopfli
Fix handling of junk after compressed data
2.3.1 9 Oct 2013 Fix builds of pigzt and pigzn to include zopfli
Add -lm, needed to link log function on some systems
Respect LDFLAGS in Makefile, use CFLAGS consistently
Add memory allocation tracking
Fix casting error in uncompressed length calculation
Update zopfli to Mar 10, 2013 Google state
Support zopfli in single thread case
Add -F, -I, -M, and -O options for zopfli tuning
2.3.2 xx Jan 2015 -
*/
#define VERSION "pigz 2.3.2\n"
/* To-do:
- make source portable for Windows, VMS, etc. (see gzip source code)
- make build portable (currently good for Unixish)
*/
/*
pigz compresses using threads to make use of multiple processors and cores.
The input is broken up into 128 KB chunks with each compressed in parallel.
The individual check value for each chunk is also calculated in parallel.
The compressed data is written in order to the output, and a combined check
value is calculated from the individual check values.
The compressed data format generated is in the gzip, zlib, or single-entry
zip format using the deflate compression method. The compression produces
partial raw deflate streams which are concatenated by a single write thread
and wrapped with the appropriate header and trailer, where the trailer
contains the combined check value.
Each partial raw deflate stream is terminated by an empty stored block
(using the Z_SYNC_FLUSH option of zlib), in order to end that partial bit
stream at a byte boundary, unless that partial stream happens to already end
at a byte boundary (the latter requires zlib 1.2.6 or later). Ending on a
byte boundary allows the partial streams to be concatenated simply as
sequences of bytes. This adds a very small four to five byte overhead
(average 3.75 bytes) to the output for each input chunk.
The default input block size is 128K, but can be changed with the -b option.
The number of compress threads is set by default to 8, which can be changed
using the -p option. Specifying -p 1 avoids the use of threads entirely.
pigz will try to determine the number of processors in the machine, in which
case if that number is two or greater, pigz will use that as the default for
-p instead of 8.
The input blocks, while compressed independently, have the last 32K of the
previous block loaded as a preset dictionary to preserve the compression
effectiveness of deflating in a single thread. This can be turned off using
the --independent or -i option, so that the blocks can be decompressed
independently for partial error recovery or for random access.
Decompression can't be parallelized, at least not without specially prepared
deflate streams for that purpose. As a result, pigz uses a single thread
(the main thread) for decompression, but will create three other threads for
reading, writing, and check calculation, which can speed up decompression
under some circumstances. Parallel decompression can be turned off by
specifying one process (-dp 1 or -tp 1).
pigz requires zlib 1.2.1 or later to allow setting the dictionary when doing
raw deflate. Since zlib 1.2.3 corrects security vulnerabilities in zlib
version 1.2.1 and 1.2.2, conditionals check for zlib 1.2.3 or later during
the compilation of pigz.c. zlib 1.2.4 includes some improvements to
Z_FULL_FLUSH and deflateSetDictionary() that permit identical output for
pigz with and without threads, which is not possible with zlib 1.2.3. This
may be important for uses of pigz -R where small changes in the contents
should result in small changes in the archive for rsync. Note that due to
the details of how the lower levels of compression result in greater speed,
compression level 3 and below does not permit identical pigz output with
and without threads.
pigz uses the POSIX pthread library for thread control and communication,
through the yarn.h interface to yarn.c. yarn.c can be replaced with
equivalent implementations using other thread libraries. pigz can be
compiled with NOTHREAD #defined to not use threads at all (in which case
pigz will not be able to live up to the "parallel" in its name).
*/
/*
Details of parallel compression implementation:
When doing parallel compression, pigz uses the main thread to read the input
in 'size' sized chunks (see -b), and puts those in a compression job list,
each with a sequence number to keep track of the ordering. If it is not the
first chunk, then that job also points to the previous input buffer, from
which the last 32K will be used as a dictionary (unless -i is specified).
This sets a lower limit of 32K on 'size'.
pigz launches up to 'procs' compression threads (see -p). Each compression
thread continues to look for jobs in the compression list and perform those
jobs until instructed to return. When a job is pulled, the dictionary, if
provided, will be loaded into the deflate engine and then that input buffer
is dropped for reuse. Then the input data is compressed into an output
buffer that grows in size if necessary to hold the compressed data. The job
is then put into the write job list, sorted by the sequence number. The
compress thread however continues to calculate the check value on the input
data, either a CRC-32 or Adler-32, possibly in parallel with the write
thread writing the output data. Once that's done, the compress thread drops
the input buffer and also releases the lock on the check value so that the
write thread can combine it with the previous check values. The compress
thread has then completed that job, and goes to look for another.
All of the compress threads are left running and waiting even after the last
chunk is processed, so that they can support the next input to be compressed
(more than one input file on the command line). Once pigz is done, it will
call all the compress threads home (that'll do pig, that'll do).
Before starting to read the input, the main thread launches the write thread
so that it is ready pick up jobs immediately. The compress thread puts the
write jobs in the list in sequence sorted order, so that the first job in
the list is always has the lowest sequence number. The write thread waits
for the next write job in sequence, and then gets that job. The job still
holds its input buffer, from which the write thread gets the input buffer
length for use in check value combination. Then the write thread drops that
input buffer to allow its reuse. Holding on to the input buffer until the
write thread starts also has the benefit that the read and compress threads
can't get way ahead of the write thread and build up a large backlog of
unwritten compressed data. The write thread will write the compressed data,
drop the output buffer, and then wait for the check value to be unlocked
by the compress thread. Then the write thread combines the check value for
this chunk with the total check value for eventual use in the trailer. If
this is not the last chunk, the write thread then goes back to look for the
next output chunk in sequence. After the last chunk, the write thread
returns and joins the main thread. Unlike the compress threads, a new write
thread is launched for each input stream. The write thread writes the
appropriate header and trailer around the compressed data.
The input and output buffers are reused through their collection in pools.
Each buffer has a use count, which when decremented to zero returns the
buffer to the respective pool. Each input buffer has up to three parallel
uses: as the input for compression, as the data for the check value
calculation, and as a dictionary for compression. Each output buffer has
only one use, which is as the output of compression followed serially as
data to be written. The input pool is limited in the number of buffers, so
that reading does not get way ahead of compression and eat up memory with
more input than can be used. The limit is approximately two times the
number of compression threads. In the case that reading is fast as compared
to compression, that number allows a second set of buffers to be read while
the first set of compressions are being performed. The number of output
buffers is not directly limited, but is indirectly limited by the release of
input buffers to about the same number.
*/
/* use large file functions if available */
#define _FILE_OFFSET_BITS 64
/* included headers and what is expected from each */
#include <stdio.h> /* fflush(), fprintf(), fputs(), getchar(), putc(), */
/* puts(), printf(), vasprintf(), stderr, EOF, NULL,
SEEK_END, size_t, off_t */
#include <stdlib.h> /* exit(), malloc(), free(), realloc(), atol(), */
/* atoi(), getenv() */
#include <stdarg.h> /* va_start(), va_end(), va_list */
#include <string.h> /* memset(), memchr(), memcpy(), strcmp(), strcpy() */
/* strncpy(), strlen(), strcat(), strrchr() */
#include <errno.h> /* errno, EEXIST */
#include <assert.h> /* assert() */
#include <time.h> /* ctime(), time(), time_t, mktime() */
#include <signal.h> /* signal(), SIGINT */
#include <sys/types.h> /* ssize_t */
#include <sys/stat.h> /* chmod(), stat(), fstat(), lstat(), struct stat, */
/* S_IFDIR, S_IFLNK, S_IFMT, S_IFREG */
#include <sys/time.h> /* utimes(), gettimeofday(), struct timeval */
#include <unistd.h> /* unlink(), _exit(), read(), write(), close(), */
/* lseek(), isatty(), chown() */
#include <fcntl.h> /* open(), O_CREAT, O_EXCL, O_RDONLY, O_TRUNC, */
/* O_WRONLY */
#include <dirent.h> /* opendir(), readdir(), closedir(), DIR, */
/* struct dirent */
#include <limits.h> /* PATH_MAX, UINT_MAX, INT_MAX */
#if __STDC_VERSION__-0 >= 199901L || __GNUC__-0 >= 3
# include <inttypes.h> /* intmax_t */
#endif
#ifdef DEBUG
# if defined(__APPLE__)
# include <malloc/malloc.h>
# define MALLOC_SIZE(p) malloc_size(p)
# elif defined (__linux)
# include <malloc.h>
# define MALLOC_SIZE(p) malloc_usable_size(p)
# elif defined (_WIN32) || defined(_WIN64)
# include <malloc.h>
# define MALLOC_SIZE(p) _msize(p)
# else
# define MALLOC_SIZE(p) (0)
# endif
#endif
#ifdef __hpux
# include <sys/param.h>
# include <sys/pstat.h>
#endif
#include "zlib.h" /* deflateInit2(), deflateReset(), deflate(), */
/* deflateEnd(), deflateSetDictionary(), crc32(),
inflateBackInit(), inflateBack(), inflateBackEnd(),
Z_DEFAULT_COMPRESSION, Z_DEFAULT_STRATEGY,
Z_DEFLATED, Z_NO_FLUSH, Z_NULL, Z_OK,
Z_SYNC_FLUSH, z_stream */
#if !defined(ZLIB_VERNUM) || ZLIB_VERNUM < 0x1230
# error Need zlib version 1.2.3 or later
#endif
#ifndef NOTHREAD
# include "yarn.h" /* thread, launch(), join(), join_all(), */
/* lock, new_lock(), possess(), twist(), wait_for(),
release(), peek_lock(), free_lock(), yarn_name */
#endif
#include "zopfli/src/zopfli/deflate.h" /* ZopfliDeflatePart(),
ZopfliInitOptions(),
ZopfliOptions */
/* for local functions and globals */
#define local static
/* prevent end-of-line conversions on MSDOSish operating systems */
#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
# include <io.h> /* setmode(), O_BINARY */
# define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
#else
# define SET_BINARY_MODE(fd)
#endif
/* release an allocated pointer, if allocated, and mark as unallocated */
#define RELEASE(ptr) \
do { \
if ((ptr) != NULL) { \
FREE(ptr); \
ptr = NULL; \
} \
} while (0)
/* sliding dictionary size for deflate */
#define DICT 32768U
/* largest power of 2 that fits in an unsigned int -- used to limit requests
to zlib functions that use unsigned int lengths */
#define MAXP2 (UINT_MAX - (UINT_MAX >> 1))
/* rsyncable constants -- RSYNCBITS is the number of bits in the mask for
comparison. For random input data, there will be a hit on average every
1<<RSYNCBITS bytes. So for an RSYNCBITS of 12, there will be an average of
one hit every 4096 bytes, resulting in a mean block size of 4096. RSYNCMASK
is the resulting bit mask. RSYNCHIT is what the hash value is compared to
after applying the mask.
The choice of 12 for RSYNCBITS is consistent with the original rsyncable
patch for gzip which also uses a 12-bit mask. This results in a relatively
small hit to compression, on the order of 1.5% to 3%. A mask of 13 bits can
be used instead if a hit of less than 1% to the compression is desired, at
the expense of more blocks transmitted for rsync updates. (Your mileage may
vary.)
This implementation of rsyncable uses a different hash algorithm than what
the gzip rsyncable patch uses in order to provide better performance in
several regards. The algorithm is simply to shift the hash value left one
bit and exclusive-or that with the next byte. This is masked to the number
of hash bits (RSYNCMASK) and compared to all ones except for a zero in the
top bit (RSYNCHIT). This rolling hash has a very small window of 19 bytes
(RSYNCBITS+7). The small window provides the benefit of much more rapid
resynchronization after a change, than does the 4096-byte window of the gzip
rsyncable patch.
The comparison value is chosen to avoid matching any repeated bytes or short
sequences. The gzip rsyncable patch on the other hand uses a sum and zero
for comparison, which results in certain bad behaviors, such as always
matching everywhere in a long sequence of zeros. Such sequences occur
frequently in tar files.
This hash efficiently discards history older than 19 bytes simply by
shifting that data past the top of the mask -- no history needs to be
retained to undo its impact on the hash value, as is needed for a sum.
The choice of the comparison value (RSYNCHIT) has the virtue of avoiding
extremely short blocks. The shortest block is five bytes (RSYNCBITS-7) from
hit to hit, and is unlikely. Whereas with the gzip rsyncable algorithm,
blocks of one byte are not only possible, but in fact are the most likely
block size.
Thanks and acknowledgement to Kevin Day for his experimentation and insights
on rsyncable hash characteristics that led to some of the choices here.
*/
#define RSYNCBITS 12
#define RSYNCMASK ((1U << RSYNCBITS) - 1)
#define RSYNCHIT (RSYNCMASK >> 1)
/* initial pool counts and sizes -- INBUFS is the limit on the number of input
spaces as a function of the number of processors (used to throttle the
creation of compression jobs), OUTPOOL is the initial size of the output
data buffer, chosen to make resizing of the buffer very unlikely and to
allow prepending with a dictionary for use as an input buffer for zopfli */
#define INBUFS(p) (((p)<<1)+3)
#define OUTPOOL(s) ((s)+((s)>>4)+DICT)
/* input buffer size */
#define BUF 32768U
/* globals (modified by main thread only when it's the only thread) */
local struct {
char *prog; /* name by which pigz was invoked */
int ind; /* input file descriptor */
int outd; /* output file descriptor */
char inf[PATH_MAX+1]; /* input file name (accommodate recursion) */
char *outf; /* output file name (allocated if not NULL) */
int verbosity; /* 0 = quiet, 1 = normal, 2 = verbose, 3 = trace */
int headis; /* 1 to store name, 2 to store date, 3 both */
int pipeout; /* write output to stdout even if file */
int keep; /* true to prevent deletion of input file */
int force; /* true to overwrite, compress links, cat */
int form; /* gzip = 0, zlib = 1, zip = 2 or 3 */
unsigned char magic1; /* first byte of possible header when decoding */
int recurse; /* true to dive down into directory structure */
char *sufx; /* suffix to use (".gz" or user supplied) */
char *name; /* name for gzip header */
time_t mtime; /* time stamp from input file for gzip header */
int list; /* true to list files instead of compress */
int first; /* true if we need to print listing header */
int decode; /* 0 to compress, 1 to decompress, 2 to test */
int level; /* compression level */
ZopfliOptions zopts; /* zopfli compression options */
int rsync; /* true for rsync blocking */
int procs; /* maximum number of compression threads (>= 1) */
int setdict; /* true to initialize dictionary in each thread */
size_t block; /* uncompressed input size per thread (>= 32K) */
/* saved gzip/zip header data for decompression, testing, and listing */
time_t stamp; /* time stamp from gzip header */
char *hname; /* name from header (allocated) */
unsigned long zip_crc; /* local header crc */
unsigned long zip_clen; /* local header compressed length */
unsigned long zip_ulen; /* local header uncompressed length */
/* globals for decompression and listing buffered reading */
unsigned char in_buf[BUF]; /* input buffer */
unsigned char *in_next; /* next unused byte in buffer */
size_t in_left; /* number of unused bytes in buffer */
int in_eof; /* true if reached end of file on input */
int in_short; /* true if last read didn't fill buffer */
off_t in_tot; /* total bytes read from input */
off_t out_tot; /* total bytes written to output */
unsigned long out_check; /* check value of output */
#ifndef NOTHREAD
/* globals for decompression parallel reading */
unsigned char in_buf2[BUF]; /* second buffer for parallel reads */
size_t in_len; /* data waiting in next buffer */
int in_which; /* -1: start, 0: in_buf2, 1: in_buf */
lock *load_state; /* value = 0 to wait, 1 to read a buffer */
thread *load_thread; /* load_read() thread for joining */
#endif
} g;
/* display a complaint with the program name on stderr */
local int complain(char *fmt, ...)
{
va_list ap;
if (g.verbosity > 0) {
fprintf(stderr, "%s: ", g.prog);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
putc('\n', stderr);
fflush(stderr);
}
return 0;
}
/* exit with error, delete output file if in the middle of writing it */
local int bail(char *why, char *what)
{
if (g.outd != -1 && g.outf != NULL)
unlink(g.outf);
complain("abort: %s%s", why, what);
exit(1);
return 0;
}
#ifdef DEBUG
/* memory tracking */
local struct mem_track_s {
size_t num; /* current number of allocations */
size_t size; /* total size of current allocations */
size_t max; /* maximum size of allocations */
#ifndef NOTHREAD
lock *lock; /* lock for access across threads */
#endif
} mem_track;
#ifndef NOTHREAD
# define mem_track_grab(m) possess((m)->lock)
# define mem_track_drop(m) release((m)->lock)
#else
# define mem_track_grab(m)
# define mem_track_drop(m)
#endif
local void *malloc_track(struct mem_track_s *mem, size_t size)
{
void *ptr;
ptr = malloc(size);
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->num++;
mem->size += size;
if (mem->size > mem->max)
mem->max = mem->size;
mem_track_drop(mem);
}
return ptr;
}
local void *realloc_track(struct mem_track_s *mem, void *ptr, size_t size)
{
size_t was;
if (ptr == NULL)
return malloc_track(mem, size);
was = MALLOC_SIZE(ptr);
ptr = realloc(ptr, size);
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->size -= was;
mem->size += size;
if (mem->size > mem->max)
mem->max = mem->size;
mem_track_drop(mem);
}
return ptr;
}
local void free_track(struct mem_track_s *mem, void *ptr)
{
size_t size;
if (ptr != NULL) {
size = MALLOC_SIZE(ptr);
mem_track_grab(mem);
mem->num--;
mem->size -= size;
mem_track_drop(mem);
free(ptr);
}
}
#ifndef NOTHREAD
local void *yarn_malloc(size_t size)
{
return malloc_track(&mem_track, size);
}
local void yarn_free(void *ptr)
{
return free_track(&mem_track, ptr);
}
#endif
local voidpf zlib_alloc(voidpf opaque, uInt items, uInt size)
{
return malloc_track(opaque, items * (size_t)size);
}
local void zlib_free(voidpf opaque, voidpf address)
{
free_track(opaque, address);
}
#define MALLOC(s) malloc_track(&mem_track, s)
#define REALLOC(p, s) realloc_track(&mem_track, p, s)
#define FREE(p) free_track(&mem_track, p)
#define OPAQUE (&mem_track)
#define ZALLOC zlib_alloc
#define ZFREE zlib_free
/* starting time of day for tracing */
local struct timeval start;
/* trace log */
local struct log {
struct timeval when; /* time of entry */
char *msg; /* message */
struct log *next; /* next entry */
} *log_head, **log_tail = NULL;
#ifndef NOTHREAD
local lock *log_lock = NULL;
#endif
/* maximum log entry length */
#define MAXMSG 256
/* set up log (call from main thread before other threads launched) */
local void log_init(void)
{
if (log_tail == NULL) {
mem_track.num = 0;
mem_track.size = 0;
mem_track.max = 0;
#ifndef NOTHREAD
mem_track.lock = new_lock(0);
yarn_mem(yarn_malloc, yarn_free);
log_lock = new_lock(0);
#endif
log_head = NULL;
log_tail = &log_head;
}
}
/* add entry to trace log */
local void log_add(char *fmt, ...)
{
struct timeval now;
struct log *me;
va_list ap;
char msg[MAXMSG];
gettimeofday(&now, NULL);
me = MALLOC(sizeof(struct log));
if (me == NULL)
bail("not enough memory", "");
me->when = now;
va_start(ap, fmt);
vsnprintf(msg, MAXMSG, fmt, ap);
va_end(ap);
me->msg = MALLOC(strlen(msg) + 1);
if (me->msg == NULL) {
FREE(me);
bail("not enough memory", "");
}
strcpy(me->msg, msg);
me->next = NULL;
#ifndef NOTHREAD
assert(log_lock != NULL);
possess(log_lock);
#endif
*log_tail = me;
log_tail = &(me->next);
#ifndef NOTHREAD
twist(log_lock, BY, +1);
#endif
}
/* pull entry from trace log and print it, return false if empty */
local int log_show(void)
{
struct log *me;
struct timeval diff;
if (log_tail == NULL)
return 0;
#ifndef NOTHREAD
possess(log_lock);
#endif
me = log_head;
if (me == NULL) {
#ifndef NOTHREAD
release(log_lock);
#endif
return 0;
}
log_head = me->next;
if (me->next == NULL)
log_tail = &log_head;
#ifndef NOTHREAD
twist(log_lock, BY, -1);
#endif
diff.tv_usec = me->when.tv_usec - start.tv_usec;
diff.tv_sec = me->when.tv_sec - start.tv_sec;
if (diff.tv_usec < 0) {
diff.tv_usec += 1000000L;
diff.tv_sec--;
}
fprintf(stderr, "trace %ld.%06ld %s\n",
(long)diff.tv_sec, (long)diff.tv_usec, me->msg);
fflush(stderr);
FREE(me->msg);
FREE(me);
return 1;
}
/* release log resources (need to do log_init() to use again) */
local void log_free(void)
{
struct log *me;
if (log_tail != NULL) {
#ifndef NOTHREAD
possess(log_lock);
#endif
while ((me = log_head) != NULL) {
log_head = me->next;
FREE(me->msg);
FREE(me);
}
#ifndef NOTHREAD
twist(log_lock, TO, 0);
free_lock(log_lock);
log_lock = NULL;
yarn_mem(malloc, free);
free_lock(mem_track.lock);
#endif
log_tail = NULL;
}
}
/* show entries until no more, free log */
local void log_dump(void)
{
if (log_tail == NULL)
return;
while (log_show())
;
log_free();
if (mem_track.num || mem_track.size)
complain("memory leak: %lu allocs of %lu bytes total",
mem_track.num, mem_track.size);
if (mem_track.max)
fprintf(stderr, "%lu bytes of memory used\n", mem_track.max);
}
/* debugging macro */
#define Trace(x) \
do { \
if (g.verbosity > 2) { \
log_add x; \
} \
} while (0)
#else /* !DEBUG */
#define MALLOC malloc
#define REALLOC realloc
#define FREE free
#define OPAQUE Z_NULL
#define ZALLOC Z_NULL
#define ZFREE Z_NULL
#define log_dump()
#define Trace(x)
#endif
/* read up to len bytes into buf, repeating read() calls as needed */
local size_t readn(int desc, unsigned char *buf, size_t len)
{
ssize_t ret;
size_t got;
got = 0;
while (len) {
ret = read(desc, buf, len);
if (ret < 0)
bail("read error on ", g.inf);
if (ret == 0)
break;
buf += ret;
len -= ret;
got += ret;
}
return got;
}
/* write len bytes, repeating write() calls as needed */
local void writen(int desc, unsigned char *buf, size_t len)
{
ssize_t ret;
while (len) {
ret = write(desc, buf, len);
if (ret < 1) {
complain("write error code %d", errno);
bail("write error on ", g.outf);
}
buf += ret;
len -= ret;
}
}
/* convert Unix time to MS-DOS date and time, assuming current timezone
(you got a better idea?) */
local unsigned long time2dos(time_t t)
{
struct tm *tm;
unsigned long dos;
if (t == 0)
t = time(NULL);
tm = localtime(&t);
if (tm->tm_year < 80 || tm->tm_year > 207)
return 0;
dos = (tm->tm_year - 80) << 25;
dos += (tm->tm_mon + 1) << 21;
dos += tm->tm_mday << 16;
dos += tm->tm_hour << 11;
dos += tm->tm_min << 5;
dos += (tm->tm_sec + 1) >> 1; /* round to double-seconds */
return dos;
}
/* put a 4-byte integer into a byte array in LSB order or MSB order */
#define PUT2L(a,b) (*(a)=(b)&0xff,(a)[1]=(b)>>8)
#define PUT4L(a,b) (PUT2L(a,(b)&0xffff),PUT2L((a)+2,(b)>>16))
#define PUT4M(a,b) (*(a)=(b)>>24,(a)[1]=(b)>>16,(a)[2]=(b)>>8,(a)[3]=(b))
/* write a gzip, zlib, or zip header using the information in the globals */
local unsigned long put_header(void)
{
unsigned long len;
unsigned char head[30];
if (g.form > 1) { /* zip */
/* write local header */
PUT4L(head, 0x04034b50UL); /* local header signature */
PUT2L(head + 4, 20); /* version needed to extract (2.0) */
PUT2L(head + 6, 8); /* flags: data descriptor follows data */
PUT2L(head + 8, 8); /* deflate */
PUT4L(head + 10, time2dos(g.mtime));
PUT4L(head + 14, 0); /* crc (not here) */
PUT4L(head + 18, 0); /* compressed length (not here) */
PUT4L(head + 22, 0); /* uncompressed length (not here) */
PUT2L(head + 26, g.name == NULL ? 1 : /* length of name */
strlen(g.name));
PUT2L(head + 28, 9); /* length of extra field (see below) */
writen(g.outd, head, 30); /* write local header */
len = 30;
/* write file name (use "-" for stdin) */
if (g.name == NULL)
writen(g.outd, (unsigned char *)"-", 1);
else
writen(g.outd, (unsigned char *)g.name, strlen(g.name));
len += g.name == NULL ? 1 : strlen(g.name);
/* write extended timestamp extra field block (9 bytes) */
PUT2L(head, 0x5455); /* extended timestamp signature */
PUT2L(head + 2, 5); /* number of data bytes in this block */
head[4] = 1; /* flag presence of mod time */
PUT4L(head + 5, g.mtime); /* mod time */
writen(g.outd, head, 9); /* write extra field block */
len += 9;
}
else if (g.form) { /* zlib */
head[0] = 0x78; /* deflate, 32K window */
head[1] = (g.level >= 9 ? 3 :
(g.level == 1 ? 0 :
(g.level >= 6 || g.level == Z_DEFAULT_COMPRESSION ?
1 : 2))) << 6;
head[1] += 31 - (((head[0] << 8) + head[1]) % 31);
writen(g.outd, head, 2);
len = 2;
}
else { /* gzip */
head[0] = 31;
head[1] = 139;
head[2] = 8; /* deflate */
head[3] = g.name != NULL ? 8 : 0;
PUT4L(head + 4, g.mtime);
head[8] = g.level >= 9 ? 2 : (g.level == 1 ? 4 : 0);
head[9] = 3; /* unix */
writen(g.outd, head, 10);
len = 10;
if (g.name != NULL)
writen(g.outd, (unsigned char *)g.name, strlen(g.name) + 1);
if (g.name != NULL)
len += strlen(g.name) + 1;
}
return len;
}
/* write a gzip, zlib, or zip trailer */
local void put_trailer(unsigned long ulen, unsigned long clen,
unsigned long check, unsigned long head)
{
unsigned char tail[46];
if (g.form > 1) { /* zip */
unsigned long cent;
/* write data descriptor (as promised in local header) */
PUT4L(tail, 0x08074b50UL);
PUT4L(tail + 4, check);
PUT4L(tail + 8, clen);
PUT4L(tail + 12, ulen);
writen(g.outd, tail, 16);
/* write central file header */
PUT4L(tail, 0x02014b50UL); /* central header signature */
tail[4] = 63; /* obeyed version 6.3 of the zip spec */
tail[5] = 255; /* ignore external attributes */
PUT2L(tail + 6, 20); /* version needed to extract (2.0) */
PUT2L(tail + 8, 8); /* data descriptor is present */
PUT2L(tail + 10, 8); /* deflate */
PUT4L(tail + 12, time2dos(g.mtime));
PUT4L(tail + 16, check); /* crc */
PUT4L(tail + 20, clen); /* compressed length */
PUT4L(tail + 24, ulen); /* uncompressed length */
PUT2L(tail + 28, g.name == NULL ? 1 : /* length of name */
strlen(g.name));
PUT2L(tail + 30, 9); /* length of extra field (see below) */
PUT2L(tail + 32, 0); /* no file comment */
PUT2L(tail + 34, 0); /* disk number 0 */
PUT2L(tail + 36, 0); /* internal file attributes */
PUT4L(tail + 38, 0); /* external file attributes (ignored) */
PUT4L(tail + 42, 0); /* offset of local header */
writen(g.outd, tail, 46); /* write central file header */
cent = 46;
/* write file name (use "-" for stdin) */
if (g.name == NULL)
writen(g.outd, (unsigned char *)"-", 1);
else
writen(g.outd, (unsigned char *)g.name, strlen(g.name));
cent += g.name == NULL ? 1 : strlen(g.name);
/* write extended timestamp extra field block (9 bytes) */
PUT2L(tail, 0x5455); /* extended timestamp signature */
PUT2L(tail + 2, 5); /* number of data bytes in this block */
tail[4] = 1; /* flag presence of mod time */
PUT4L(tail + 5, g.mtime); /* mod time */
writen(g.outd, tail, 9); /* write extra field block */
cent += 9;
/* write end of central directory record */
PUT4L(tail, 0x06054b50UL); /* end of central directory signature */
PUT2L(tail + 4, 0); /* number of this disk */
PUT2L(tail + 6, 0); /* disk with start of central directory */
PUT2L(tail + 8, 1); /* number of entries on this disk */
PUT2L(tail + 10, 1); /* total number of entries */
PUT4L(tail + 12, cent); /* size of central directory */
PUT4L(tail + 16, head + clen + 16); /* offset of central directory */
PUT2L(tail + 20, 0); /* no zip file comment */
writen(g.outd, tail, 22); /* write end of central directory record */
}
else if (g.form) { /* zlib */
PUT4M(tail, check);
writen(g.outd, tail, 4);
}
else { /* gzip */
PUT4L(tail, check);
PUT4L(tail + 4, ulen);
writen(g.outd, tail, 8);
}
}
/* compute check value depending on format */
#define CHECK(a,b,c) (g.form == 1 ? adler32(a,b,c) : crc32(a,b,c))
#ifndef NOTHREAD
/* -- threaded portions of pigz -- */
/* -- check value combination routines for parallel calculation -- */
#define COMB(a,b,c) (g.form == 1 ? adler32_comb(a,b,c) : crc32_comb(a,b,c))
/* combine two crc-32's or two adler-32's (copied from zlib 1.2.3 so that pigz
can be compatible with older versions of zlib) */
/* we copy the combination routines from zlib here, in order to avoid
linkage issues with the zlib 1.2.3 builds on Sun, Ubuntu, and others */
local unsigned long gf2_matrix_times(unsigned long *mat, unsigned long vec)
{
unsigned long sum;
sum = 0;
while (vec) {
if (vec & 1)
sum ^= *mat;
vec >>= 1;
mat++;
}
return sum;
}
local void gf2_matrix_square(unsigned long *square, unsigned long *mat)
{
int n;
for (n = 0; n < 32; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
local unsigned long crc32_comb(unsigned long crc1, unsigned long crc2,
size_t len2)
{
int n;
unsigned long row;
unsigned long even[32]; /* even-power-of-two zeros operator */
unsigned long odd[32]; /* odd-power-of-two zeros operator */
/* degenerate case */
if (len2 == 0)
return crc1;
/* put operator for one zero bit in odd */
odd[0] = 0xedb88320UL; /* CRC-32 polynomial */
row = 1;
for (n = 1; n < 32; n++) {
odd[n] = row;
row <<= 1;
}
/* put operator for two zero bits in even */
gf2_matrix_square(even, odd);
/* put operator for four zero bits in odd */
gf2_matrix_square(odd, even);
/* apply len2 zeros to crc1 (first square will put the operator for one
zero byte, eight zero bits, in even) */
do {
/* apply zeros operator for this bit of len2 */
gf2_matrix_square(even, odd);
if (len2 & 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
/* if no more bits set, then done */
if (len2 == 0)
break;
/* another iteration of the loop with odd and even swapped */
gf2_matrix_square(odd, even);
if (len2 & 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
/* if no more bits set, then done */
} while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}
#define BASE 65521U /* largest prime smaller than 65536 */
#define LOW16 0xffff /* mask lower 16 bits */
local unsigned long adler32_comb(unsigned long adler1, unsigned long adler2,
size_t len2)
{
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* the derivation of this formula is left as an exercise for the reader */
rem = (unsigned)(len2 % BASE);
sum1 = adler1 & LOW16;
sum2 = (rem * sum1) % BASE;
sum1 += (adler2 & LOW16) + BASE - 1;
sum2 += ((adler1 >> 16) & LOW16) + ((adler2 >> 16) & LOW16) + BASE - rem;
if (sum1 >= BASE) sum1 -= BASE;
if (sum1 >= BASE) sum1 -= BASE;
if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 >= BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
}
/* -- pool of spaces for buffer management -- */
/* These routines manage a pool of spaces. Each pool specifies a fixed size
buffer to be contained in each space. Each space has a use count, which
when decremented to zero returns the space to the pool. If a space is
requested from the pool and the pool is empty, a space is immediately
created unless a specified limit on the number of spaces has been reached.
Only if the limit is reached will it wait for a space to be returned to the
pool. Each space knows what pool it belongs to, so that it can be returned.
*/
/* a space (one buffer for each space) */
struct space {
lock *use; /* use count -- return to pool when zero */
unsigned char *buf; /* buffer of size size */
size_t size; /* current size of this buffer */
size_t len; /* for application usage (initially zero) */
struct pool *pool; /* pool to return to */
struct space *next; /* for pool linked list */
};
/* pool of spaces (one pool for each type needed) */
struct pool {
lock *have; /* unused spaces available, lock for list */
struct space *head; /* linked list of available buffers */
size_t size; /* size of new buffers in this pool */
int limit; /* number of new spaces allowed, or -1 */
int made; /* number of buffers made */
};
/* initialize a pool (pool structure itself provided, not allocated) -- the
limit is the maximum number of spaces in the pool, or -1 to indicate no
limit, i.e., to never wait for a buffer to return to the pool */
local void new_pool(struct pool *pool, size_t size, int limit)
{
pool->have = new_lock(0);
pool->head = NULL;
pool->size = size;
pool->limit = limit;
pool->made = 0;
}
/* get a space from a pool -- the use count is initially set to one, so there
is no need to call use_space() for the first use */
local struct space *get_space(struct pool *pool)
{
struct space *space;
/* if can't create any more, wait for a space to show up */
possess(pool->have);
if (pool->limit == 0)
wait_for(pool->have, NOT_TO_BE, 0);
/* if a space is available, pull it from the list and return it */
if (pool->head != NULL) {
space = pool->head;
possess(space->use);
pool->head = space->next;
twist(pool->have, BY, -1); /* one less in pool */
twist(space->use, TO, 1); /* initially one user */
space->len = 0;
return space;
}
/* nothing available, don't want to wait, make a new space */
assert(pool->limit != 0);
if (pool->limit > 0)
pool->limit--;
pool->made++;
release(pool->have);
space = MALLOC(sizeof(struct space));
if (space == NULL)
bail("not enough memory", "");
space->use = new_lock(1); /* initially one user */
space->buf = MALLOC(pool->size);
if (space->buf == NULL)
bail("not enough memory", "");
space->size = pool->size;
space->len = 0;
space->pool = pool; /* remember the pool this belongs to */
return space;
}
/* compute next size up by multiplying by about 2**(1/3) and round to the next
power of 2 if we're close (so three applications results in doubling) -- if
small, go up to at least 16, if overflow, go to max size_t value */
local size_t grow(size_t size)
{
size_t was, top;
int shift;
was = size;
size += size >> 2;
top = size;
for (shift = 0; top > 7; shift++)
top >>= 1;
if (top == 7)
size = (size_t)1 << (shift + 3);
if (size < 16)
size = 16;
if (size <= was)
size = (size_t)0 - 1;
return size;
}
/* increase the size of the buffer in space */
local void grow_space(struct space *space)
{
size_t more;
/* compute next size up */
more = grow(space->size);
if (more == space->size)
bail("not enough memory", "");
/* reallocate the buffer */
space->buf = REALLOC(space->buf, more);
if (space->buf == NULL)
bail("not enough memory", "");
space->size = more;
}
/* increment the use count to require one more drop before returning this space
to the pool */
local void use_space(struct space *space)
{
possess(space->use);
twist(space->use, BY, +1);
}
/* drop a space, returning it to the pool if the use count is zero */
local void drop_space(struct space *space)
{
int use;
struct pool *pool;
possess(space->use);
use = peek_lock(space->use);
assert(use != 0);
if (use == 1) {
pool = space->pool;
possess(pool->have);
space->next = pool->head;
pool->head = space;
twist(pool->have, BY, +1);
}
twist(space->use, BY, -1);
}
/* free the memory and lock resources of a pool -- return number of spaces for
debugging and resource usage measurement */
local int free_pool(struct pool *pool)
{
int count;
struct space *space;
possess(pool->have);
count = 0;
while ((space = pool->head) != NULL) {
pool->head = space->next;
FREE(space->buf);
free_lock(space->use);
FREE(space);
count++;
}
assert(count == pool->made);
release(pool->have);
free_lock(pool->have);
return count;
}
/* input and output buffer pools */
local struct pool in_pool;
local struct pool out_pool;
local struct pool dict_pool;
local struct pool lens_pool;
/* -- parallel compression -- */
/* compress or write job (passed from compress list to write list) -- if seq is
equal to -1, compress_thread is instructed to return; if more is false then
this is the last chunk, which after writing tells write_thread to return */
struct job {
long seq; /* sequence number */
int more; /* true if this is not the last chunk */
struct space *in; /* input data to compress */
struct space *out; /* dictionary or resulting compressed data */
struct space *lens; /* coded list of flush block lengths */
unsigned long check; /* check value for input data */
lock *calc; /* released when check calculation complete */
struct job *next; /* next job in the list (either list) */
};
/* list of compress jobs (with tail for appending to list) */
local lock *compress_have = NULL; /* number of compress jobs waiting */
local struct job *compress_head, **compress_tail;
/* list of write jobs */
local lock *write_first; /* lowest sequence number in list */
local struct job *write_head;
/* number of compression threads running */
local int cthreads = 0;
/* write thread if running */
local thread *writeth = NULL;
/* setup job lists (call from main thread) */
local void setup_jobs(void)
{
/* set up only if not already set up*/
if (compress_have != NULL)
return;
/* allocate locks and initialize lists */
compress_have = new_lock(0);
compress_head = NULL;
compress_tail = &compress_head;
write_first = new_lock(-1);
write_head = NULL;
/* initialize buffer pools (initial size for out_pool not critical, since
buffers will be grown in size if needed -- initial size chosen to make
this unlikely -- same for lens_pool) */
new_pool(&in_pool, g.block, INBUFS(g.procs));
new_pool(&out_pool, OUTPOOL(g.block), -1);
new_pool(&dict_pool, DICT, -1);
new_pool(&lens_pool, g.block >> (RSYNCBITS - 1), -1);
}
/* command the compress threads to all return, then join them all (call from
main thread), free all the thread-related resources */
local void finish_jobs(void)
{
struct job job;
int caught;
/* only do this once */
if (compress_have == NULL)
return;
/* command all of the extant compress threads to return */
possess(compress_have);
job.seq = -1;
job.next = NULL;
compress_head = &job;
compress_tail = &(job.next);
twist(compress_have, BY, +1); /* will wake them all up */
/* join all of the compress threads, verify they all came back */
caught = join_all();
Trace(("-- joined %d compress threads", caught));
assert(caught == cthreads);
cthreads = 0;
/* free the resources */
caught = free_pool(&lens_pool);
Trace(("-- freed %d block lengths buffers", caught));
caught = free_pool(&dict_pool);
Trace(("-- freed %d dictionary buffers", caught));
caught = free_pool(&out_pool);
Trace(("-- freed %d output buffers", caught));
caught = free_pool(&in_pool);
Trace(("-- freed %d input buffers", caught));
free_lock(write_first);
free_lock(compress_have);
compress_have = NULL;
}
/* compress all strm->avail_in bytes at strm->next_in to out->buf, updating
out->len, grow the size of the buffer (out->size) if necessary -- respect
the size limitations of the zlib stream data types (size_t may be larger
than unsigned) */
local void deflate_engine(z_stream *strm, struct space *out, int flush)
{
size_t room;
do {
room = out->size - out->len;
if (room == 0) {
grow_space(out);
room = out->size - out->len;
}
strm->next_out = out->buf + out->len;
strm->avail_out = room < UINT_MAX ? (unsigned)room : UINT_MAX;
(void)deflate(strm, flush);
out->len = strm->next_out - out->buf;
} while (strm->avail_out == 0);
assert(strm->avail_in == 0);
}
/* get the next compression job from the head of the list, compress and compute
the check value on the input, and put a job in the write list with the
results -- keep looking for more jobs, returning when a job is found with a
sequence number of -1 (leave that job in the list for other incarnations to
find) */
local void compress_thread(void *dummy)
{
struct job *job; /* job pulled and working on */
struct job *here, **prior; /* pointers for inserting in write list */
unsigned long check; /* check value of input */
unsigned char *next; /* pointer for blocks, check value data */
size_t left; /* input left to process */
size_t len; /* remaining bytes to compress/check */
#if ZLIB_VERNUM >= 0x1260
int bits; /* deflate pending bits */
#endif
struct space *temp = NULL; /* temporary space for zopfli input */
z_stream strm; /* deflate stream */
(void)dummy;
/* initialize the deflate stream for this thread */
strm.zfree = ZFREE;
strm.zalloc = ZALLOC;
strm.opaque = OPAQUE;
if (deflateInit2(&strm, 6, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK)
bail("not enough memory", "");
/* keep looking for work */
for (;;) {
/* get a job (like I tell my son) */
possess(compress_have);
wait_for(compress_have, NOT_TO_BE, 0);
job = compress_head;
assert(job != NULL);
if (job->seq == -1)
break;
compress_head = job->next;
if (job->next == NULL)
compress_tail = &compress_head;
twist(compress_have, BY, -1);
/* got a job -- initialize and set the compression level (note that if
deflateParams() is called immediately after deflateReset(), there is
no need to initialize the input/output for the stream) */
Trace(("-- compressing #%ld", job->seq));
if (g.level <= 9) {
(void)deflateReset(&strm);
(void)deflateParams(&strm, g.level, Z_DEFAULT_STRATEGY);
}
else {
temp = get_space(&out_pool);
temp->len = 0;
}
/* set dictionary if provided, release that input or dictionary buffer
(not NULL if g.setdict is true and if this is not the first work
unit) */
if (job->out != NULL) {
len = job->out->len;
left = len < DICT ? len : DICT;
if (g.level <= 9)
deflateSetDictionary(&strm, job->out->buf + (len - left),
left);
else {
memcpy(temp->buf, job->out->buf + (len - left), left);
temp->len = left;
}
drop_space(job->out);
}
/* set up input and output */
job->out = get_space(&out_pool);
if (g.level <= 9) {
strm.next_in = job->in->buf;
strm.next_out = job->out->buf;
}
else
memcpy(temp->buf + temp->len, job->in->buf, job->in->len);
/* compress each block, either flushing or finishing */
next = job->lens == NULL ? NULL : job->lens->buf;
left = job->in->len;
job->out->len = 0;
do {
/* decode next block length from blocks list */
len = next == NULL ? 128 : *next++;
if (len < 128) /* 64..32831 */
len = (len << 8) + (*next++) + 64;
else if (len == 128) /* end of list */
len = left;
else if (len < 192) /* 1..63 */
len &= 0x3f;
else if (len < 224){ /* 32832..2129983 */
len = ((len & 0x1f) << 16) + (*next++ << 8);
len += *next++ + 32832U;
}
else { /* 2129984..539000895 */
len = ((len & 0x1f) << 24) + (*next++ << 16);
len += *next++ << 8;
len += *next++ + 2129984UL;
}
left -= len;
if (g.level <= 9) {
/* run MAXP2-sized amounts of input through deflate -- this
loop is needed for those cases where the unsigned type is
smaller than the size_t type, or when len is close to the
limit of the size_t type */
while (len > MAXP2) {
strm.avail_in = MAXP2;
deflate_engine(&strm, job->out, Z_NO_FLUSH);
len -= MAXP2;
}
/* run the last piece through deflate -- end on a byte
boundary, using a sync marker if necessary, or finish the
deflate stream if this is the last block */
strm.avail_in = (unsigned)len;
if (left || job->more) {
#if ZLIB_VERNUM >= 0x1260
deflate_engine(&strm, job->out, Z_BLOCK);
/* add enough empty blocks to get to a byte boundary */
(void)deflatePending(&strm, Z_NULL, &bits);
if (bits & 1)
deflate_engine(&strm, job->out, Z_SYNC_FLUSH);
else if (bits & 7) {
do { /* add static empty blocks */
bits = deflatePrime(&strm, 10, 2);
assert(bits == Z_OK);
(void)deflatePending(&strm, Z_NULL, &bits);
} while (bits & 7);
deflate_engine(&strm, job->out, Z_BLOCK);
}
#else
deflate_engine(&strm, job->out, Z_SYNC_FLUSH);
#endif
}
else
deflate_engine(&strm, job->out, Z_FINISH);
}
else {
/* compress len bytes using zopfli, bring to byte boundary */
unsigned char bits, *out;
size_t outsize;
out = NULL;
outsize = 0;
bits = 0;
ZopfliDeflatePart(&g.zopts, 2, !(left || job->more),
temp->buf, temp->len, temp->len + len,
&bits, &out, &outsize);
assert(job->out->len + outsize + 5 <= job->out->size);
memcpy(job->out->buf + job->out->len, out, outsize);
free(out);
job->out->len += outsize;
if (left || job->more) {
bits &= 7;
if (bits & 1) {
if (bits == 7)
job->out->buf[job->out->len++] = 0;
job->out->buf[job->out->len++] = 0;
job->out->buf[job->out->len++] = 0;
job->out->buf[job->out->len++] = 0xff;
job->out->buf[job->out->len++] = 0xff;
}
else if (bits) {
do {
job->out->buf[job->out->len - 1] += 2 << bits;
job->out->buf[job->out->len++] = 0;
bits += 2;
} while (bits < 8);
}
}
temp->len += len;
}
} while (left);
if (g.level > 9)
drop_space(temp);
if (job->lens != NULL) {
drop_space(job->lens);
job->lens = NULL;
}
Trace(("-- compressed #%ld%s", job->seq, job->more ? "" : " (last)"));
/* reserve input buffer until check value has been calculated */
use_space(job->in);
/* insert write job in list in sorted order, alert write thread */
possess(write_first);
prior = &write_head;
while ((here = *prior) != NULL) {
if (here->seq > job->seq)
break;
prior = &(here->next);
}
job->next = here;
*prior = job;
twist(write_first, TO, write_head->seq);
/* calculate the check value in parallel with writing, alert the write
thread that the calculation is complete, and drop this usage of the
input buffer */
len = job->in->len;
next = job->in->buf;
check = CHECK(0L, Z_NULL, 0);
while (len > MAXP2) {
check = CHECK(check, next, MAXP2);
len -= MAXP2;
next += MAXP2;
}
check = CHECK(check, next, (unsigned)len);
drop_space(job->in);
job->check = check;
Trace(("-- checked #%ld%s", job->seq, job->more ? "" : " (last)"));
possess(job->calc);
twist(job->calc, TO, 1);
/* done with that one -- go find another job */
}
/* found job with seq == -1 -- free deflate memory and return to join */
release(compress_have);
(void)deflateEnd(&strm);
}
/* collect the write jobs off of the list in sequence order and write out the
compressed data until the last chunk is written -- also write the header and
trailer and combine the individual check values of the input buffers */
local void write_thread(void *dummy)
{
long seq; /* next sequence number looking for */
struct job *job; /* job pulled and working on */
size_t len; /* input length */
int more; /* true if more chunks to write */
unsigned long head; /* header length */
unsigned long ulen; /* total uncompressed size (overflow ok) */
unsigned long clen; /* total compressed size (overflow ok) */
unsigned long check; /* check value of uncompressed data */
(void)dummy;
/* build and write header */
Trace(("-- write thread running"));
head = put_header();
/* process output of compress threads until end of input */
ulen = clen = 0;
check = CHECK(0L, Z_NULL, 0);
seq = 0;
do {
/* get next write job in order */
possess(write_first);
wait_for(write_first, TO_BE, seq);
job = write_head;
write_head = job->next;
twist(write_first, TO, write_head == NULL ? -1 : write_head->seq);
/* update lengths, save uncompressed length for COMB */
more = job->more;
len = job->in->len;
drop_space(job->in);
ulen += (unsigned long)len;
clen += (unsigned long)(job->out->len);
/* write the compressed data and drop the output buffer */
Trace(("-- writing #%ld", seq));
writen(g.outd, job->out->buf, job->out->len);
drop_space(job->out);
Trace(("-- wrote #%ld%s", seq, more ? "" : " (last)"));
/* wait for check calculation to complete, then combine, once
the compress thread is done with the input, release it */
possess(job->calc);
wait_for(job->calc, TO_BE, 1);
release(job->calc);
check = COMB(check, job->check, len);
/* free the job */
free_lock(job->calc);
FREE(job);
/* get the next buffer in sequence */
seq++;
} while (more);
/* write trailer */
put_trailer(ulen, clen, check, head);
/* verify no more jobs, prepare for next use */
possess(compress_have);
assert(compress_head == NULL && peek_lock(compress_have) == 0);
release(compress_have);
possess(write_first);
assert(write_head == NULL);
twist(write_first, TO, -1);
}
/* encode a hash hit to the block lengths list -- hit == 0 ends the list */
local void append_len(struct job *job, size_t len)
{
struct space *lens;
assert(len < 539000896UL);
if (job->lens == NULL)
job->lens = get_space(&lens_pool);
lens = job->lens;
if (lens->size < lens->len + 3)
grow_space(lens);
if (len < 64)
lens->buf[lens->len++] = len + 128;
else if (len < 32832U) {
len -= 64;
lens->buf[lens->len++] = len >> 8;
lens->buf[lens->len++] = len;
}
else if (len < 2129984UL) {
len -= 32832U;
lens->buf[lens->len++] = (len >> 16) + 192;
lens->buf[lens->len++] = len >> 8;
lens->buf[lens->len++] = len;
}
else {
len -= 2129984UL;
lens->buf[lens->len++] = (len >> 24) + 224;
lens->buf[lens->len++] = len >> 16;
lens->buf[lens->len++] = len >> 8;
lens->buf[lens->len++] = len;
}
}
/* compress ind to outd, using multiple threads for the compression and check
value calculations and one other thread for writing the output -- compress
threads will be launched and left running (waiting actually) to support
subsequent calls of parallel_compress() */
local void parallel_compress(void)
{
long seq; /* sequence number */
struct space *curr; /* input data to compress */
struct space *next; /* input data that follows curr */
struct space *hold; /* input data that follows next */
struct space *dict; /* dictionary for next compression */
struct job *job; /* job for compress, then write */
int more; /* true if more input to read */
unsigned hash; /* hash for rsyncable */
unsigned char *scan; /* next byte to compute hash on */
unsigned char *end; /* after end of data to compute hash on */
unsigned char *last; /* position after last hit */
size_t left; /* last hit in curr to end of curr */
size_t len; /* for various length computations */
/* if first time or after an option change, setup the job lists */
setup_jobs();
/* start write thread */
writeth = launch(write_thread, NULL);
/* read from input and start compress threads (write thread will pick up
the output of the compress threads) */
seq = 0;
next = get_space(&in_pool);
next->len = readn(g.ind, next->buf, next->size);
hold = NULL;
dict = NULL;
scan = next->buf;
hash = RSYNCHIT;
left = 0;
do {
/* create a new job */
job = MALLOC(sizeof(struct job));
if (job == NULL)
bail("not enough memory", "");
job->calc = new_lock(0);
/* update input spaces */
curr = next;
next = hold;
hold = NULL;
/* get more input if we don't already have some */
if (next == NULL) {
next = get_space(&in_pool);
next->len = readn(g.ind, next->buf, next->size);
}
/* if rsyncable, generate block lengths and prepare curr for job to
likely have less than size bytes (up to the last hash hit) */
job->lens = NULL;
if (g.rsync && curr->len) {
/* compute the hash function starting where we last left off to
cover either size bytes or to EOF, whichever is less, through
the data in curr (and in the next loop, through next) -- save
the block lengths resulting from the hash hits in the job->lens
list */
if (left == 0) {
/* scan is in curr */
last = curr->buf;
end = curr->buf + curr->len;
while (scan < end) {
hash = ((hash << 1) ^ *scan++) & RSYNCMASK;
if (hash == RSYNCHIT) {
len = scan - last;
append_len(job, len);
last = scan;
}
}
/* continue scan in next */
left = scan - last;
scan = next->buf;
}
/* scan in next for enough bytes to fill curr, or what is available
in next, whichever is less (if next isn't full, then we're at
the end of the file) -- the bytes in curr since the last hit,
stored in left, counts towards the size of the first block */
last = next->buf;
len = curr->size - curr->len;
if (len > next->len)
len = next->len;
end = next->buf + len;
while (scan < end) {
hash = ((hash << 1) ^ *scan++) & RSYNCMASK;
if (hash == RSYNCHIT) {
len = (scan - last) + left;
left = 0;
append_len(job, len);
last = scan;
}
}
append_len(job, 0);
/* create input in curr for job up to last hit or entire buffer if
no hits at all -- save remainder in next and possibly hold */
len = (job->lens->len == 1 ? scan : last) - next->buf;
if (len) {
/* got hits in next, or no hits in either -- copy to curr */
memcpy(curr->buf + curr->len, next->buf, len);
curr->len += len;
memmove(next->buf, next->buf + len, next->len - len);
next->len -= len;
scan -= len;
left = 0;
}
else if (job->lens->len != 1 && left && next->len) {
/* had hits in curr, but none in next, and last hit in curr
wasn't right at the end, so we have input there to save --
use curr up to the last hit, save the rest, moving next to
hold */
hold = next;
next = get_space(&in_pool);
memcpy(next->buf, curr->buf + (curr->len - left), left);
next->len = left;
curr->len -= left;
}
else {
/* else, last match happened to be right at the end of curr,
or we're at the end of the input compressing the rest */
left = 0;
}
}
/* compress curr->buf to curr->len -- compress thread will drop curr */
job->in = curr;
/* set job->more if there is more to compress after curr */
more = next->len != 0;
job->more = more;
/* provide dictionary for this job, prepare dictionary for next job */
job->out = dict;
if (more && g.setdict) {
if (curr->len >= DICT || job->out == NULL) {
dict = curr;
use_space(dict);
}
else {
dict = get_space(&dict_pool);
len = DICT - curr->len;
memcpy(dict->buf, job->out->buf + (job->out->len - len), len);
memcpy(dict->buf + len, curr->buf, curr->len);
dict->len = DICT;
}
}
/* preparation of job is complete */
job->seq = seq;
Trace(("-- read #%ld%s", seq, more ? "" : " (last)"));
if (++seq < 1)
bail("input too long: ", g.inf);
/* start another compress thread if needed */
if (cthreads < seq && cthreads < g.procs) {
(void)launch(compress_thread, NULL);
cthreads++;
}
/* put job at end of compress list, let all the compressors know */
possess(compress_have);
job->next = NULL;
*compress_tail = job;
compress_tail = &(job->next);
twist(compress_have, BY, +1);
} while (more);
drop_space(next);
/* wait for the write thread to complete (we leave the compress threads out
there and waiting in case there is another stream to compress) */
join(writeth);
writeth = NULL;
Trace(("-- write thread joined"));
}
#endif
/* repeated code in single_compress to compress available input and write it */
#define DEFLATE_WRITE(flush) \
do { \
do { \
strm->avail_out = out_size; \
strm->next_out = out; \
(void)deflate(strm, flush); \
writen(g.outd, out, out_size - strm->avail_out); \
clen += out_size - strm->avail_out; \
} while (strm->avail_out == 0); \
assert(strm->avail_in == 0); \
} while (0)
/* do a simple compression in a single thread from ind to outd -- if reset is
true, instead free the memory that was allocated and retained for input,
output, and deflate */
local void single_compress(int reset)
{
size_t got; /* amount of data in in[] */
size_t more; /* amount of data in next[] (0 if eof) */
size_t start; /* start of data in next[] */
size_t have; /* bytes in current block for -i */
size_t hist; /* offset of permitted history */
int fresh; /* if true, reset compression history */
unsigned hash; /* hash for rsyncable */
unsigned char *scan; /* pointer for hash computation */
size_t left; /* bytes left to compress after hash hit */
unsigned long head; /* header length */
unsigned long ulen; /* total uncompressed size (overflow ok) */
unsigned long clen; /* total compressed size (overflow ok) */
unsigned long check; /* check value of uncompressed data */
static unsigned out_size; /* size of output buffer */
static unsigned char *in, *next, *out; /* reused i/o buffers */
static z_stream *strm = NULL; /* reused deflate structure */
/* if requested, just release the allocations and return */
if (reset) {
if (strm != NULL) {
(void)deflateEnd(strm);
FREE(strm);
FREE(out);
FREE(next);
FREE(in);
strm = NULL;
}
return;
}
/* initialize the deflate structure if this is the first time */
if (strm == NULL) {
out_size = g.block > MAXP2 ? MAXP2 : (unsigned)g.block;
if ((in = MALLOC(g.block + DICT)) == NULL ||
(next = MALLOC(g.block + DICT)) == NULL ||
(out = MALLOC(out_size)) == NULL ||
(strm = MALLOC(sizeof(z_stream))) == NULL)
bail("not enough memory", "");
strm->zfree = ZFREE;
strm->zalloc = ZALLOC;
strm->opaque = OPAQUE;
if (deflateInit2(strm, 6, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) !=
Z_OK)
bail("not enough memory", "");
}
/* write header */
head = put_header();
/* set compression level in case it changed */
if (g.level <= 9) {
(void)deflateReset(strm);
(void)deflateParams(strm, g.level, Z_DEFAULT_STRATEGY);
}
/* do raw deflate and calculate check value */
got = 0;
more = readn(g.ind, next, g.block);
ulen = (unsigned long)more;
start = 0;
hist = 0;
clen = 0;
have = 0;
check = CHECK(0L, Z_NULL, 0);
hash = RSYNCHIT;
do {
/* get data to compress, see if there is any more input */
if (got == 0) {
scan = in; in = next; next = scan;
strm->next_in = in + start;
got = more;
if (g.level > 9) {
left = start + more - hist;
if (left > DICT)
left = DICT;
memcpy(next, in + ((start + more) - left), left);
start = left;
hist = 0;
}
else
start = 0;
more = readn(g.ind, next + start, g.block);
ulen += (unsigned long)more;
}
/* if rsyncable, compute hash until a hit or the end of the block */
left = 0;
if (g.rsync && got) {
scan = strm->next_in;
left = got;
do {
if (left == 0) {
/* went to the end -- if no more or no hit in size bytes,
then proceed to do a flush or finish with got bytes */
if (more == 0 || got == g.block)
break;
/* fill in[] with what's left there and as much as possible
from next[] -- set up to continue hash hit search */
if (g.level > 9) {
left = (strm->next_in - in) - hist;
if (left > DICT)
left = DICT;
}
memmove(in, strm->next_in - left, left + got);
hist = 0;
strm->next_in = in + left;
scan = in + left + got;
left = more > g.block - got ? g.block - got : more;
memcpy(scan, next + start, left);
got += left;
more -= left;
start += left;
/* if that emptied the next buffer, try to refill it */
if (more == 0) {
more = readn(g.ind, next, g.block);
ulen += (unsigned long)more;
start = 0;
}
}
left--;
hash = ((hash << 1) ^ *scan++) & RSYNCMASK;
} while (hash != RSYNCHIT);
got -= left;
}
/* clear history for --independent option */
fresh = 0;
if (!g.setdict) {
have += got;
if (have > g.block) {
fresh = 1;
have = got;
}
}
if (g.level <= 9) {
/* clear history if requested */
if (fresh)
(void)deflateReset(strm);
/* compress MAXP2-size chunks in case unsigned type is small */
while (got > MAXP2) {
strm->avail_in = MAXP2;
check = CHECK(check, strm->next_in, strm->avail_in);
DEFLATE_WRITE(Z_NO_FLUSH);
got -= MAXP2;
}
/* compress the remainder, emit a block, finish if end of input */
strm->avail_in = (unsigned)got;
got = left;
check = CHECK(check, strm->next_in, strm->avail_in);
if (more || got) {
#if ZLIB_VERNUM >= 0x1260
int bits;
DEFLATE_WRITE(Z_BLOCK);
(void)deflatePending(strm, Z_NULL, &bits);
if (bits & 1)
DEFLATE_WRITE(Z_SYNC_FLUSH);
else if (bits & 7) {
do {
bits = deflatePrime(strm, 10, 2);
assert(bits == Z_OK);
(void)deflatePending(strm, Z_NULL, &bits);
} while (bits & 7);
DEFLATE_WRITE(Z_NO_FLUSH);
}
#else
DEFLATE_WRITE(Z_SYNC_FLUSH);
#endif
}
else
DEFLATE_WRITE(Z_FINISH);
}
else {
/* compress got bytes using zopfli, bring to byte boundary */
unsigned char bits, *out;
size_t outsize, off;
/* discard history if requested */
off = strm->next_in - in;
if (fresh)
hist = off;
out = NULL;
outsize = 0;
bits = 0;
ZopfliDeflatePart(&g.zopts, 2, !(more || left),
in + hist, off - hist, (off - hist) + got,
&bits, &out, &outsize);
bits &= 7;
if ((more || left) && bits) {
if (bits & 1) {
writen(g.outd, out, outsize);
if (bits == 7)
writen(g.outd, (unsigned char *)"\0", 1);
writen(g.outd, (unsigned char *)"\0\0\xff\xff", 4);
}
else {
assert(outsize > 0);
writen(g.outd, out, outsize - 1);
do {
out[outsize - 1] += 2 << bits;
writen(g.outd, out + outsize - 1, 1);
out[outsize - 1] = 0;
bits += 2;
} while (bits < 8);
writen(g.outd, out + outsize - 1, 1);
}
}
else
writen(g.outd, out, outsize);
free(out);
while (got > MAXP2) {
check = CHECK(check, strm->next_in, MAXP2);
strm->next_in += MAXP2;
got -= MAXP2;
}
check = CHECK(check, strm->next_in, (unsigned)got);
strm->next_in += got;
got = left;
}
/* do until no more input */
} while (more || got);
/* write trailer */
put_trailer(ulen, clen, check, head);
}
/* --- decompression --- */
#ifndef NOTHREAD
/* parallel read thread */
local void load_read(void *dummy)
{
size_t len;
(void)dummy;
Trace(("-- launched decompress read thread"));
do {
possess(g.load_state);
wait_for(g.load_state, TO_BE, 1);
g.in_len = len = readn(g.ind, g.in_which ? g.in_buf : g.in_buf2, BUF);
Trace(("-- decompress read thread read %lu bytes", len));
twist(g.load_state, TO, 0);
} while (len == BUF);
Trace(("-- exited decompress read thread"));
}
#endif
/* load() is called when the input has been consumed in order to provide more
input data: load the input buffer with BUF or fewer bytes (fewer if at end
of file) from the file g.ind, set g.in_next to point to the g.in_left bytes
read, update g.in_tot, and return g.in_left -- g.in_eof is set to true when
g.in_left has gone to zero and there is no more data left to read */
local size_t load(void)
{
/* if already detected end of file, do nothing */
if (g.in_short) {
g.in_eof = 1;
g.in_left = 0;
return 0;
}
#ifndef NOTHREAD
/* if first time in or procs == 1, read a buffer to have something to
return, otherwise wait for the previous read job to complete */
if (g.procs > 1) {
/* if first time, fire up the read thread, ask for a read */
if (g.in_which == -1) {
g.in_which = 1;
g.load_state = new_lock(1);
g.load_thread = launch(load_read, NULL);
}
/* wait for the previously requested read to complete */
possess(g.load_state);
wait_for(g.load_state, TO_BE, 0);
release(g.load_state);
/* set up input buffer with the data just read */
g.in_next = g.in_which ? g.in_buf : g.in_buf2;
g.in_left = g.in_len;
/* if not at end of file, alert read thread to load next buffer,
alternate between g.in_buf and g.in_buf2 */
if (g.in_len == BUF) {
g.in_which = 1 - g.in_which;
possess(g.load_state);
twist(g.load_state, TO, 1);
}
/* at end of file -- join read thread (already exited), clean up */
else {
join(g.load_thread);
free_lock(g.load_state);
g.in_which = -1;
}
}
else
#endif
{
/* don't use threads -- simply read a buffer into g.in_buf */
g.in_left = readn(g.ind, g.in_next = g.in_buf, BUF);
}
/* note end of file */
if (g.in_left < BUF) {
g.in_short = 1;
/* if we got bupkis, now is the time to mark eof */
if (g.in_left == 0)
g.in_eof = 1;
}
/* update the total and return the available bytes */
g.in_tot += g.in_left;
return g.in_left;
}
/* initialize for reading new input */
local void in_init(void)
{
g.in_left = 0;
g.in_eof = 0;
g.in_short = 0;
g.in_tot = 0;
#ifndef NOTHREAD
g.in_which = -1;
#endif
}
/* buffered reading macros for decompression and listing */
#define GET() (g.in_left == 0 && (g.in_eof || load() == 0) ? 0 : \
(g.in_left--, *g.in_next++))
#define GET2() (tmp2 = GET(), tmp2 + ((unsigned)(GET()) << 8))
#define GET4() (tmp4 = GET2(), tmp4 + ((unsigned long)(GET2()) << 16))
#define SKIP(dist) \
do { \
size_t togo = (dist); \
while (togo > g.in_left) { \
togo -= g.in_left; \
if (load() == 0) \
return -1; \
} \
g.in_left -= togo; \
g.in_next += togo; \
} while (0)
/* pull LSB order or MSB order integers from an unsigned char buffer */
#define PULL2L(p) ((p)[0] + ((unsigned)((p)[1]) << 8))
#define PULL4L(p) (PULL2L(p) + ((unsigned long)(PULL2L((p) + 2)) << 16))
#define PULL2M(p) (((unsigned)((p)[0]) << 8) + (p)[1])
#define PULL4M(p) (((unsigned long)(PULL2M(p)) << 16) + PULL2M((p) + 2))
/* convert MS-DOS date and time to a Unix time, assuming current timezone
(you got a better idea?) */
local time_t dos2time(unsigned long dos)
{
struct tm tm;
if (dos == 0)
return time(NULL);
tm.tm_year = ((int)(dos >> 25) & 0x7f) + 80;
tm.tm_mon = ((int)(dos >> 21) & 0xf) - 1;
tm.tm_mday = (int)(dos >> 16) & 0x1f;
tm.tm_hour = (int)(dos >> 11) & 0x1f;
tm.tm_min = (int)(dos >> 5) & 0x3f;
tm.tm_sec = (int)(dos << 1) & 0x3e;
tm.tm_isdst = -1; /* figure out if DST or not */
return mktime(&tm);
}
/* convert an unsigned 32-bit integer to signed, even if long > 32 bits */
local long tolong(unsigned long val)
{
return (long)(val & 0x7fffffffUL) - (long)(val & 0x80000000UL);
}
#define LOW32 0xffffffffUL
/* process zip extra field to extract zip64 lengths and Unix mod time */
local int read_extra(unsigned len, int save)
{
unsigned id, size, tmp2;
unsigned long tmp4;
/* process extra blocks */
while (len >= 4) {
id = GET2();
size = GET2();
if (g.in_eof)
return -1;
len -= 4;
if (size > len)
break;
len -= size;
if (id == 0x0001) {
/* Zip64 Extended Information Extra Field */
if (g.zip_ulen == LOW32 && size >= 8) {
g.zip_ulen = GET4();
SKIP(4);
size -= 8;
}
if (g.zip_clen == LOW32 && size >= 8) {
g.zip_clen = GET4();
SKIP(4);
size -= 8;
}
}
if (save) {
if ((id == 0x000d || id == 0x5855) && size >= 8) {
/* PKWare Unix or Info-ZIP Type 1 Unix block */
SKIP(4);
g.stamp = tolong(GET4());
size -= 8;
}
if (id == 0x5455 && size >= 5) {
/* Extended Timestamp block */
size--;
if (GET() & 1) {
g.stamp = tolong(GET4());
size -= 4;
}
}
}
SKIP(size);
}
SKIP(len);
return 0;
}
/* read a gzip, zip, zlib, or lzw header from ind and return the method in the
range 0..256 (256 implies a zip method greater than 255), or on error return
negative: -1 is immediate EOF, -2 is not a recognized compressed format, -3
is premature EOF within the header, -4 is unexpected header flag values, -5
is the zip central directory; a method of 257 is lzw -- if the return value
is not negative, then get_header() sets g.form to indicate gzip (0), zlib
(1), or zip (2, or 3 if the entry is followed by a data descriptor) */
local int get_header(int save)
{
unsigned magic; /* magic header */
int method; /* compression method */
int flags; /* header flags */
unsigned fname, extra; /* name and extra field lengths */
unsigned tmp2; /* for macro */
unsigned long tmp4; /* for macro */
/* clear return information */
if (save) {
g.stamp = 0;
RELEASE(g.hname);
}
/* see if it's a gzip, zlib, or lzw file */
g.form = -1;
g.magic1 = GET();
if (g.in_eof)
return -1;
magic = g.magic1 << 8;
magic += GET();
if (g.in_eof)
return -2;
if (magic % 31 == 0) { /* it's zlib */
g.form = 1;
return (int)((magic >> 8) & 0xf);
}
if (magic == 0x1f9d) /* it's lzw */
return 257;
if (magic == 0x504b) { /* it's zip */
magic = GET2(); /* the rest of the signature */
if (g.in_eof)
return -3;
if (magic == 0x0201 || magic == 0x0806)
return -5; /* central header or archive extra */
if (magic != 0x0403)
return -4; /* not a local header */
SKIP(2);
flags = GET2();
if (g.in_eof)
return -3;
if (flags & 0xfff0)
return -4;
method = GET(); /* return low byte of method or 256 */
if (GET() != 0 || flags & 1)
method = 256; /* unknown or encrypted */
if (g.in_eof)
return -3;
if (save)
g.stamp = dos2time(GET4());
else
SKIP(4);
g.zip_crc = GET4();
g.zip_clen = GET4();
g.zip_ulen = GET4();
fname = GET2();
extra = GET2();
if (save) {
char *next = g.hname = MALLOC(fname + 1);
if (g.hname == NULL)
bail("not enough memory", "");
while (fname > g.in_left) {
memcpy(next, g.in_next, g.in_left);
fname -= g.in_left;
next += g.in_left;
if (load() == 0)
return -3;
}
memcpy(next, g.in_next, fname);
g.in_left -= fname;
g.in_next += fname;
next += fname;
*next = 0;
}
else
SKIP(fname);
read_extra(extra, save);
g.form = 2 + ((flags & 8) >> 3);
return g.in_eof ? -3 : method;
}
if (magic != 0x1f8b) { /* not gzip */
g.in_left++; /* unget second magic byte */
g.in_next--;
return -2;
}
/* it's gzip -- get method and flags */
method = GET();
flags = GET();
if (g.in_eof)
return -1;
if (flags & 0xe0)
return -4;
/* get time stamp */
if (save)
g.stamp = tolong(GET4());
else
SKIP(4);
/* skip extra field and OS */
SKIP(2);
/* skip extra field, if present */
if (flags & 4) {
extra = GET2();
if (g.in_eof)
return -3;
SKIP(extra);
}
/* read file name, if present, into allocated memory */
if ((flags & 8) && save) {
unsigned char *end;
size_t copy, have, size = 128;
g.hname = MALLOC(size);
if (g.hname == NULL)
bail("not enough memory", "");
have = 0;
do {
if (g.in_left == 0 && load() == 0)
return -3;
end = memchr(g.in_next, 0, g.in_left);
copy = end == NULL ? g.in_left : (size_t)(end - g.in_next) + 1;
if (have + copy > size) {
while (have + copy > (size <<= 1))
;
g.hname = REALLOC(g.hname, size);
if (g.hname == NULL)
bail("not enough memory", "");
}
memcpy(g.hname + have, g.in_next, copy);
have += copy;
g.in_left -= copy;
g.in_next += copy;
} while (end == NULL);
}
else if (flags & 8)
while (GET() != 0)
if (g.in_eof)
return -3;
/* skip comment */
if (flags & 16)
while (GET() != 0)
if (g.in_eof)
return -3;
/* skip header crc */
if (flags & 2)
SKIP(2);
/* return gzip compression method */
g.form = 0;
return method;
}
/* --- list contents of compressed input (gzip, zlib, or lzw) */
/* find standard compressed file suffix, return length of suffix */
local size_t compressed_suffix(char *nm)
{
size_t len;
len = strlen(nm);
if (len > 4) {
nm += len - 4;
len = 4;
if (strcmp(nm, ".zip") == 0 || strcmp(nm, ".ZIP") == 0 ||
strcmp(nm, ".tgz") == 0)
return 4;
}
if (len > 3) {
nm += len - 3;
len = 3;
if (strcmp(nm, ".gz") == 0 || strcmp(nm, "-gz") == 0 ||
strcmp(nm, ".zz") == 0 || strcmp(nm, "-zz") == 0)
return 3;
}
if (len > 2) {
nm += len - 2;
if (strcmp(nm, ".z") == 0 || strcmp(nm, "-z") == 0 ||
strcmp(nm, "_z") == 0 || strcmp(nm, ".Z") == 0)
return 2;
}
return 0;
}
/* listing file name lengths for -l and -lv */
#define NAMEMAX1 48 /* name display limit at verbosity 1 */
#define NAMEMAX2 16 /* name display limit at verbosity 2 */
/* print gzip or lzw file information */
local void show_info(int method, unsigned long check, off_t len, int cont)
{
size_t max; /* maximum name length for current verbosity */
size_t n; /* name length without suffix */
time_t now; /* for getting current year */
char mod[26]; /* modification time in text */
char tag[NAMEMAX1+1]; /* header or file name, possibly truncated */
/* create abbreviated name from header file name or actual file name */
max = g.verbosity > 1 ? NAMEMAX2 : NAMEMAX1;
memset(tag, 0, max + 1);
if (cont)
strncpy(tag, "<...>", max + 1);
else if (g.hname == NULL) {
n = strlen(g.inf) - compressed_suffix(g.inf);
strncpy(tag, g.inf, n > max + 1 ? max + 1 : n);
if (strcmp(g.inf + n, ".tgz") == 0 && n < max + 1)
strncpy(tag + n, ".tar", max + 1 - n);
}
else
strncpy(tag, g.hname, max + 1);
if (tag[max])
strcpy(tag + max - 3, "...");
/* convert time stamp to text */
if (g.stamp) {
strcpy(mod, ctime(&g.stamp));
now = time(NULL);
if (strcmp(mod + 20, ctime(&now) + 20) != 0)
strcpy(mod + 11, mod + 19);
}
else
strcpy(mod + 4, "------ -----");
mod[16] = 0;
/* if first time, print header */
if (g.first) {
if (g.verbosity > 1)
fputs("method check timestamp ", stdout);
if (g.verbosity > 0)
puts("compressed original reduced name");
g.first = 0;
}
/* print information */
if (g.verbosity > 1) {
if (g.form == 3 && !g.decode)
printf("zip%3d -------- %s ", method, mod + 4);
else if (g.form > 1)
printf("zip%3d %08lx %s ", method, check, mod + 4);
else if (g.form == 1)
printf("zlib%2d %08lx %s ", method, check, mod + 4);
else if (method == 257)
printf("lzw -------- %s ", mod + 4);
else
printf("gzip%2d %08lx %s ", method, check, mod + 4);
}
if (g.verbosity > 0) {
if ((g.form == 3 && !g.decode) ||
(method == 8 && g.in_tot > (len + (len >> 10) + 12)) ||
(method == 257 && g.in_tot > len + (len >> 1) + 3))
#if __STDC_VERSION__-0 >= 199901L || __GNUC__-0 >= 3
printf("%10jd %10jd? unk %s\n",
(intmax_t)g.in_tot, (intmax_t)len, tag);
else
printf("%10jd %10jd %6.1f%% %s\n",
(intmax_t)g.in_tot, (intmax_t)len,
len == 0 ? 0 : 100 * (len - g.in_tot)/(double)len,
tag);
#else
printf(sizeof(off_t) == sizeof(long) ?
"%10ld %10ld? unk %s\n" : "%10lld %10lld? unk %s\n",
g.in_tot, len, tag);
else
printf(sizeof(off_t) == sizeof(long) ?
"%10ld %10ld %6.1f%% %s\n" : "%10lld %10lld %6.1f%% %s\n",
g.in_tot, len,
len == 0 ? 0 : 100 * (len - g.in_tot)/(double)len,
tag);
#endif
}
}
/* list content information about the gzip file at ind (only works if the gzip
file contains a single gzip stream with no junk at the end, and only works
well if the uncompressed length is less than 4 GB) */
local void list_info(void)
{
int method; /* get_header() return value */
size_t n; /* available trailer bytes */
off_t at; /* used to calculate compressed length */
unsigned char tail[8]; /* trailer containing check and length */
unsigned long check, len; /* check value and length from trailer */
/* initialize input buffer */
in_init();
/* read header information and position input after header */
method = get_header(1);
if (method < 0) {
RELEASE(g.hname);
if (method != -1 && g.verbosity > 1)
complain("%s not a compressed file -- skipping", g.inf);
return;
}
/* list zip file */
if (g.form > 1) {
g.in_tot = g.zip_clen;
show_info(method, g.zip_crc, g.zip_ulen, 0);
return;
}
/* list zlib file */
if (g.form == 1) {
at = lseek(g.ind, 0, SEEK_END);
if (at == -1) {
check = 0;
do {
len = g.in_left < 4 ? g.in_left : 4;
g.in_next += g.in_left - len;
while (len--)
check = (check << 8) + *g.in_next++;
} while (load() != 0);
check &= LOW32;
}
else {
g.in_tot = at;
lseek(g.ind, -4, SEEK_END);
readn(g.ind, tail, 4);
check = PULL4M(tail);
}
g.in_tot -= 6;
show_info(method, check, 0, 0);
return;
}
/* list lzw file */
if (method == 257) {
at = lseek(g.ind, 0, SEEK_END);
if (at == -1)
while (load() != 0)
;
else
g.in_tot = at;
g.in_tot -= 3;
show_info(method, 0, 0, 0);
return;
}
/* skip to end to get trailer (8 bytes), compute compressed length */
if (g.in_short) { /* whole thing already read */
if (g.in_left < 8) {
complain("%s not a valid gzip file -- skipping", g.inf);
return;
}
g.in_tot = g.in_left - 8; /* compressed size */
memcpy(tail, g.in_next + (g.in_left - 8), 8);
}
else if ((at = lseek(g.ind, -8, SEEK_END)) != -1) {
g.in_tot = at - g.in_tot + g.in_left; /* compressed size */
readn(g.ind, tail, 8); /* get trailer */
}
else { /* can't seek */
at = g.in_tot - g.in_left; /* save header size */
do {
n = g.in_left < 8 ? g.in_left : 8;
memcpy(tail, g.in_next + (g.in_left - n), n);
load();
} while (g.in_left == BUF); /* read until end */
if (g.in_left < 8) {
if (n + g.in_left < 8) {
complain("%s not a valid gzip file -- skipping", g.inf);
return;
}
if (g.in_left) {
if (n + g.in_left > 8)
memcpy(tail, tail + n - (8 - g.in_left), 8 - g.in_left);
memcpy(tail + 8 - g.in_left, g.in_next, g.in_left);
}
}
else
memcpy(tail, g.in_next + (g.in_left - 8), 8);
g.in_tot -= at + 8;
}
if (g.in_tot < 2) {
complain("%s not a valid gzip file -- skipping", g.inf);
return;
}
/* convert trailer to check and uncompressed length (modulo 2^32) */
check = PULL4L(tail);
len = PULL4L(tail + 4);
/* list information about contents */
show_info(method, check, len, 0);
RELEASE(g.hname);
}
/* --- copy input to output (when acting like cat) --- */
local void cat(void)
{
/* write first magic byte (if we're here, there's at least one byte) */
writen(g.outd, &g.magic1, 1);
g.out_tot = 1;
/* copy the remainder of the input to the output (if there were any more
bytes of input, then g.in_left is non-zero and g.in_next is pointing to
the second magic byte) */
while (g.in_left) {
writen(g.outd, g.in_next, g.in_left);
g.out_tot += g.in_left;
g.in_left = 0;
load();
}
}
/* --- decompress deflate input --- */
/* call-back input function for inflateBack() */
local unsigned inb(void *desc, unsigned char **buf)
{
(void)desc;
load();
*buf = g.in_next;
return g.in_left;
}
/* output buffers and window for infchk() and unlzw() */
#define OUTSIZE 32768U /* must be at least 32K for inflateBack() window */
local unsigned char out_buf[OUTSIZE];
#ifndef NOTHREAD
/* output data for parallel write and check */
local unsigned char out_copy[OUTSIZE];
local size_t out_len;
/* outb threads states */
local lock *outb_write_more = NULL;
local lock *outb_check_more;
/* output write thread */
local void outb_write(void *dummy)
{
size_t len;
(void)dummy;
Trace(("-- launched decompress write thread"));
do {
possess(outb_write_more);
wait_for(outb_write_more, TO_BE, 1);
len = out_len;
if (len && g.decode == 1)
writen(g.outd, out_copy, len);
Trace(("-- decompress wrote %lu bytes", len));
twist(outb_write_more, TO, 0);
} while (len);
Trace(("-- exited decompress write thread"));
}
/* output check thread */
local void outb_check(void *dummy)
{
size_t len;
(void)dummy;
Trace(("-- launched decompress check thread"));
do {
possess(outb_check_more);
wait_for(outb_check_more, TO_BE, 1);
len = out_len;
g.out_check = CHECK(g.out_check, out_copy, len);
Trace(("-- decompress checked %lu bytes", len));
twist(outb_check_more, TO, 0);
} while (len);
Trace(("-- exited decompress check thread"));
}
#endif
/* call-back output function for inflateBack() -- wait for the last write and
check calculation to complete, copy the write buffer, and then alert the
write and check threads and return for more decompression while that's
going on (or just write and check if no threads or if proc == 1) */
local int outb(void *desc, unsigned char *buf, unsigned len)
{
#ifndef NOTHREAD
static thread *wr, *ch;
if (g.procs > 1) {
/* if first time, initialize state and launch threads */
if (outb_write_more == NULL) {
outb_write_more = new_lock(0);
outb_check_more = new_lock(0);
wr = launch(outb_write, NULL);
ch = launch(outb_check, NULL);
}
/* wait for previous write and check threads to complete */
possess(outb_check_more);
wait_for(outb_check_more, TO_BE, 0);
possess(outb_write_more);
wait_for(outb_write_more, TO_BE, 0);
/* copy the output and alert the worker bees */
out_len = len;
g.out_tot += len;
memcpy(out_copy, buf, len);
twist(outb_write_more, TO, 1);
twist(outb_check_more, TO, 1);
/* if requested with len == 0, clean up -- terminate and join write and
check threads, free lock */
if (len == 0) {
join(ch);
join(wr);
free_lock(outb_check_more);
free_lock(outb_write_more);
outb_write_more = NULL;
}
/* return for more decompression while last buffer is being written
and having its check value calculated -- we wait for those to finish
the next time this function is called */
return 0;
}
#endif
(void)desc;
/* if just one process or no threads, then do it without threads */
if (len) {
if (g.decode == 1)
writen(g.outd, buf, len);
g.out_check = CHECK(g.out_check, buf, len);
g.out_tot += len;
}
return 0;
}
/* inflate for decompression or testing -- decompress from ind to outd unless
decode != 1, in which case just test ind, and then also list if list != 0;
look for and decode multiple, concatenated gzip and/or zlib streams;
read and check the gzip, zlib, or zip trailer */
local void infchk(void)
{
int ret, cont, was;
unsigned long check, len;
z_stream strm;
unsigned tmp2;
unsigned long tmp4;
off_t clen;
cont = 0;
do {
/* header already read -- set up for decompression */
g.in_tot = g.in_left; /* track compressed data length */
g.out_tot = 0;
g.out_check = CHECK(0L, Z_NULL, 0);
strm.zalloc = ZALLOC;
strm.zfree = ZFREE;
strm.opaque = OPAQUE;
ret = inflateBackInit(&strm, 15, out_buf);
if (ret != Z_OK)
bail("not enough memory", "");
/* decompress, compute lengths and check value */
strm.avail_in = g.in_left;
strm.next_in = g.in_next;
ret = inflateBack(&strm, inb, NULL, outb, NULL);
if (ret != Z_STREAM_END)
bail("corrupted input -- invalid deflate data: ", g.inf);
g.in_left = strm.avail_in;
g.in_next = strm.next_in;
inflateBackEnd(&strm);
outb(NULL, NULL, 0); /* finish off final write and check */
/* compute compressed data length */
clen = g.in_tot - g.in_left;
/* read and check trailer */
if (g.form > 1) { /* zip local trailer (if any) */
if (g.form == 3) { /* data descriptor follows */
/* read original version of data descriptor */
g.zip_crc = GET4();
g.zip_clen = GET4();
g.zip_ulen = GET4();
if (g.in_eof)
bail("corrupted zip entry -- missing trailer: ", g.inf);
/* if crc doesn't match, try info-zip variant with sig */
if (g.zip_crc != g.out_check) {
if (g.zip_crc != 0x08074b50UL || g.zip_clen != g.out_check)
bail("corrupted zip entry -- crc32 mismatch: ", g.inf);
g.zip_crc = g.zip_clen;
g.zip_clen = g.zip_ulen;
g.zip_ulen = GET4();
}
/* handle incredibly rare cases where crc equals signature */
else if (g.zip_crc == 0x08074b50UL &&
g.zip_clen == g.zip_crc &&
((clen & LOW32) != g.zip_crc ||
g.zip_ulen == g.zip_crc)) {
g.zip_crc = g.zip_clen;
g.zip_clen = g.zip_ulen;
g.zip_ulen = GET4();
}
/* if second length doesn't match, try 64-bit lengths */
if (g.zip_ulen != (g.out_tot & LOW32)) {
g.zip_ulen = GET4();
(void)GET4();
}
if (g.in_eof)
bail("corrupted zip entry -- missing trailer: ", g.inf);
}
if (g.zip_clen != (clen & LOW32) ||
g.zip_ulen != (g.out_tot & LOW32))
bail("corrupted zip entry -- length mismatch: ", g.inf);
check = g.zip_crc;
}
else if (g.form == 1) { /* zlib (big-endian) trailer */
check = (unsigned long)(GET()) << 24;
check += (unsigned long)(GET()) << 16;
check += (unsigned)(GET()) << 8;
check += GET();
if (g.in_eof)
bail("corrupted zlib stream -- missing trailer: ", g.inf);
if (check != g.out_check)
bail("corrupted zlib stream -- adler32 mismatch: ", g.inf);
}
else { /* gzip trailer */
check = GET4();
len = GET4();
if (g.in_eof)
bail("corrupted gzip stream -- missing trailer: ", g.inf);
if (check != g.out_check)
bail("corrupted gzip stream -- crc32 mismatch: ", g.inf);
if (len != (g.out_tot & LOW32))
bail("corrupted gzip stream -- length mismatch: ", g.inf);
}
/* show file information if requested */
if (g.list) {
g.in_tot = clen;
show_info(8, check, g.out_tot, cont);
cont = 1;
}
/* if a gzip entry follows a gzip entry, decompress it (don't replace
saved header information from first entry) */
was = g.form;
} while (was == 0 && (ret = get_header(0)) == 8 && g.form == 0);
/* gzip -cdf copies junk after gzip stream directly to output */
if (was == 0 && ret == -2 && g.force && g.pipeout && g.decode != 2 &&
!g.list)
cat();
else if (was > 1 && get_header(0) != -5)
complain("entries after the first in %s were ignored", g.inf);
else if ((was == 0 && ret != -1) || (was == 1 && (GET(), !g.in_eof)))
complain("%s OK, has trailing junk which was ignored", g.inf);
}
/* --- decompress Unix compress (LZW) input --- */
/* Type for accumulating bits. 23 bits will be used to accumulate up to 16-bit
symbols. */
typedef uint_fast32_t bits_t;
#define NOMORE() (g.in_left == 0 && (g.in_eof || load() == 0))
#define NEXT() (g.in_left--, *g.in_next++)
/* Decompress a compress (LZW) file from ind to outd. The compress magic
header (two bytes) has already been read and verified. */
local void unlzw(void)
{
unsigned bits; /* current bits per code (9..16) */
unsigned mask; /* mask for current bits codes = (1<<bits)-1 */
bits_t buf; /* bit buffer (need 23 bits) */
unsigned left; /* bits left in buf (0..7 after code pulled) */
off_t mark; /* offset where last change in bits began */
unsigned code; /* code, table traversal index */
unsigned max; /* maximum bits per code for this stream */
unsigned flags; /* compress flags, then block compress flag */
unsigned end; /* last valid entry in prefix/suffix tables */
unsigned prev; /* previous code */
unsigned final; /* last character written for previous code */
unsigned stack; /* next position for reversed string */
unsigned outcnt; /* bytes in output buffer */
/* memory for unlzw() -- the first 256 entries of prefix[] and suffix[] are
never used, so could have offset the index but it's faster to waste a
little memory */
uint_least16_t prefix[65536]; /* index to LZW prefix string */
unsigned char suffix[65536]; /* one-character LZW suffix */
unsigned char match[65280 + 2]; /* buffer for reversed match */
/* process remainder of compress header -- a flags byte */
g.out_tot = 0;
if (NOMORE())
bail("lzw premature end: ", g.inf);
flags = NEXT();
if (flags & 0x60)
bail("unknown lzw flags set: ", g.inf);
max = flags & 0x1f;
if (max < 9 || max > 16)
bail("lzw bits out of range: ", g.inf);
if (max == 9) /* 9 doesn't really mean 9 */
max = 10;
flags &= 0x80; /* true if block compress */
/* mark the start of the compressed data for computing the first flush */
mark = g.in_tot - g.in_left;
/* clear table, start at nine bits per symbol */
bits = 9;
mask = 0x1ff;
end = flags ? 256 : 255;
/* set up: get first 9-bit code, which is the first decompressed byte, but
don't create a table entry until the next code */
if (NOMORE()) /* no compressed data is ok */
return;
buf = NEXT();
if (NOMORE())
bail("lzw premature end: ", g.inf); /* need at least nine bits */
buf += NEXT() << 8;
final = prev = buf & mask; /* code */
buf >>= bits;
left = 16 - bits;
if (prev > 255)
bail("invalid lzw code: ", g.inf);
out_buf[0] = final; /* write first decompressed byte */
outcnt = 1;
/* decode codes */
stack = 0;
for (;;) {
/* if the table will be full after this, increment the code size */
if (end >= mask && bits < max) {
/* flush unused input bits and bytes to next 8*bits bit boundary
(this is a vestigial aspect of the compressed data format
derived from an implementation that made use of a special VAX
machine instruction!) */
{
unsigned rem = ((g.in_tot - g.in_left) - mark) % bits;
if (rem)
rem = bits - rem;
while (rem > g.in_left) {
rem -= g.in_left;
if (load() == 0)
break;
}
g.in_left -= rem;
g.in_next += rem;
}
buf = 0;
left = 0;
/* mark this new location for computing the next flush */
mark = g.in_tot - g.in_left;
/* go to the next number of bits per symbol */
bits++;
mask <<= 1;
mask++;
}
/* get a code of bits bits */
if (NOMORE())
break; /* end of compressed data */
buf += (bits_t)(NEXT()) << left;
left += 8;
if (left < bits) {
if (NOMORE())
bail("lzw premature end: ", g.inf);
buf += (bits_t)(NEXT()) << left;
left += 8;
}
code = buf & mask;
buf >>= bits;
left -= bits;
/* process clear code (256) */
if (code == 256 && flags) {
/* flush unused input bits and bytes to next 8*bits bit boundary */
{
unsigned rem = ((g.in_tot - g.in_left) - mark) % bits;
if (rem)
rem = bits - rem;
while (rem > g.in_left) {
rem -= g.in_left;
if (load() == 0)
break;
}
g.in_left -= rem;
g.in_next += rem;
}
buf = 0;
left = 0;
/* mark this new location for computing the next flush */
mark = g.in_tot - g.in_left;
/* go back to nine bits per symbol */
bits = 9; /* initialize bits and mask */
mask = 0x1ff;
end = 255; /* empty table */
continue; /* get next code */
}
/* special code to reuse last match */
{
unsigned temp = code; /* save the current code */
if (code > end) {
/* Be picky on the allowed code here, and make sure that the
code we drop through (prev) will be a valid index so that
random input does not cause an exception. */
if (code != end + 1 || prev > end)
bail("invalid lzw code: ", g.inf);
match[stack++] = final;
code = prev;
}
/* walk through linked list to generate output in reverse order */
while (code >= 256) {
match[stack++] = suffix[code];
code = prefix[code];
}
match[stack++] = code;
final = code;
/* link new table entry */
if (end < mask) {
end++;
prefix[end] = prev;
suffix[end] = final;
}
/* set previous code for next iteration */
prev = temp;
}
/* write output in forward order */
while (stack > OUTSIZE - outcnt) {
while (outcnt < OUTSIZE)
out_buf[outcnt++] = match[--stack];
g.out_tot += outcnt;
if (g.decode == 1)
writen(g.outd, out_buf, outcnt);
outcnt = 0;
}
do {
out_buf[outcnt++] = match[--stack];
} while (stack);
}
/* write any remaining buffered output */
g.out_tot += outcnt;
if (outcnt && g.decode == 1)
writen(g.outd, out_buf, outcnt);
}
/* --- file processing --- */
/* extract file name from path */
local char *justname(char *path)
{
char *p;
p = strrchr(path, '/');
return p == NULL ? path : p + 1;
}
/* Copy file attributes, from -> to, as best we can. This is best effort, so
no errors are reported. The mode bits, including suid, sgid, and the sticky
bit are copied (if allowed), the owner's user id and group id are copied
(again if allowed), and the access and modify times are copied. */
local void copymeta(char *from, char *to)
{
struct stat st;
struct timeval times[2];
/* get all of from's Unix meta data, return if not a regular file */
if (stat(from, &st) != 0 || (st.st_mode & S_IFMT) != S_IFREG)
return;
/* set to's mode bits, ignore errors */
(void)chmod(to, st.st_mode & 07777);
/* copy owner's user and group, ignore errors */
(void)chown(to, st.st_uid, st.st_gid);
/* copy access and modify times, ignore errors */
times[0].tv_sec = st.st_atime;
times[0].tv_usec = 0;
times[1].tv_sec = st.st_mtime;
times[1].tv_usec = 0;
(void)utimes(to, times);
}
/* set the access and modify times of fd to t */
local void touch(char *path, time_t t)
{
struct timeval times[2];
times[0].tv_sec = t;
times[0].tv_usec = 0;
times[1].tv_sec = t;
times[1].tv_usec = 0;
(void)utimes(path, times);
}
/* process provided input file, or stdin if path is NULL -- process() can
call itself for recursive directory processing */
local void process(char *path)
{
int method = -1; /* get_header() return value */
size_t len; /* length of base name (minus suffix) */
struct stat st; /* to get file type and mod time */
/* all compressed suffixes for decoding search, in length order */
static char *sufs[] = {".z", "-z", "_z", ".Z", ".gz", "-gz", ".zz", "-zz",
".zip", ".ZIP", ".tgz", NULL};
/* open input file with name in, descriptor ind -- set name and mtime */
if (path == NULL) {
strcpy(g.inf, "<stdin>");
g.ind = 0;
g.name = NULL;
g.mtime = g.headis & 2 ?
(fstat(g.ind, &st) ? time(NULL) : st.st_mtime) : 0;
len = 0;
}
else {
/* set input file name (already set if recursed here) */
if (path != g.inf) {
strncpy(g.inf, path, sizeof(g.inf));
if (g.inf[sizeof(g.inf) - 1])
bail("name too long: ", path);
}
len = strlen(g.inf);
/* try to stat input file -- if not there and decoding, look for that
name with compressed suffixes */
if (lstat(g.inf, &st)) {
if (errno == ENOENT && (g.list || g.decode)) {
char **try = sufs;
do {
if (*try == NULL || len + strlen(*try) >= sizeof(g.inf))
break;
strcpy(g.inf + len, *try++);
errno = 0;
} while (lstat(g.inf, &st) && errno == ENOENT);
}
#ifdef EOVERFLOW
if (errno == EOVERFLOW || errno == EFBIG)
bail(g.inf,
" too large -- not compiled with large file support");
#endif
if (errno) {
g.inf[len] = 0;
complain("%s does not exist -- skipping", g.inf);
return;
}
len = strlen(g.inf);
}
/* only process regular files, but allow symbolic links if -f,
recurse into directory if -r */
if ((st.st_mode & S_IFMT) != S_IFREG &&
(st.st_mode & S_IFMT) != S_IFLNK &&
(st.st_mode & S_IFMT) != S_IFDIR) {
complain("%s is a special file or device -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFLNK && !g.force && !g.pipeout) {
complain("%s is a symbolic link -- skipping", g.inf);
return;
}
if ((st.st_mode & S_IFMT) == S_IFDIR && !g.recurse) {
complain("%s is a directory -- skipping", g.inf);
return;
}
/* recurse into directory (assumes Unix) */
if ((st.st_mode & S_IFMT) == S_IFDIR) {
char *roll, *item, *cut, *base, *bigger;
size_t len, hold;
DIR *here;
struct dirent *next;
/* accumulate list of entries (need to do this, since readdir()
behavior not defined if directory modified between calls) */
here = opendir(g.inf);
if (here == NULL)
return;
hold = 512;
roll = MALLOC(hold);
if (roll == NULL)
bail("not enough memory", "");
*roll = 0;
item = roll;
while ((next = readdir(here)) != NULL) {
if (next->d_name[0] == 0 ||
(next->d_name[0] == '.' && (next->d_name[1] == 0 ||
(next->d_name[1] == '.' && next->d_name[2] == 0))))
continue;
len = strlen(next->d_name) + 1;
if (item + len + 1 > roll + hold) {
do { /* make roll bigger */
hold <<= 1;
} while (item + len + 1 > roll + hold);
bigger = REALLOC(roll, hold);
if (bigger == NULL) {
FREE(roll);
bail("not enough memory", "");
}
item = bigger + (item - roll);
roll = bigger;
}
strcpy(item, next->d_name);
item += len;
*item = 0;
}
closedir(here);
/* run process() for each entry in the directory */
cut = base = g.inf + strlen(g.inf);
if (base > g.inf && base[-1] != (unsigned char)'/') {
if ((size_t)(base - g.inf) >= sizeof(g.inf))
bail("path too long", g.inf);
*base++ = '/';
}
item = roll;
while (*item) {
strncpy(base, item, sizeof(g.inf) - (base - g.inf));
if (g.inf[sizeof(g.inf) - 1]) {
strcpy(g.inf + (sizeof(g.inf) - 4), "...");
bail("path too long: ", g.inf);
}
process(g.inf);
item += strlen(item) + 1;
}
*cut = 0;
/* release list of entries */
FREE(roll);
return;
}
/* don't compress .gz (or provided suffix) files, unless -f */
if (!(g.force || g.list || g.decode) && len >= strlen(g.sufx) &&
strcmp(g.inf + len - strlen(g.sufx), g.sufx) == 0) {
complain("%s ends with %s -- skipping", g.inf, g.sufx);
return;
}
/* create output file only if input file has compressed suffix */
if (g.decode == 1 && !g.pipeout && !g.list) {
int suf = compressed_suffix(g.inf);
if (suf == 0) {
complain("%s does not have compressed suffix -- skipping",
g.inf);
return;
}
len -= suf;
}
/* open input file */
g.ind = open(g.inf, O_RDONLY, 0);
if (g.ind < 0)
bail("read error on ", g.inf);
/* prepare gzip header information for compression */
g.name = g.headis & 1 ? justname(g.inf) : NULL;
g.mtime = g.headis & 2 ? st.st_mtime : 0;
}
SET_BINARY_MODE(g.ind);
/* if decoding or testing, try to read gzip header */
g.hname = NULL;
if (g.decode) {
in_init();
method = get_header(1);
if (method != 8 && method != 257 &&
/* gzip -cdf acts like cat on uncompressed input */
!(method == -2 && g.force && g.pipeout && g.decode != 2 &&
!g.list)) {
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
if (method != -1)
complain(method < 0 ? "%s is not compressed -- skipping" :
"%s has unknown compression method -- skipping",
g.inf);
return;
}
/* if requested, test input file (possibly a special list) */
if (g.decode == 2) {
if (method == 8)
infchk();
else {
unlzw();
if (g.list) {
g.in_tot -= 3;
show_info(method, 0, g.out_tot, 0);
}
}
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
}
/* if requested, just list information about input file */
if (g.list) {
list_info();
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* create output file out, descriptor outd */
if (path == NULL || g.pipeout) {
/* write to stdout */
g.outf = MALLOC(strlen("<stdout>") + 1);
if (g.outf == NULL)
bail("not enough memory", "");
strcpy(g.outf, "<stdout>");
g.outd = 1;
if (!g.decode && !g.force && isatty(g.outd))
bail("trying to write compressed data to a terminal",
" (use -f to force)");
}
else {
char *to, *repl;
/* use header name for output when decompressing with -N */
to = g.inf;
if (g.decode && (g.headis & 1) != 0 && g.hname != NULL) {
to = g.hname;
len = strlen(g.hname);
}
/* replace .tgz with .tar when decoding */
repl = g.decode && strcmp(to + len, ".tgz") ? "" : ".tar";
/* create output file and open to write */
g.outf = MALLOC(len + (g.decode ? strlen(repl) : strlen(g.sufx)) + 1);
if (g.outf == NULL)
bail("not enough memory", "");
memcpy(g.outf, to, len);
strcpy(g.outf + len, g.decode ? repl : g.sufx);
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY |
(g.force ? 0 : O_EXCL), 0600);
/* if exists and not -f, give user a chance to overwrite */
if (g.outd < 0 && errno == EEXIST && isatty(0) && g.verbosity) {
int ch, reply;
fprintf(stderr, "%s exists -- overwrite (y/n)? ", g.outf);
fflush(stderr);
reply = -1;
do {
ch = getchar();
if (reply < 0 && ch != ' ' && ch != '\t')
reply = ch == 'y' || ch == 'Y' ? 1 : 0;
} while (ch != EOF && ch != '\n' && ch != '\r');
if (reply == 1)
g.outd = open(g.outf, O_CREAT | O_TRUNC | O_WRONLY,
0600);
}
/* if exists and no overwrite, report and go on to next */
if (g.outd < 0 && errno == EEXIST) {
complain("%s exists -- skipping", g.outf);
RELEASE(g.outf);
RELEASE(g.hname);
if (g.ind != 0)
close(g.ind);
return;
}
/* if some other error, give up */
if (g.outd < 0)
bail("write error on ", g.outf);
}
SET_BINARY_MODE(g.outd);
RELEASE(g.hname);
/* process ind to outd */
if (g.verbosity > 1)
fprintf(stderr, "%s to %s ", g.inf, g.outf);
if (g.decode) {
if (method == 8)
infchk();
else if (method == 257)
unlzw();
else
cat();
}
#ifndef NOTHREAD
else if (g.procs > 1)
parallel_compress();
#endif
else
single_compress(0);
if (g.verbosity > 1) {
putc('\n', stderr);
fflush(stderr);
}
/* finish up, copy attributes, set times, delete original */
if (g.ind != 0)
close(g.ind);
if (g.outd != 1) {
if (close(g.outd))
bail("write error on ", g.outf);
g.outd = -1; /* now prevent deletion on interrupt */
if (g.ind != 0) {
copymeta(g.inf, g.outf);
if (!g.keep)
unlink(g.inf);
}
if (g.decode && (g.headis & 2) != 0 && g.stamp)
touch(g.outf, g.stamp);
}
RELEASE(g.outf);
}
local char *helptext[] = {
"Usage: pigz [options] [files ...]",
" will compress files in place, adding the suffix '.gz'. If no files are",
#ifdef NOTHREAD
" specified, stdin will be compressed to stdout. pigz does what gzip does.",
#else
" specified, stdin will be compressed to stdout. pigz does what gzip does,",
" but spreads the work over multiple processors and cores when compressing.",
#endif
"",
"Options:",
" -0 to -9, -11 Compression level (11 is much slower, a few % better)",
" --fast, --best Compression levels 1 and 9 respectively",
" -b, --blocksize mmm Set compression block size to mmmK (default 128K)",
" -c, --stdout Write all processed output to stdout (won't delete)",
" -d, --decompress Decompress the compressed input",
" -f, --force Force overwrite, compress .gz, links, and to terminal",
" -F --first Do iterations first, before block split for -11",
" -h, --help Display a help screen and quit",
" -i, --independent Compress blocks independently for damage recovery",
" -I, --iterations n Number of iterations for -11 optimization",
" -k, --keep Do not delete original file after processing",
" -K, --zip Compress to PKWare zip (.zip) single entry format",
" -l, --list List the contents of the compressed input",
" -L, --license Display the pigz license and quit",
" -M, --maxsplits n Maximum number of split blocks for -11",
" -n, --no-name Do not store or restore file name in/from header",
" -N, --name Store/restore file name and mod time in/from header",
" -O --oneblock Do not split into smaller blocks for -11",
#ifndef NOTHREAD
" -p, --processes n Allow up to n compression threads (default is the",
" number of online processors, or 8 if unknown)",
#endif
" -q, --quiet Print no messages, even on error",
" -r, --recursive Process the contents of all subdirectories",
" -R, --rsyncable Input-determined block locations for rsync",
" -S, --suffix .sss Use suffix .sss instead of .gz (for compression)",
" -t, --test Test the integrity of the compressed input",
" -T, --no-time Do not store or restore mod time in/from header",
#ifdef DEBUG
" -v, --verbose Provide more verbose output (-vv to debug)",
#else
" -v, --verbose Provide more verbose output",
#endif
" -V --version Show the version of pigz",
" -z, --zlib Compress to zlib (.zz) instead of gzip format",
" -- All arguments after \"--\" are treated as files"
};
/* display the help text above */
local void help(void)
{
int n;
if (g.verbosity == 0)
return;
for (n = 0; n < (int)(sizeof(helptext) / sizeof(char *)); n++)
fprintf(stderr, "%s\n", helptext[n]);
fflush(stderr);
exit(0);
}
#ifndef NOTHREAD
/* try to determine the number of processors */
local int nprocs(int n)
{
# ifdef _SC_NPROCESSORS_ONLN
n = (int)sysconf(_SC_NPROCESSORS_ONLN);
# else
# ifdef _SC_NPROC_ONLN
n = (int)sysconf(_SC_NPROC_ONLN);
# else
# ifdef __hpux
struct pst_dynamic psd;
if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) != -1)
n = psd.psd_proc_cnt;
# endif
# endif
# endif
return n;
}
#endif
/* set option defaults */
local void defaults(void)
{
g.level = Z_DEFAULT_COMPRESSION;
/* default zopfli options as set by ZopfliInitOptions():
verbose = 0
numiterations = 15
blocksplitting = 1
blocksplittinglast = 0
blocksplittingmax = 15
*/
ZopfliInitOptions(&g.zopts);
#ifdef NOTHREAD
g.procs = 1;
#else
g.procs = nprocs(8);
#endif
g.block = 131072UL; /* 128K */
g.rsync = 0; /* don't do rsync blocking */
g.setdict = 1; /* initialize dictionary each thread */
g.verbosity = 1; /* normal message level */
g.headis = 3; /* store/restore name and timestamp */
g.pipeout = 0; /* don't force output to stdout */
g.sufx = ".gz"; /* compressed file suffix */
g.decode = 0; /* compress */
g.list = 0; /* compress */
g.keep = 0; /* delete input file once compressed */
g.force = 0; /* don't overwrite, don't compress links */
g.recurse = 0; /* don't go into directories */
g.form = 0; /* use gzip format */
}
/* long options conversion to short options */
local char *longopts[][2] = {
{"LZW", "Z"}, {"ascii", "a"}, {"best", "9"}, {"bits", "Z"},
{"blocksize", "b"}, {"decompress", "d"}, {"fast", "1"}, {"first", "F"},
{"force", "f"}, {"help", "h"}, {"independent", "i"}, {"iterations", "I"},
{"keep", "k"}, {"license", "L"}, {"list", "l"}, {"maxsplits", "M"},
{"name", "N"}, {"no-name", "n"}, {"no-time", "T"}, {"oneblock", "O"},
{"processes", "p"}, {"quiet", "q"}, {"recursive", "r"}, {"rsyncable", "R"},
{"silent", "q"}, {"stdout", "c"}, {"suffix", "S"}, {"test", "t"},
{"to-stdout", "c"}, {"uncompress", "d"}, {"verbose", "v"},
{"version", "V"}, {"zip", "K"}, {"zlib", "z"}};
#define NLOPTS (sizeof(longopts) / (sizeof(char *) << 1))
/* either new buffer size, new compression level, or new number of processes --
get rid of old buffers and threads to force the creation of new ones with
the new settings */
local void new_opts(void)
{
single_compress(1);
#ifndef NOTHREAD
finish_jobs();
#endif
}
/* verify that arg is only digits, and if so, return the decimal value */
local size_t num(char *arg)
{
char *str = arg;
size_t val = 0;
if (*str == 0)
bail("internal error: empty parameter", "");
do {
if (*str < '0' || *str > '9' ||
(val && ((~(size_t)0) - (*str - '0')) / val < 10))
bail("invalid numeric parameter: ", arg);
val = val * 10 + (*str - '0');
} while (*++str);
return val;
}
/* process an option, return true if a file name and not an option */
local int option(char *arg)
{
static int get = 0; /* if not zero, look for option parameter */
char bad[3] = "-X"; /* for error messages (X is replaced) */
/* if no argument or dash option, check status of get */
if (get && (arg == NULL || *arg == '-')) {
bad[1] = "bpSIM"[get - 1];
bail("missing parameter after ", bad);
}
if (arg == NULL)
return 0;
/* process long option or short options */
if (*arg == '-') {
/* a single dash will be interpreted as stdin */
if (*++arg == 0)
return 1;
/* process long option (fall through with equivalent short option) */
if (*arg == '-') {
int j;
arg++;
for (j = NLOPTS - 1; j >= 0; j--)
if (strcmp(arg, longopts[j][0]) == 0) {
arg = longopts[j][1];
break;
}
if (j < 0)
bail("invalid option: ", arg - 2);
}
/* process short options (more than one allowed after dash) */
do {
/* if looking for a parameter, don't process more single character
options until we have the parameter */
if (get) {
if (get == 3)
bail("invalid usage: -s must be followed by space", "");
break; /* allow -pnnn and -bnnn, fall to parameter code */
}
/* process next single character option or compression level */
bad[1] = *arg;
switch (*arg) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
g.level = *arg - '0';
while (arg[1] >= '0' && arg[1] <= '9') {
if (g.level && (INT_MAX - (arg[1] - '0')) / g.level < 10)
bail("only levels 0..9 and 11 are allowed", "");
g.level = g.level * 10 + *++arg - '0';
}
if (g.level == 10 || g.level > 11)
bail("only levels 0..9 and 11 are allowed", "");
new_opts();
break;
case 'F': g.zopts.blocksplittinglast = 1; break;
case 'I': get = 4; break;
case 'K': g.form = 2; g.sufx = ".zip"; break;
case 'L':
fputs(VERSION, stderr);
fputs("Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013"
" Mark Adler\n",
stderr);
fputs("Subject to the terms of the zlib license.\n",
stderr);
fputs("No warranty is provided or implied.\n", stderr);
exit(0);
case 'M': get = 5; break;
case 'N': g.headis |= 0xf; break;
case 'O': g.zopts.blocksplitting = 0; break;
case 'R': g.rsync = 1; break;
case 'S': get = 3; break;
case 'T': g.headis &= ~0xa; break;
case 'V': fputs(VERSION, stderr); exit(0);
case 'Z':
bail("invalid option: LZW output not supported: ", bad);
case 'a':
bail("invalid option: ascii conversion not supported: ", bad);
case 'b': get = 1; break;
case 'c': g.pipeout = 1; break;
case 'd': if (!g.decode) g.headis >>= 2; g.decode = 1; break;
case 'f': g.force = 1; break;
case 'h': help(); break;
case 'i': g.setdict = 0; break;
case 'k': g.keep = 1; break;
case 'l': g.list = 1; break;
case 'n': g.headis &= ~5; break;
case 'p': get = 2; break;
case 'q': g.verbosity = 0; break;
case 'r': g.recurse = 1; break;
case 't': g.decode = 2; break;
case 'v': g.verbosity++; break;
case 'z': g.form = 1; g.sufx = ".zz"; break;
default:
bail("invalid option: ", bad);
}
} while (*++arg);
if (*arg == 0)
return 0;
}
/* process option parameter for -b, -p, -S, -I, or -M */
if (get) {
size_t n;
if (get == 1) {
n = num(arg);
g.block = n << 10; /* chunk size */
if (g.block < DICT)
bail("block size too small (must be >= 32K)", "");
if (n != g.block >> 10 ||
OUTPOOL(g.block) < g.block ||
(ssize_t)OUTPOOL(g.block) < 0 ||
g.block > (1UL << 29)) /* limited by append_len() */
bail("block size too large: ", arg);
new_opts();
}
else if (get == 2) {
n = num(arg);
g.procs = (int)n; /* # processes */
if (g.procs < 1)
bail("invalid number of processes: ", arg);
if ((size_t)g.procs != n || INBUFS(g.procs) < 1)
bail("too many processes: ", arg);
#ifdef NOTHREAD
if (g.procs > 1)
bail("compiled without threads", "");
#endif
new_opts();
}
else if (get == 3)
g.sufx = arg; /* gz suffix */
else if (get == 4)
g.zopts.numiterations = num(arg); /* optimization iterations */
else if (get == 5)
g.zopts.blocksplittingmax = num(arg); /* max block splits */
get = 0;
return 0;
}
/* neither an option nor parameter */
return 1;
}
/* catch termination signal */
local void cut_short(int sig)
{
(void)sig;
Trace(("termination by user"));
if (g.outd != -1 && g.outf != NULL)
unlink(g.outf);
log_dump();
_exit(1);
}
/* Process arguments, compress in the gzip format. Note that procs must be at
least two in order to provide a dictionary in one work unit for the other
work unit, and that size must be at least 32K to store a full dictionary. */
int main(int argc, char **argv)
{
int n; /* general index */
int noop; /* true to suppress option decoding */
unsigned long done; /* number of named files processed */
char *opts, *p; /* environment default options, marker */
/* initialize globals */
g.outf = NULL;
g.first = 1;
g.hname = NULL;
/* save pointer to program name for error messages */
p = strrchr(argv[0], '/');
p = p == NULL ? argv[0] : p + 1;
g.prog = *p ? p : "pigz";
/* prepare for interrupts and logging */
signal(SIGINT, cut_short);
#ifndef NOTHREAD
yarn_prefix = g.prog; /* prefix for yarn error messages */
yarn_abort = cut_short; /* call on thread error */
#endif
#ifdef DEBUG
gettimeofday(&start, NULL); /* starting time for log entries */
log_init(); /* initialize logging */
#endif
/* set all options to defaults */
defaults();
/* process user environment variable defaults in GZIP */
opts = getenv("GZIP");
if (opts != NULL) {
while (*opts) {
while (*opts == ' ' || *opts == '\t')
opts++;
p = opts;
while (*p && *p != ' ' && *p != '\t')
p++;
n = *p;
*p = 0;
if (option(opts))
bail("cannot provide files in GZIP environment variable", "");
opts = p + (n ? 1 : 0);
}
option(NULL);
}
/* process user environment variable defaults in PIGZ as well */
opts = getenv("PIGZ");
if (opts != NULL) {
while (*opts) {
while (*opts == ' ' || *opts == '\t')
opts++;
p = opts;
while (*p && *p != ' ' && *p != '\t')
p++;
n = *p;
*p = 0;
if (option(opts))
bail("cannot provide files in PIGZ environment variable", "");
opts = p + (n ? 1 : 0);
}
option(NULL);
}
/* decompress if named "unpigz" or "gunzip", to stdout if "*cat" */
if (strcmp(g.prog, "unpigz") == 0 || strcmp(g.prog, "gunzip") == 0) {
if (!g.decode)
g.headis >>= 2;
g.decode = 1;
}
if ((n = strlen(g.prog)) > 2 && strcmp(g.prog + n - 3, "cat") == 0) {
if (!g.decode)
g.headis >>= 2;
g.decode = 1;
g.pipeout = 1;
}
/* if no arguments and compressed data to or from a terminal, show help */
if (argc < 2 && isatty(g.decode ? 0 : 1))
help();
/* process command-line arguments, no options after "--" */
done = noop = 0;
for (n = 1; n < argc; n++)
if (noop == 0 && strcmp(argv[n], "--") == 0) {
noop = 1;
option(NULL);
}
else if (noop || option(argv[n])) { /* true if file name, process it */
if (done == 1 && g.pipeout && !g.decode && !g.list && g.form > 1)
complain("warning: output will be concatenated zip files -- "
"will not be able to extract");
process(strcmp(argv[n], "-") ? argv[n] : NULL);
done++;
}
option(NULL);
/* list stdin or compress stdin to stdout if no file names provided */
if (done == 0)
process(NULL);
/* done -- release resources, show log */
new_opts();
log_dump();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1466_0 |
crossvul-cpp_data_good_1567_0 | /*
Copyright (C) 2010 ABRT team
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, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "problem_api.h"
#include "libabrt.h"
/* Maximal length of backtrace. */
#define MAX_BACKTRACE_SIZE (1024*1024)
/* Amount of data received from one client for a message before reporting error. */
#define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE)
/* Maximal number of characters read from socket at once. */
#define INPUT_BUFFER_SIZE (8*1024)
/* We exit after this many seconds */
#define TIMEOUT 10
/*
Unix socket in ABRT daemon for creating new dump directories.
Why to use socket for creating dump dirs? Security. When a Python
script throws unexpected exception, ABRT handler catches it, running
as a part of that broken Python application. The application is running
with certain SELinux privileges, for example it can not execute other
programs, or to create files in /var/cache or anything else required
to properly fill a problem directory. Adding these privileges to every
application would weaken the security.
The most suitable solution is for the Python application
to open a socket where ABRT daemon is listening, write all relevant
data to that socket, and close it. ABRT daemon handles the rest.
** Protocol
Initializing new dump:
open /var/run/abrt.socket
Providing dump data (hook writes to the socket):
MANDATORY ITEMS:
-> "PID="
number 0 - PID_MAX (/proc/sys/kernel/pid_max)
\0
-> "EXECUTABLE="
string
\0
-> "BACKTRACE="
string
\0
-> "ANALYZER="
string
\0
-> "BASENAME="
string (no slashes)
\0
-> "REASON="
string
\0
You can send more messages using the same KEY=value format.
*/
static unsigned total_bytes_read = 0;
static uid_t client_uid = (uid_t)-1L;
static bool dir_is_in_dump_location(const char *dump_dir_name)
{
unsigned len = strlen(g_settings_dump_location);
if (strncmp(dump_dir_name, g_settings_dump_location, len) == 0
&& dump_dir_name[len] == '/'
/* must not contain "/." anywhere (IOW: disallow ".." component) */
&& !strstr(dump_dir_name + len, "/.")
) {
return 1;
}
return 0;
}
/* Remove dump dir */
static int delete_path(const char *dump_dir_name)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dump_dir_name))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location);
return 400; /* Bad Request */
}
if (!dump_dir_accessible_by_uid(dump_dir_name, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dump_dir_name);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid);
return 403; /* Forbidden */
}
delete_dump_dir(dump_dir_name);
return 0; /* success */
}
static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp)
{
char *args[7];
args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event";
/* Do not forward ASK_* messages to parent*/
args[1] = (char *) "-i";
args[2] = (char *) "-e";
args[3] = (char *) event_name;
args[4] = (char *) "--";
args[5] = (char *) dump_dir_name;
args[6] = NULL;
int pipeout[2];
int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT;
VERB1 flags &= ~EXECFLG_QUIET;
char *env_vec[2];
/* Intercept ASK_* messages in Client API -> don't wait for user response */
env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1");
env_vec[1] = NULL;
pid_t child = fork_execv_on_steroids(flags, args, pipeout,
env_vec, /*dir:*/ NULL,
/*uid(unused):*/ 0);
if (fdp)
*fdp = pipeout[0];
return child;
}
static int run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (g_settings_privatereports)
{
struct stat statbuf;
if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
{
error_msg("Path '%s' isn't directory", dirname);
return 404; /* Not Found */
}
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (!gr)
{
error_msg("Group 'abrt' does not exist");
return 500;
}
if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname);
return 403;
}
struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);
const bool complete = dd && problem_dump_dir_is_complete(dd);
dd_close(dd);
if (complete)
{
error_msg("Problem directory '%s' has already been processed", dirname);
return 403;
}
}
else if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
//log("Reading from event fd %d", child_stdout_fd);
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
//log("Started notify, fd %d -> %d", fd, child_stdout_fd);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
}
/* Create a new problem directory from client session.
* Caller must ensure that all fields in struct client
* are properly filled.
*/
static int create_problem_dir(GHashTable *problem_info, unsigned pid)
{
/* Exit if free space is less than 1/4 of MaxCrashReportsSize */
if (g_settings_nMaxCrashReportsSize > 0)
{
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
exit(1);
}
/* Create temp directory with the problem data.
* This directory is renamed to final directory name after
* all files have been stored into it.
*/
gchar *dir_basename = g_hash_table_lookup(problem_info, "basename");
if (!dir_basename)
dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE);
char *path = xasprintf("%s/%s-%s-%u.new",
g_settings_dump_location,
dir_basename,
iso_date_string(NULL),
pid);
/* This item is useless, don't save it */
g_hash_table_remove(problem_info, "basename");
/* No need to check the path length, as all variables used are limited,
* and dd_create() fails if the path is too long.
*/
struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE);
if (!dd)
{
error_msg_and_die("Error creating problem directory '%s'", path);
}
dd_create_basic_files(dd, client_uid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE);
if (!gpkey)
{
/* Obtain and save the command line. */
char *cmdline = get_cmdline(pid);
if (cmdline)
{
dd_save_text(dd, FILENAME_CMDLINE, cmdline);
free(cmdline);
}
}
/* Store id of the user whose application crashed. */
char uid_str[sizeof(long) * 3 + 2];
sprintf(uid_str, "%lu", (long)client_uid);
dd_save_text(dd, FILENAME_UID, uid_str);
GHashTableIter iter;
gpointer gpvalue;
g_hash_table_iter_init(&iter, problem_info);
while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue))
{
dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue);
}
dd_close(dd);
/* Not needing it anymore */
g_hash_table_destroy(problem_info);
/* Move the completely created problem directory
* to final directory.
*/
char *newpath = xstrndup(path, strlen(path) - strlen(".new"));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log_notice("Saved problem directory of pid %u to '%s'", pid, path);
/* We let the peer know that problem dir was created successfully
* _before_ we run potentially long-running post-create.
*/
printf("HTTP/1.1 201 Created\r\n\r\n");
fflush(NULL);
close(STDOUT_FILENO);
xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */
/* Trim old problem directories if necessary */
if (g_settings_nMaxCrashReportsSize > 0)
{
trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path);
}
run_post_create(path);
/* free(path); */
exit(0);
}
static gboolean key_value_ok(gchar *key, gchar *value)
{
char *i;
/* check key, it has to be valid filename and will end up in the
* bugzilla */
for (i = key; *i != 0; i++)
{
if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' '))
return FALSE;
}
/* check value of 'basename', it has to be valid non-hidden directory
* name */
if (strcmp(key, "basename") == 0
|| strcmp(key, FILENAME_TYPE) == 0
)
{
if (!str_is_correct_filename(value))
{
error_msg("Value of '%s' ('%s') is not a valid directory name",
key, value);
return FALSE;
}
}
return TRUE;
}
/* Handles a message received from client over socket. */
static void process_message(GHashTable *problem_info, char *message)
{
gchar *key, *value;
value = strchr(message, '=');
if (value)
{
key = g_ascii_strdown(message, value - message); /* result is malloced */
//TODO: is it ok? it uses g_malloc, not malloc!
value++;
if (key_value_ok(key, value))
{
if (strcmp(key, FILENAME_UID) == 0)
{
error_msg("Ignoring value of %s, will be determined later",
FILENAME_UID);
}
else
{
g_hash_table_insert(problem_info, key, xstrdup(value));
/* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */
if (strcmp(key, FILENAME_TYPE) == 0)
g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value));
/* Prevent freeing key later: */
key = NULL;
}
}
else
{
/* should use error_msg_and_die() here? */
error_msg("Invalid key or value format: %s", message);
}
free(key);
}
else
{
/* should use error_msg_and_die() here? */
error_msg("Invalid message format: '%s'", message);
}
}
static void die_if_data_is_missing(GHashTable *problem_info)
{
gboolean missing_data = FALSE;
gchar **pstring;
static const gchar *const needed[] = {
FILENAME_TYPE,
FILENAME_REASON,
/* FILENAME_BACKTRACE, - ECC errors have no such elements */
/* FILENAME_EXECUTABLE, */
NULL
};
for (pstring = (gchar**) needed; *pstring; pstring++)
{
if (!g_hash_table_lookup(problem_info, *pstring))
{
error_msg("Element '%s' is missing", *pstring);
missing_data = TRUE;
}
}
if (missing_data)
error_msg_and_die("Some data is missing, aborting");
}
/*
* Takes hash table, looks for key FILENAME_PID and tries to convert its value
* to int.
*/
unsigned convert_pid(GHashTable *problem_info)
{
long ret;
gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID);
char *err_pos;
if (!pid_str)
error_msg_and_die("PID data is missing, aborting");
errno = 0;
ret = strtol(pid_str, &err_pos, 10);
if (errno || pid_str == err_pos || *err_pos != '\0'
|| ret > UINT_MAX || ret < 1)
error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str);
return (unsigned) ret;
}
static int perform_http_xact(void)
{
/* use free instead of g_free so that we can use xstr* functions from
* libreport/lib/xfuncs.c
*/
GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal,
free, free);
/* Read header */
char *body_start = NULL;
char *messagebuf_data = NULL;
unsigned messagebuf_len = 0;
/* Loop until EOF/error/timeout/end_of_header */
while (1)
{
messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE);
char *p = messagebuf_data + messagebuf_len;
int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE);
if (rd < 0)
{
if (errno == EINTR) /* SIGALRM? */
error_msg_and_die("Timed out");
perror_msg_and_die("read");
}
if (rd == 0)
break;
log_debug("Received %u bytes of data", rd);
messagebuf_len += rd;
total_bytes_read += rd;
if (total_bytes_read > MAX_MESSAGE_SIZE)
error_msg_and_die("Message is too long, aborting");
/* Check whether we see end of header */
/* Note: we support both [\r]\n\r\n and \n\n */
char *past_end = messagebuf_data + messagebuf_len;
if (p > messagebuf_data+1)
p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */
while (p < past_end)
{
p = memchr(p, '\n', past_end - p);
if (!p)
break;
p++;
if (p >= past_end)
break;
if (*p == '\n'
|| (*p == '\r' && p+1 < past_end && p[1] == '\n')
) {
body_start = p + 1 + (*p == '\r');
*p = '\0';
goto found_end_of_header;
}
}
} /* while (read) */
found_end_of_header: ;
log_debug("Request: %s", messagebuf_data);
/* Sanitize and analyze header.
* Header now is in messagebuf_data, NUL terminated string,
* with last empty line deleted (by placement of NUL).
* \r\n are not (yet) converted to \n, multi-line headers also
* not converted.
*/
/* First line must be "op<space>[http://host]/path<space>HTTP/n.n".
* <space> is exactly one space char.
*/
if (prefixcmp(messagebuf_data, "DELETE ") == 0)
{
messagebuf_data += strlen("DELETE ");
char *space = strchr(messagebuf_data, ' ');
if (!space || prefixcmp(space+1, "HTTP/") != 0)
return 400; /* Bad Request */
*space = '\0';
//decode_url(messagebuf_data); %20 => ' '
alarm(0);
return delete_path(messagebuf_data);
}
/* We erroneously used "PUT /" to create new problems.
* POST is the correct request in this case:
* "PUT /" implies creation or replace of resource named "/"!
* Delete PUT in 2014.
*/
if (prefixcmp(messagebuf_data, "PUT ") != 0
&& prefixcmp(messagebuf_data, "POST ") != 0
) {
return 400; /* Bad Request */
}
enum {
CREATION_NOTIFICATION,
CREATION_REQUEST,
};
int url_type;
char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */
if (prefixcmp(url, "/creation_notification ") == 0)
url_type = CREATION_NOTIFICATION;
else if (prefixcmp(url, "/ ") == 0)
url_type = CREATION_REQUEST;
else
return 400; /* Bad Request */
/* Read body */
if (!body_start)
{
log_warning("Premature EOF detected, exiting");
return 400; /* Bad Request */
}
messagebuf_len -= (body_start - messagebuf_data);
memmove(messagebuf_data, body_start, messagebuf_len);
log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data);
/* Loop until EOF/error/timeout */
while (1)
{
if (url_type == CREATION_REQUEST)
{
while (1)
{
unsigned len = strnlen(messagebuf_data, messagebuf_len);
if (len >= messagebuf_len)
break;
/* messagebuf has at least one NUL - process the line */
process_message(problem_info, messagebuf_data);
messagebuf_len -= (len + 1);
memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len);
}
}
messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1);
int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE);
if (rd < 0)
{
if (errno == EINTR) /* SIGALRM? */
error_msg_and_die("Timed out");
perror_msg_and_die("read");
}
if (rd == 0)
break;
log_debug("Received %u bytes of data", rd);
messagebuf_len += rd;
total_bytes_read += rd;
if (total_bytes_read > MAX_MESSAGE_SIZE)
error_msg_and_die("Message is too long, aborting");
}
/* Body received, EOF was seen. Don't let alarm to interrupt after this. */
alarm(0);
if (url_type == CREATION_NOTIFICATION)
{
messagebuf_data[messagebuf_len] = '\0';
return run_post_create(messagebuf_data);
}
/* Save problem dir */
int ret = 0;
unsigned pid = convert_pid(problem_info);
die_if_data_is_missing(problem_info);
char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE);
if (executable)
{
char *last_file = concat_path_file(g_settings_dump_location, "last-via-server");
int repeating_crash = check_recent_crash_file(last_file, executable);
free(last_file);
if (repeating_crash) /* Only pretend that we saved it */
goto out; /* ret is 0: "success" */
}
#if 0
//TODO:
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(problem_info);
//...the problem being that problem_info here is not a problem_data_t!
#endif
create_problem_dir(problem_info, pid);
/* does not return */
out:
g_hash_table_destroy(problem_info);
return ret; /* Used as HTTP response code */
}
static void dummy_handler(int sig_unused) {}
int main(int argc, char **argv)
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
abrt_init(argv);
/* Can't keep these strings/structs static: _() doesn't support that */
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_u = 1 << 1,
OPT_s = 1 << 2,
OPT_p = 1 << 3,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")),
OPT_BOOL( 's', NULL, NULL , _("Log to syslog")),
OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")),
OPT_END()
};
unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(opts & OPT_p);
msg_prefix = xasprintf("%s[%u]", g_progname, getpid());
if (opts & OPT_s)
{
logmode = LOGMODE_JOURNAL;
}
/* Set up timeout handling */
/* Part 1 - need this to make SIGALRM interrupt syscalls
* (as opposed to restarting them): I want read syscall to be interrupted
*/
struct sigaction sa;
/* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */
memset(&sa, 0, sizeof(sa));
sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */
sigaction(SIGALRM, &sa, NULL);
/* Part 2 - set the timeout per se */
alarm(TIMEOUT);
if (client_uid == (uid_t)-1L)
{
/* Get uid of the connected client */
struct ucred cr;
socklen_t crlen = sizeof(cr);
if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen))
perror_msg_and_die("getsockopt(SO_PEERCRED)");
if (crlen != sizeof(cr))
error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen);
client_uid = cr.uid;
}
load_abrt_conf();
int r = perform_http_xact();
if (r == 0)
r = 200;
free_abrt_conf_data();
printf("HTTP/1.1 %u \r\n\r\n", r);
return (r >= 400); /* Error if 400+ */
}
#if 0
// TODO: example of SSLed connection
#include <openssl/ssl.h>
#include <openssl/err.h>
if (flags & OPT_SSL) {
/* load key and cert files */
SSL_CTX *ctx;
SSL *ssl;
ctx = init_ssl_context();
if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0
|| SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0
) {
ERR_print_errors_fp(stderr);
error_msg_and_die("SSL certificates err\n");
}
if (!SSL_CTX_check_private_key(ctx)) {
error_msg_and_die("Private key does not match public key\n");
}
(void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
//TODO more errors?
ssl = SSL_new(ctx);
SSL_set_fd(ssl, sockfd_in);
//SSL_set_accept_state(ssl);
if (SSL_accept(ssl) == 1) {
//while whatever serve
while (serve(ssl, flags))
continue;
//TODO errors
SSL_shutdown(ssl);
}
SSL_free(ssl);
SSL_CTX_free(ctx);
} else {
while (serve(&sockfd_in, flags))
continue;
}
err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1):
read(*(int*)sock, buffer, READ_BUF-1);
if ( err < 0 ) {
//TODO handle errno || SSL_get_error(ssl,err);
break;
}
if ( err == 0 ) break;
if (!head) {
buffer[err] = '\0';
clean[i%2] = delete_cr(buffer);
cut = g_strstr_len(buffer, -1, "\n\n");
if ( cut == NULL ) {
g_string_append(headers, buffer);
} else {
g_string_append_len(headers, buffer, cut-buffer);
}
}
/* end of header section? */
if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) {
parse_head(&request, headers);
head = TRUE;
c_len = has_body(&request);
if ( c_len ) {
//if we want to read body some day - this will be the right place to begin
//malloc body append rest of the (fixed) buffer at the beginning of a body
//if clean buffer[1];
} else {
break;
}
break; //because we don't support body yet
} else if ( head == TRUE ) {
/* body-reading stuff
* read body, check content-len
* save body to request
*/
break;
} else {
// count header size
len += err;
if ( len > READ_BUF-1 ) {
//TODO header is too long
break;
}
}
i++;
}
g_string_free(headers, true); //because we allocated it
rt = generate_response(&request, &response);
/* write headers */
if ( flags & OPT_SSL ) {
//TODO err
err = SSL_write(sock, response.response_line, strlen(response.response_line));
err = SSL_write(sock, response.head->str , strlen(response.head->str));
err = SSL_write(sock, "\r\n", 2);
} else {
//TODO err
err = write(*(int*)sock, response.response_line, strlen(response.response_line));
err = write(*(int*)sock, response.head->str , strlen(response.head->str));
err = write(*(int*)sock, "\r\n", 2);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1567_0 |
crossvul-cpp_data_bad_249_0 | /**
* @file
* IMAP helper functions
*
* @authors
* Copyright (C) 1996-1998,2010,2012-2013 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1996-1999 Brandon Long <blong@fiction.net>
* Copyright (C) 1999-2009,2012 Brendan Cully <brendan@kublai.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page imap_util IMAP helper functions
*
* IMAP helper functions
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "imap_private.h"
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "bcache.h"
#include "context.h"
#include "globals.h"
#include "header.h"
#include "imap/imap.h"
#include "mailbox.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_socket.h"
#include "mx.h"
#include "options.h"
#include "protos.h"
#include "url.h"
#ifdef USE_HCACHE
#include "hcache/hcache.h"
#endif
/**
* imap_expand_path - Canonicalise an IMAP path
* @param path Buffer containing path
* @param len Buffer length
* @retval 0 Success
* @retval -1 Error
*
* IMAP implementation of mutt_expand_path. Rewrite an IMAP path in canonical
* and absolute form. The buffer is rewritten in place with the canonical IMAP
* path.
*
* Function can fail if imap_parse_path() or url_tostring() fail,
* of if the buffer isn't large enough.
*/
int imap_expand_path(char *path, size_t len)
{
struct ImapMbox mx;
struct ImapData *idata = NULL;
struct Url url;
char fixedpath[LONG_STRING];
int rc;
if (imap_parse_path(path, &mx) < 0)
return -1;
idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW);
mutt_account_tourl(&mx.account, &url);
imap_fix_path(idata, mx.mbox, fixedpath, sizeof(fixedpath));
url.path = fixedpath;
rc = url_tostring(&url, path, len, U_DECODE_PASSWD);
FREE(&mx.mbox);
return rc;
}
/**
* imap_get_parent - Get an IMAP folder's parent
* @param output Buffer for the result
* @param mbox Mailbox whose parent is to be determined
* @param olen Length of the buffer
* @param delim Path delimiter
*/
void imap_get_parent(char *output, const char *mbox, size_t olen, char delim)
{
int n;
/* Make a copy of the mailbox name, but only if the pointers are different */
if (mbox != output)
mutt_str_strfcpy(output, mbox, olen);
n = mutt_str_strlen(output);
/* Let's go backwards until the next delimiter
*
* If output[n] is a '/', the first n-- will allow us
* to ignore it. If it isn't, then output looks like
* "/aaaaa/bbbb". There is at least one "b", so we can't skip
* the "/" after the 'a's.
*
* If output == '/', then n-- => n == 0, so the loop ends
* immediately
*/
for (n--; n >= 0 && output[n] != delim; n--)
;
/* We stopped before the beginning. There is a trailing
* slash.
*/
if (n > 0)
{
/* Strip the trailing delimiter. */
output[n] = '\0';
}
else
{
output[0] = (n == 0) ? delim : '\0';
}
}
/**
* imap_get_parent_path - Get the path of the parent folder
* @param output Buffer for the result
* @param path Mailbox whose parent is to be determined
* @param olen Length of the buffer
*
* Provided an imap path, returns in output the parent directory if
* existent. Else returns the same path.
*/
void imap_get_parent_path(char *output, const char *path, size_t olen)
{
struct ImapMbox mx;
struct ImapData *idata = NULL;
char mbox[LONG_STRING] = "";
if (imap_parse_path(path, &mx) < 0)
{
mutt_str_strfcpy(output, path, olen);
return;
}
idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW);
if (!idata)
{
mutt_str_strfcpy(output, path, olen);
return;
}
/* Stores a fixed path in mbox */
imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox));
/* Gets the parent mbox in mbox */
imap_get_parent(mbox, mbox, sizeof(mbox), idata->delim);
/* Returns a fully qualified IMAP url */
imap_qualify_path(output, olen, &mx, mbox);
FREE(&mx.mbox);
}
/**
* imap_clean_path - Cleans an IMAP path using imap_fix_path
* @param path Path to be cleaned
* @param plen Length of the buffer
*
* Does it in place.
*/
void imap_clean_path(char *path, size_t plen)
{
struct ImapMbox mx;
struct ImapData *idata = NULL;
char mbox[LONG_STRING] = "";
if (imap_parse_path(path, &mx) < 0)
return;
idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW);
if (!idata)
return;
/* Stores a fixed path in mbox */
imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox));
/* Returns a fully qualified IMAP url */
imap_qualify_path(path, plen, &mx, mbox);
}
#ifdef USE_HCACHE
/**
* imap_hcache_namer - Generate a filename for the header cache
* @param path Path for the header cache file
* @param dest Buffer for result
* @param dlen Length of buffer
* @retval num Chars written to dest
*/
static int imap_hcache_namer(const char *path, char *dest, size_t dlen)
{
return snprintf(dest, dlen, "%s.hcache", path);
}
/**
* imap_hcache_open - Open a header cache
* @param idata Server data
* @param path Path to the header cache
* @retval ptr HeaderCache
* @retval NULL Failure
*/
header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)
{
struct ImapMbox mx;
struct Url url;
char cachepath[PATH_MAX];
char mbox[PATH_MAX];
if (path)
imap_cachepath(idata, path, mbox, sizeof(mbox));
else
{
if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)
return NULL;
imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));
FREE(&mx.mbox);
}
mutt_account_tourl(&idata->conn->account, &url);
url.path = mbox;
url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);
return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);
}
/**
* imap_hcache_close - Close the header cache
* @param idata Server data
*/
void imap_hcache_close(struct ImapData *idata)
{
if (!idata->hcache)
return;
mutt_hcache_close(idata->hcache);
idata->hcache = NULL;
}
/**
* imap_hcache_get - Get a header cache entry by its UID
* @param idata Server data
* @param uid UID to find
* @retval ptr Email Header
* @retval NULL Failure
*/
struct Header *imap_hcache_get(struct ImapData *idata, unsigned int uid)
{
char key[16];
void *uv = NULL;
struct Header *h = NULL;
if (!idata->hcache)
return NULL;
sprintf(key, "/%u", uid);
uv = mutt_hcache_fetch(idata->hcache, key, imap_hcache_keylen(key));
if (uv)
{
if (*(unsigned int *) uv == idata->uid_validity)
h = mutt_hcache_restore(uv);
else
mutt_debug(3, "hcache uidvalidity mismatch: %u\n", *(unsigned int *) uv);
mutt_hcache_free(idata->hcache, &uv);
}
return h;
}
/**
* imap_hcache_put - Add an entry to the header cache
* @param idata Server data
* @param h Email Header
* @retval 0 Success
* @retval -1 Failure
*/
int imap_hcache_put(struct ImapData *idata, struct Header *h)
{
char key[16];
if (!idata->hcache)
return -1;
sprintf(key, "/%u", HEADER_DATA(h)->uid);
return mutt_hcache_store(idata->hcache, key, imap_hcache_keylen(key), h, idata->uid_validity);
}
/**
* imap_hcache_del - Delete an item from the header cache
* @param idata Server data
* @param uid UID of entry to delete
* @retval 0 Success
* @retval -1 Failure
*/
int imap_hcache_del(struct ImapData *idata, unsigned int uid)
{
char key[16];
if (!idata->hcache)
return -1;
sprintf(key, "/%u", uid);
return mutt_hcache_delete(idata->hcache, key, imap_hcache_keylen(key));
}
#endif
/**
* imap_parse_path - Parse an IMAP mailbox name into name,host,port
* @param path Mailbox path to parse
* @param mx An IMAP mailbox
* @retval 0 Success
* @retval -1 Failure
*
* Given an IMAP mailbox name, return host, port and a path IMAP servers will
* recognize. mx.mbox is malloc'd, caller must free it
*/
int imap_parse_path(const char *path, struct ImapMbox *mx)
{
static unsigned short ImapPort = 0;
static unsigned short ImapsPort = 0;
struct servent *service = NULL;
struct Url url;
char *c = NULL;
if (!ImapPort)
{
service = getservbyname("imap", "tcp");
if (service)
ImapPort = ntohs(service->s_port);
else
ImapPort = IMAP_PORT;
mutt_debug(3, "Using default IMAP port %d\n", ImapPort);
}
if (!ImapsPort)
{
service = getservbyname("imaps", "tcp");
if (service)
ImapsPort = ntohs(service->s_port);
else
ImapsPort = IMAP_SSL_PORT;
mutt_debug(3, "Using default IMAPS port %d\n", ImapsPort);
}
/* Defaults */
memset(&mx->account, 0, sizeof(mx->account));
mx->account.port = ImapPort;
mx->account.type = MUTT_ACCT_TYPE_IMAP;
c = mutt_str_strdup(path);
url_parse(&url, c);
if (url.scheme == U_IMAP || url.scheme == U_IMAPS)
{
if (mutt_account_fromurl(&mx->account, &url) < 0 || !*mx->account.host)
{
url_free(&url);
FREE(&c);
return -1;
}
mx->mbox = mutt_str_strdup(url.path);
if (url.scheme == U_IMAPS)
mx->account.flags |= MUTT_ACCT_SSL;
url_free(&url);
FREE(&c);
}
/* old PINE-compatibility code */
else
{
url_free(&url);
FREE(&c);
char tmp[128];
if (sscanf(path, "{%127[^}]}", tmp) != 1)
return -1;
c = strchr(path, '}');
if (!c)
return -1;
else
{
/* walk past closing '}' */
mx->mbox = mutt_str_strdup(c + 1);
}
c = strrchr(tmp, '@');
if (c)
{
*c = '\0';
mutt_str_strfcpy(mx->account.user, tmp, sizeof(mx->account.user));
mutt_str_strfcpy(tmp, c + 1, sizeof(tmp));
mx->account.flags |= MUTT_ACCT_USER;
}
const int n = sscanf(tmp, "%127[^:/]%127s", mx->account.host, tmp);
if (n < 1)
{
mutt_debug(1, "NULL host in %s\n", path);
FREE(&mx->mbox);
return -1;
}
if (n > 1)
{
if (sscanf(tmp, ":%hu%127s", &(mx->account.port), tmp) >= 1)
mx->account.flags |= MUTT_ACCT_PORT;
if (sscanf(tmp, "/%s", tmp) == 1)
{
if (mutt_str_strncmp(tmp, "ssl", 3) == 0)
mx->account.flags |= MUTT_ACCT_SSL;
else
{
mutt_debug(1, "Unknown connection type in %s\n", path);
FREE(&mx->mbox);
return -1;
}
}
}
}
if ((mx->account.flags & MUTT_ACCT_SSL) && !(mx->account.flags & MUTT_ACCT_PORT))
mx->account.port = ImapsPort;
return 0;
}
/**
* imap_mxcmp - Compare mailbox names, giving priority to INBOX
* @param mx1 First mailbox name
* @param mx2 Second mailbox name
* @retval <0 First mailbox precedes Second mailbox
* @retval 0 Mailboxes are the same
* @retval >0 Second mailbox precedes First mailbox
*
* Like a normal sort function except that "INBOX" will be sorted to the
* beginning of the list.
*/
int imap_mxcmp(const char *mx1, const char *mx2)
{
char *b1 = NULL;
char *b2 = NULL;
int rc;
if (!mx1 || !*mx1)
mx1 = "INBOX";
if (!mx2 || !*mx2)
mx2 = "INBOX";
if ((mutt_str_strcasecmp(mx1, "INBOX") == 0) &&
(mutt_str_strcasecmp(mx2, "INBOX") == 0))
{
return 0;
}
b1 = mutt_mem_malloc(strlen(mx1) + 1);
b2 = mutt_mem_malloc(strlen(mx2) + 1);
imap_fix_path(NULL, mx1, b1, strlen(mx1) + 1);
imap_fix_path(NULL, mx2, b2, strlen(mx2) + 1);
rc = mutt_str_strcmp(b1, b2);
FREE(&b1);
FREE(&b2);
return rc;
}
/**
* imap_pretty_mailbox - Prettify an IMAP mailbox name
* @param path Mailbox name to be tidied
*
* Called by mutt_pretty_mailbox() to make IMAP paths look nice.
*/
void imap_pretty_mailbox(char *path)
{
struct ImapMbox home, target;
struct Url url;
char *delim = NULL;
int tlen;
int hlen = 0;
bool home_match = false;
if (imap_parse_path(path, &target) < 0)
return;
tlen = mutt_str_strlen(target.mbox);
/* check whether we can do '=' substitution */
if (mx_is_imap(Folder) && !imap_parse_path(Folder, &home))
{
hlen = mutt_str_strlen(home.mbox);
if (tlen && mutt_account_match(&home.account, &target.account) &&
(mutt_str_strncmp(home.mbox, target.mbox, hlen) == 0))
{
if (hlen == 0)
home_match = true;
else if (ImapDelimChars)
{
for (delim = ImapDelimChars; *delim != '\0'; delim++)
if (target.mbox[hlen] == *delim)
home_match = true;
}
}
FREE(&home.mbox);
}
/* do the '=' substitution */
if (home_match)
{
*path++ = '=';
/* copy remaining path, skipping delimiter */
if (hlen == 0)
hlen = -1;
memcpy(path, target.mbox + hlen + 1, tlen - hlen - 1);
path[tlen - hlen - 1] = '\0';
}
else
{
mutt_account_tourl(&target.account, &url);
url.path = target.mbox;
/* FIXME: That hard-coded constant is bogus. But we need the actual
* size of the buffer from mutt_pretty_mailbox. And these pretty
* operations usually shrink the result. Still... */
url_tostring(&url, path, 1024, 0);
}
FREE(&target.mbox);
}
/**
* imap_continue - display a message and ask the user if they want to go on
* @param msg Location of the error
* @param resp Message for user
* @retval num Result: #MUTT_YES, #MUTT_NO, #MUTT_ABORT
*/
int imap_continue(const char *msg, const char *resp)
{
imap_error(msg, resp);
return mutt_yesorno(_("Continue?"), 0);
}
/**
* imap_error - show an error and abort
* @param where Location of the error
* @param msg Message for user
*/
void imap_error(const char *where, const char *msg)
{
mutt_error("%s [%s]\n", where, msg);
}
/**
* imap_new_idata - Allocate and initialise a new ImapData structure
* @retval NULL Failure (no mem)
* @retval ptr New ImapData
*/
struct ImapData *imap_new_idata(void)
{
struct ImapData *idata = mutt_mem_calloc(1, sizeof(struct ImapData));
idata->cmdbuf = mutt_buffer_new();
idata->cmdslots = ImapPipelineDepth + 2;
idata->cmds = mutt_mem_calloc(idata->cmdslots, sizeof(*idata->cmds));
STAILQ_INIT(&idata->flags);
STAILQ_INIT(&idata->mboxcache);
return idata;
}
/**
* imap_free_idata - Release and clear storage in an ImapData structure
* @param idata Server data
*/
void imap_free_idata(struct ImapData **idata)
{
if (!idata)
return;
FREE(&(*idata)->capstr);
mutt_list_free(&(*idata)->flags);
imap_mboxcache_free(*idata);
mutt_buffer_free(&(*idata)->cmdbuf);
FREE(&(*idata)->buf);
mutt_bcache_close(&(*idata)->bcache);
FREE(&(*idata)->cmds);
FREE(idata);
}
/**
* imap_fix_path - Fix up the imap path
* @param idata Server data
* @param mailbox Mailbox path
* @param path Buffer for the result
* @param plen Length of buffer
* @retval ptr Fixed-up path
*
* This is necessary because the rest of neomutt assumes a hierarchy delimiter of
* '/', which is not necessarily true in IMAP. Additionally, the filesystem
* converts multiple hierarchy delimiters into a single one, ie "///" is equal
* to "/". IMAP servers are not required to do this.
* Moreover, IMAP servers may dislike the path ending with the delimiter.
*/
char *imap_fix_path(struct ImapData *idata, const char *mailbox, char *path, size_t plen)
{
int i = 0;
char delim = '\0';
if (idata)
delim = idata->delim;
while (mailbox && *mailbox && i < plen - 1)
{
if ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim))
{
/* use connection delimiter if known. Otherwise use user delimiter */
if (!idata)
delim = *mailbox;
while (*mailbox && ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) ||
(delim && *mailbox == delim)))
{
mailbox++;
}
path[i] = delim;
}
else
{
path[i] = *mailbox;
mailbox++;
}
i++;
}
if (i && path[--i] != delim)
i++;
path[i] = '\0';
return path;
}
/**
* imap_cachepath - Generate a cache path for a mailbox
* @param idata Server data
* @param mailbox Mailbox name
* @param dest Buffer to store cache path
* @param dlen Length of buffer
*/
void imap_cachepath(struct ImapData *idata, const char *mailbox, char *dest, size_t dlen)
{
char *s = NULL;
const char *p = mailbox;
for (s = dest; p && *p && dlen; dlen--)
{
if (*p == idata->delim)
{
*s = '/';
/* simple way to avoid collisions with UIDs */
if (*(p + 1) >= '0' && *(p + 1) <= '9')
{
if (--dlen)
*++s = '_';
}
}
else
*s = *p;
p++;
s++;
}
*s = '\0';
}
/**
* imap_get_literal_count - write number of bytes in an IMAP literal into bytes
* @param[in] buf Number as a string
* @param[out] bytes Resulting number
* @retval 0 Success
* @retval -1 Failure
*/
int imap_get_literal_count(const char *buf, unsigned int *bytes)
{
char *pc = NULL;
char *pn = NULL;
if (!buf || !(pc = strchr(buf, '{')))
return -1;
pc++;
pn = pc;
while (isdigit((unsigned char) *pc))
pc++;
*pc = '\0';
if (mutt_str_atoui(pn, bytes) < 0)
return -1;
return 0;
}
/**
* imap_get_qualifier - Get the qualifier from a tagged response
* @param buf Command string to process
* @retval ptr Start of the qualifier
*
* In a tagged response, skip tag and status for the qualifier message.
* Used by imap_copy_message for TRYCREATE
*/
char *imap_get_qualifier(char *buf)
{
char *s = buf;
/* skip tag */
s = imap_next_word(s);
/* skip OK/NO/BAD response */
s = imap_next_word(s);
return s;
}
/**
* imap_next_word - Find where the next IMAP word begins
* @param s Command string to process
* @retval ptr Next IMAP word
*/
char *imap_next_word(char *s)
{
int quoted = 0;
while (*s)
{
if (*s == '\\')
{
s++;
if (*s)
s++;
continue;
}
if (*s == '\"')
quoted = quoted ? 0 : 1;
if (!quoted && ISSPACE(*s))
break;
s++;
}
SKIPWS(s);
return s;
}
/**
* imap_qualify_path - Make an absolute IMAP folder target
* @param dest Buffer for the result
* @param len Length of buffer
* @param mx Imap mailbox
* @param path Path relative to the mailbox
*
* given ImapMbox and relative path.
*/
void imap_qualify_path(char *dest, size_t len, struct ImapMbox *mx, char *path)
{
struct Url url;
mutt_account_tourl(&mx->account, &url);
url.path = path;
url_tostring(&url, dest, len, 0);
}
/**
* imap_quote_string - quote string according to IMAP rules
* @param dest Buffer for the result
* @param dlen Length of the buffer
* @param src String to be quoted
*
* Surround string with quotes, escape " and \ with backslash
*/
void imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick)
{
const char *quote = "`\"\\";
if (!quote_backtick)
quote++;
char *pt = dest;
const char *s = src;
*pt++ = '"';
/* save room for trailing quote-char */
dlen -= 2;
for (; *s && dlen; s++)
{
if (strchr(quote, *s))
{
dlen -= 2;
if (dlen == 0)
break;
*pt++ = '\\';
*pt++ = *s;
}
else
{
*pt++ = *s;
dlen--;
}
}
*pt++ = '"';
*pt = '\0';
}
/**
* imap_unquote_string - equally stupid unquoting routine
* @param s String to be unquoted
*/
void imap_unquote_string(char *s)
{
char *d = s;
if (*s == '\"')
s++;
else
return;
while (*s)
{
if (*s == '\"')
{
*d = '\0';
return;
}
if (*s == '\\')
{
s++;
}
if (*s)
{
*d = *s;
d++;
s++;
}
}
*d = '\0';
}
/**
* imap_munge_mbox_name - Quote awkward characters in a mailbox name
* @param idata Server data
* @param dest Buffer to store safe mailbox name
* @param dlen Length of buffer
* @param src Mailbox name
*/
void imap_munge_mbox_name(struct ImapData *idata, char *dest, size_t dlen, const char *src)
{
char *buf = mutt_str_strdup(src);
imap_utf_encode(idata, &buf);
imap_quote_string(dest, dlen, buf, false);
FREE(&buf);
}
/**
* imap_unmunge_mbox_name - Remove quoting from a mailbox name
* @param idata Server data
* @param s Mailbox name
*
* The string will be altered in-place.
*/
void imap_unmunge_mbox_name(struct ImapData *idata, char *s)
{
imap_unquote_string(s);
char *buf = mutt_str_strdup(s);
if (buf)
{
imap_utf_decode(idata, &buf);
strncpy(s, buf, strlen(s));
}
FREE(&buf);
}
/**
* imap_keepalive - poll the current folder to keep the connection alive
*/
void imap_keepalive(void)
{
struct Connection *conn = NULL;
struct ImapData *idata = NULL;
time_t now = time(NULL);
TAILQ_FOREACH(conn, mutt_socket_head(), entries)
{
if (conn->account.type == MUTT_ACCT_TYPE_IMAP)
{
idata = conn->data;
if (idata->state >= IMAP_AUTHENTICATED && now >= idata->lastread + ImapKeepalive)
{
imap_check(idata, 1);
}
}
}
}
/**
* imap_wait_keepalive - Wait for a process to change state
* @param pid Process ID to listen to
* @retval num 'wstatus' from waitpid()
*/
int imap_wait_keepalive(pid_t pid)
{
struct sigaction oldalrm;
struct sigaction act;
sigset_t oldmask;
int rc;
bool imap_passive = ImapPassive;
ImapPassive = true;
OptKeepQuiet = true;
sigprocmask(SIG_SETMASK, NULL, &oldmask);
sigemptyset(&act.sa_mask);
act.sa_handler = mutt_sig_empty_handler;
#ifdef SA_INTERRUPT
act.sa_flags = SA_INTERRUPT;
#else
act.sa_flags = 0;
#endif
sigaction(SIGALRM, &act, &oldalrm);
alarm(ImapKeepalive);
while (waitpid(pid, &rc, 0) < 0 && errno == EINTR)
{
alarm(0); /* cancel a possibly pending alarm */
imap_keepalive();
alarm(ImapKeepalive);
}
alarm(0); /* cancel a possibly pending alarm */
sigaction(SIGALRM, &oldalrm, NULL);
sigprocmask(SIG_SETMASK, &oldmask, NULL);
OptKeepQuiet = false;
if (!imap_passive)
ImapPassive = false;
return rc;
}
/**
* imap_allow_reopen - Allow re-opening a folder upon expunge
* @param ctx Context
*/
void imap_allow_reopen(struct Context *ctx)
{
struct ImapData *idata = NULL;
if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP)
return;
idata = ctx->data;
if (idata->ctx == ctx)
idata->reopen |= IMAP_REOPEN_ALLOW;
}
/**
* imap_disallow_reopen - Disallow re-opening a folder upon expunge
* @param ctx Context
*/
void imap_disallow_reopen(struct Context *ctx)
{
struct ImapData *idata = NULL;
if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP)
return;
idata = ctx->data;
if (idata->ctx == ctx)
idata->reopen &= ~IMAP_REOPEN_ALLOW;
}
/**
* imap_account_match - Compare two Accounts
* @param a1 First Account
* @param a2 Second Account
* @retval true Accounts match
*/
int imap_account_match(const struct Account *a1, const struct Account *a2)
{
struct ImapData *a1_idata = imap_conn_find(a1, MUTT_IMAP_CONN_NONEW);
struct ImapData *a2_idata = imap_conn_find(a2, MUTT_IMAP_CONN_NONEW);
const struct Account *a1_canon = a1_idata == NULL ? a1 : &a1_idata->conn->account;
const struct Account *a2_canon = a2_idata == NULL ? a2 : &a2_idata->conn->account;
return mutt_account_match(a1_canon, a2_canon);
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_249_0 |
crossvul-cpp_data_good_1566_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
bool allowed_problem_dir(const char *dir_name)
{
if (!dir_is_in_dump_location(dir_name))
{
error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location);
return false;
}
/* We cannot test correct permissions yet because we still need to chown
* dump directories before reporting and Chowing changes the file owner to
* the reporter, which causes this test to fail and prevents users from
* getting problem data after reporting it.
*
* Fortunately, libreport has been hardened against hard link and symbolic
* link attacks and refuses to work with such files, so this test isn't
* really necessary, however, we will use it once we get rid of the
* chowning files.
*
* abrt-server refuses to run post-create on directories that have
* incorrect owner (not "root:(abrt|root)"), incorrect permissions (other
* bits are not 0) and are complete (post-create finished). So, there is no
* way to run security sensitive event scripts (post-create) on crafted
* problem directories.
*/
#if 0
if (!dir_has_correct_permissions(dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name);
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
char *problem_id = NULL;
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
if (allowed_new_user_problem_entry(caller_uid, key, value) == false)
{
*error = xasprintf("You are not allowed to create element '%s' containing '%s'", key, value);
goto finito;
}
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
finito:
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
int dir_fd = dd_openfd(problem_id);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
return NULL;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
close(dir_fd);
return NULL;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
close(dir_fd);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (!allowed_problem_dir(problem_id))
{
return_InvalidProblemDir_error(invocation, problem_id);
return;
}
if (!str_is_correct_filename(element))
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
if (!allowed_problem_dir(problem_id))
{
return_InvalidProblemDir_error(invocation, problem_id);
return;
}
if (!str_is_correct_filename(element))
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
int dir_fd = dd_openfd(dir_name);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", dir_name);
return_InvalidProblemDir_error(invocation, dir_name);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
close(dir_fd);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
close(dir_fd);
continue;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0);
if (dd)
{
if (dd_delete(dd) != 0)
{
error_msg("Failed to delete problem directory '%s'", dir_name);
dd_close(dd);
}
}
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (!str_is_correct_filename(element))
{
log_notice("'%s' is not a valid element name", element);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1566_0 |
crossvul-cpp_data_bad_440_0 | #include "first.h"
#include "base.h"
#include "log.h"
#include "buffer.h"
#include "plugin.h"
#include <stdlib.h>
#include <string.h>
/* plugin config for all request/connections */
typedef struct {
array *alias;
} plugin_config;
typedef struct {
PLUGIN_DATA;
plugin_config **config_storage;
plugin_config conf;
} plugin_data;
/* init the plugin data */
INIT_FUNC(mod_alias_init) {
plugin_data *p;
p = calloc(1, sizeof(*p));
return p;
}
/* detroy the plugin data */
FREE_FUNC(mod_alias_free) {
plugin_data *p = p_d;
if (!p) return HANDLER_GO_ON;
if (p->config_storage) {
size_t i;
for (i = 0; i < srv->config_context->used; i++) {
plugin_config *s = p->config_storage[i];
if (NULL == s) continue;
array_free(s->alias);
free(s);
}
free(p->config_storage);
}
free(p);
return HANDLER_GO_ON;
}
/* handle plugin config and check values */
SETDEFAULTS_FUNC(mod_alias_set_defaults) {
plugin_data *p = p_d;
size_t i = 0;
config_values_t cv[] = {
{ "alias.url", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
{ NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
};
if (!p) return HANDLER_ERROR;
p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
for (i = 0; i < srv->config_context->used; i++) {
data_config const* config = (data_config const*)srv->config_context->data[i];
plugin_config *s;
s = calloc(1, sizeof(plugin_config));
s->alias = array_init();
cv[0].destination = s->alias;
p->config_storage[i] = s;
if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
return HANDLER_ERROR;
}
if (!array_is_kvstring(s->alias)) {
log_error_write(srv, __FILE__, __LINE__, "s",
"unexpected value for alias.url; expected list of \"urlpath\" => \"filepath\"");
return HANDLER_ERROR;
}
if (s->alias->used >= 2) {
const array *a = s->alias;
size_t j, k;
for (j = 0; j < a->used; j ++) {
const buffer *prefix = a->data[a->sorted[j]]->key;
for (k = j + 1; k < a->used; k ++) {
const buffer *key = a->data[a->sorted[k]]->key;
if (buffer_string_length(key) < buffer_string_length(prefix)) {
break;
}
if (memcmp(key->ptr, prefix->ptr, buffer_string_length(prefix)) != 0) {
break;
}
/* ok, they have same prefix. check position */
if (a->sorted[j] < a->sorted[k]) {
log_error_write(srv, __FILE__, __LINE__, "SBSBS",
"url.alias: `", key, "' will never match as `", prefix, "' matched first");
return HANDLER_ERROR;
}
}
}
}
}
return HANDLER_GO_ON;
}
#define PATCH(x) \
p->conf.x = s->x;
static int mod_alias_patch_connection(server *srv, connection *con, plugin_data *p) {
size_t i, j;
plugin_config *s = p->config_storage[0];
PATCH(alias);
/* skip the first, the global context */
for (i = 1; i < srv->config_context->used; i++) {
data_config *dc = (data_config *)srv->config_context->data[i];
s = p->config_storage[i];
/* condition didn't match */
if (!config_check_cond(srv, con, dc)) continue;
/* merge config */
for (j = 0; j < dc->value->used; j++) {
data_unset *du = dc->value->data[j];
if (buffer_is_equal_string(du->key, CONST_STR_LEN("alias.url"))) {
PATCH(alias);
}
}
}
return 0;
}
#undef PATCH
PHYSICALPATH_FUNC(mod_alias_physical_handler) {
plugin_data *p = p_d;
int uri_len, basedir_len;
char *uri_ptr;
size_t k;
if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;
mod_alias_patch_connection(srv, con, p);
/* not to include the tailing slash */
basedir_len = buffer_string_length(con->physical.basedir);
if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len;
uri_len = buffer_string_length(con->physical.path) - basedir_len;
uri_ptr = con->physical.path->ptr + basedir_len;
for (k = 0; k < p->conf.alias->used; k++) {
data_string *ds = (data_string *)p->conf.alias->data[k];
int alias_len = buffer_string_length(ds->key);
if (alias_len > uri_len) continue;
if (buffer_is_empty(ds->key)) continue;
if (0 == (con->conf.force_lowercase_filenames ?
strncasecmp(uri_ptr, ds->key->ptr, alias_len) :
strncmp(uri_ptr, ds->key->ptr, alias_len))) {
/* matched */
buffer_copy_buffer(con->physical.basedir, ds->value);
buffer_copy_buffer(srv->tmp_buf, ds->value);
buffer_append_string(srv->tmp_buf, uri_ptr + alias_len);
buffer_copy_buffer(con->physical.path, srv->tmp_buf);
return HANDLER_GO_ON;
}
}
/* not found */
return HANDLER_GO_ON;
}
/* this function is called at dlopen() time and inits the callbacks */
int mod_alias_plugin_init(plugin *p);
int mod_alias_plugin_init(plugin *p) {
p->version = LIGHTTPD_VERSION_ID;
p->name = buffer_init_string("alias");
p->init = mod_alias_init;
p->handle_physical= mod_alias_physical_handler;
p->set_defaults = mod_alias_set_defaults;
p->cleanup = mod_alias_free;
p->data = NULL;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_440_0 |
crossvul-cpp_data_good_1520_1 | /*-
* Copyright (c) 2003-2007 Tim Kientzle
* 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
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpio_platform.h"
__FBSDID("$FreeBSD: src/usr.bin/cpio/cpio.c,v 1.15 2008/12/06 07:30:40 kientzle Exp $");
#include <sys/types.h>
#include <archive.h>
#include <archive_entry.h>
#ifdef HAVE_SYS_MKDEV_H
#include <sys/mkdev.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdio.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include "cpio.h"
#include "err.h"
#include "line_reader.h"
#include "passphrase.h"
/* Fixed size of uname/gname caches. */
#define name_cache_size 101
#ifndef O_BINARY
#define O_BINARY 0
#endif
struct name_cache {
int probes;
int hits;
size_t size;
struct {
id_t id;
char *name;
} cache[name_cache_size];
};
static int extract_data(struct archive *, struct archive *);
const char * cpio_i64toa(int64_t);
static const char *cpio_rename(const char *name);
static int entry_to_archive(struct cpio *, struct archive_entry *);
static int file_to_archive(struct cpio *, const char *);
static void free_cache(struct name_cache *cache);
static void list_item_verbose(struct cpio *, struct archive_entry *);
static void long_help(void);
static const char *lookup_gname(struct cpio *, gid_t gid);
static int lookup_gname_helper(struct cpio *,
const char **name, id_t gid);
static const char *lookup_uname(struct cpio *, uid_t uid);
static int lookup_uname_helper(struct cpio *,
const char **name, id_t uid);
static void mode_in(struct cpio *);
static void mode_list(struct cpio *);
static void mode_out(struct cpio *);
static void mode_pass(struct cpio *, const char *);
static const char *remove_leading_slash(const char *);
static int restore_time(struct cpio *, struct archive_entry *,
const char *, int fd);
static void usage(void);
static void version(void);
static const char * passphrase_callback(struct archive *, void *);
static void passphrase_free(char *);
int
main(int argc, char *argv[])
{
static char buff[16384];
struct cpio _cpio; /* Allocated on stack. */
struct cpio *cpio;
const char *errmsg;
int uid, gid;
int opt;
cpio = &_cpio;
memset(cpio, 0, sizeof(*cpio));
cpio->buff = buff;
cpio->buff_size = sizeof(buff);
#if defined(HAVE_SIGACTION) && defined(SIGPIPE)
{ /* Ignore SIGPIPE signals. */
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, NULL);
}
#endif
/* Set lafe_progname before calling lafe_warnc. */
lafe_setprogname(*argv, "bsdcpio");
#if HAVE_SETLOCALE
if (setlocale(LC_ALL, "") == NULL)
lafe_warnc(0, "Failed to set default locale");
#endif
cpio->uid_override = -1;
cpio->gid_override = -1;
cpio->argv = argv;
cpio->argc = argc;
cpio->mode = '\0';
cpio->verbose = 0;
cpio->compress = '\0';
cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
#if !defined(_WIN32) && !defined(__CYGWIN__)
if (geteuid() == 0)
cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
#endif
cpio->bytes_per_block = 512;
cpio->filename = NULL;
cpio->matching = archive_match_new();
if (cpio->matching == NULL)
lafe_errc(1, 0, "Out of memory");
while ((opt = cpio_getopt(cpio)) != -1) {
switch (opt) {
case '0': /* GNU convention: --null, -0 */
cpio->option_null = 1;
break;
case 'A': /* NetBSD/OpenBSD */
cpio->option_append = 1;
break;
case 'a': /* POSIX 1997 */
cpio->option_atime_restore = 1;
break;
case 'B': /* POSIX 1997 */
cpio->bytes_per_block = 5120;
break;
case OPTION_B64ENCODE:
cpio->add_filter = opt;
break;
case 'C': /* NetBSD/OpenBSD */
cpio->bytes_per_block = atoi(cpio->argument);
if (cpio->bytes_per_block <= 0)
lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
break;
case 'c': /* POSIX 1997 */
cpio->format = "odc";
break;
case 'd': /* POSIX 1997 */
cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
break;
case 'E': /* NetBSD/OpenBSD */
if (archive_match_include_pattern_from_file(
cpio->matching, cpio->argument,
cpio->option_null) != ARCHIVE_OK)
lafe_errc(1, 0, "Error : %s",
archive_error_string(cpio->matching));
break;
case 'F': /* NetBSD/OpenBSD/GNU cpio */
cpio->filename = cpio->argument;
break;
case 'f': /* POSIX 1997 */
if (archive_match_exclude_pattern(cpio->matching,
cpio->argument) != ARCHIVE_OK)
lafe_errc(1, 0, "Error : %s",
archive_error_string(cpio->matching));
break;
case OPTION_GRZIP:
cpio->compress = opt;
break;
case 'H': /* GNU cpio (also --format) */
cpio->format = cpio->argument;
break;
case 'h':
long_help();
break;
case 'I': /* NetBSD/OpenBSD */
cpio->filename = cpio->argument;
break;
case 'i': /* POSIX 1997 */
if (cpio->mode != '\0')
lafe_errc(1, 0,
"Cannot use both -i and -%c", cpio->mode);
cpio->mode = opt;
break;
case 'J': /* GNU tar, others */
cpio->compress = opt;
break;
case 'j': /* GNU tar, others */
cpio->compress = opt;
break;
case OPTION_INSECURE:
cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
break;
case 'L': /* GNU cpio */
cpio->option_follow_links = 1;
break;
case 'l': /* POSIX 1997 */
cpio->option_link = 1;
break;
case OPTION_LRZIP:
case OPTION_LZ4:
case OPTION_LZMA: /* GNU tar, others */
case OPTION_LZOP: /* GNU tar, others */
cpio->compress = opt;
break;
case 'm': /* POSIX 1997 */
cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
break;
case 'n': /* GNU cpio */
cpio->option_numeric_uid_gid = 1;
break;
case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
break;
case 'O': /* GNU cpio */
cpio->filename = cpio->argument;
break;
case 'o': /* POSIX 1997 */
if (cpio->mode != '\0')
lafe_errc(1, 0,
"Cannot use both -o and -%c", cpio->mode);
cpio->mode = opt;
break;
case 'p': /* POSIX 1997 */
if (cpio->mode != '\0')
lafe_errc(1, 0,
"Cannot use both -p and -%c", cpio->mode);
cpio->mode = opt;
cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
break;
case OPTION_PASSPHRASE:
cpio->passphrase = cpio->argument;
break;
case OPTION_PRESERVE_OWNER:
cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
break;
case OPTION_QUIET: /* GNU cpio */
cpio->quiet = 1;
break;
case 'R': /* GNU cpio, also --owner */
/* TODO: owner_parse should return uname/gname
* also; use that to set [ug]name_override. */
errmsg = owner_parse(cpio->argument, &uid, &gid);
if (errmsg) {
lafe_warnc(-1, "%s", errmsg);
usage();
}
if (uid != -1) {
cpio->uid_override = uid;
cpio->uname_override = NULL;
}
if (gid != -1) {
cpio->gid_override = gid;
cpio->gname_override = NULL;
}
break;
case 'r': /* POSIX 1997 */
cpio->option_rename = 1;
break;
case 't': /* POSIX 1997 */
cpio->option_list = 1;
break;
case 'u': /* POSIX 1997 */
cpio->extract_flags
&= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
break;
case OPTION_UUENCODE:
cpio->add_filter = opt;
break;
case 'v': /* POSIX 1997 */
cpio->verbose++;
break;
case 'V': /* GNU cpio */
cpio->dot++;
break;
case OPTION_VERSION: /* GNU convention */
version();
break;
#if 0
/*
* cpio_getopt() handles -W specially, so it's not
* available here.
*/
case 'W': /* Obscure, but useful GNU convention. */
break;
#endif
case 'y': /* tar convention */
cpio->compress = opt;
break;
case 'Z': /* tar convention */
cpio->compress = opt;
break;
case 'z': /* tar convention */
cpio->compress = opt;
break;
default:
usage();
}
}
/*
* Sanity-check args, error out on nonsensical combinations.
*/
/* -t implies -i if no mode was specified. */
if (cpio->option_list && cpio->mode == '\0')
cpio->mode = 'i';
/* -t requires -i */
if (cpio->option_list && cpio->mode != 'i')
lafe_errc(1, 0, "Option -t requires -i");
/* -n requires -it */
if (cpio->option_numeric_uid_gid && !cpio->option_list)
lafe_errc(1, 0, "Option -n requires -it");
/* Can only specify format when writing */
if (cpio->format != NULL && cpio->mode != 'o')
lafe_errc(1, 0, "Option --format requires -o");
/* -l requires -p */
if (cpio->option_link && cpio->mode != 'p')
lafe_errc(1, 0, "Option -l requires -p");
/* -v overrides -V */
if (cpio->dot && cpio->verbose)
cpio->dot = 0;
/* TODO: Flag other nonsensical combinations. */
switch (cpio->mode) {
case 'o':
/* TODO: Implement old binary format in libarchive,
use that here. */
if (cpio->format == NULL)
cpio->format = "odc"; /* Default format */
mode_out(cpio);
break;
case 'i':
while (*cpio->argv != NULL) {
if (archive_match_include_pattern(cpio->matching,
*cpio->argv) != ARCHIVE_OK)
lafe_errc(1, 0, "Error : %s",
archive_error_string(cpio->matching));
--cpio->argc;
++cpio->argv;
}
if (cpio->option_list)
mode_list(cpio);
else
mode_in(cpio);
break;
case 'p':
if (*cpio->argv == NULL || **cpio->argv == '\0')
lafe_errc(1, 0,
"-p mode requires a target directory");
mode_pass(cpio, *cpio->argv);
break;
default:
lafe_errc(1, 0,
"Must specify at least one of -i, -o, or -p");
}
archive_match_free(cpio->matching);
free_cache(cpio->gname_cache);
free_cache(cpio->uname_cache);
free(cpio->destdir);
passphrase_free(cpio->ppbuff);
return (cpio->return_value);
}
static void
usage(void)
{
const char *p;
p = lafe_getprogname();
fprintf(stderr, "Brief Usage:\n");
fprintf(stderr, " List: %s -it < archive\n", p);
fprintf(stderr, " Extract: %s -i < archive\n", p);
fprintf(stderr, " Create: %s -o < filenames > archive\n", p);
fprintf(stderr, " Help: %s --help\n", p);
exit(1);
}
static const char *long_help_msg =
"First option must be a mode specifier:\n"
" -i Input -o Output -p Pass\n"
"Common Options:\n"
" -v Verbose filenames -V one dot per file\n"
"Create: %p -o [options] < [list of files] > [archive]\n"
" -J,-y,-z,--lzma Compress archive with xz/bzip2/gzip/lzma\n"
" --format {odc|newc|ustar} Select archive format\n"
"List: %p -it < [archive]\n"
"Extract: %p -i [options] < [archive]\n";
/*
* Note that the word 'bsdcpio' will always appear in the first line
* of output.
*
* In particular, /bin/sh scripts that need to test for the presence
* of bsdcpio can use the following template:
*
* if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
* echo bsdcpio; else echo not bsdcpio; fi
*/
static void
long_help(void)
{
const char *prog;
const char *p;
prog = lafe_getprogname();
fflush(stderr);
p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
printf("%s%s: manipulate archive files\n", prog, p);
for (p = long_help_msg; *p != '\0'; p++) {
if (*p == '%') {
if (p[1] == 'p') {
fputs(prog, stdout);
p++;
} else
putchar('%');
} else
putchar(*p);
}
version();
}
static void
version(void)
{
fprintf(stdout,"bsdcpio %s -- %s\n",
BSDCPIO_VERSION_STRING,
archive_version_details());
exit(0);
}
static void
mode_out(struct cpio *cpio)
{
struct archive_entry *entry, *spare;
struct lafe_line_reader *lr;
const char *p;
int r;
if (cpio->option_append)
lafe_errc(1, 0, "Append mode not yet supported.");
cpio->archive_read_disk = archive_read_disk_new();
if (cpio->archive_read_disk == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
if (cpio->option_follow_links)
archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
else
archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
cpio->archive = archive_write_new();
if (cpio->archive == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
switch (cpio->compress) {
case OPTION_GRZIP:
r = archive_write_add_filter_grzip(cpio->archive);
break;
case 'J':
r = archive_write_add_filter_xz(cpio->archive);
break;
case OPTION_LRZIP:
r = archive_write_add_filter_lrzip(cpio->archive);
break;
case OPTION_LZ4:
r = archive_write_add_filter_lz4(cpio->archive);
break;
case OPTION_LZMA:
r = archive_write_add_filter_lzma(cpio->archive);
break;
case OPTION_LZOP:
r = archive_write_add_filter_lzop(cpio->archive);
break;
case 'j': case 'y':
r = archive_write_add_filter_bzip2(cpio->archive);
break;
case 'z':
r = archive_write_add_filter_gzip(cpio->archive);
break;
case 'Z':
r = archive_write_add_filter_compress(cpio->archive);
break;
default:
r = archive_write_add_filter_none(cpio->archive);
break;
}
if (r < ARCHIVE_WARN)
lafe_errc(1, 0, "Requested compression not available");
switch (cpio->add_filter) {
case 0:
r = ARCHIVE_OK;
break;
case OPTION_B64ENCODE:
r = archive_write_add_filter_b64encode(cpio->archive);
break;
case OPTION_UUENCODE:
r = archive_write_add_filter_uuencode(cpio->archive);
break;
}
if (r < ARCHIVE_WARN)
lafe_errc(1, 0, "Requested filter not available");
r = archive_write_set_format_by_name(cpio->archive, cpio->format);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
cpio->linkresolver = archive_entry_linkresolver_new();
archive_entry_linkresolver_set_strategy(cpio->linkresolver,
archive_format(cpio->archive));
if (cpio->passphrase != NULL)
r = archive_write_set_passphrase(cpio->archive,
cpio->passphrase);
else
r = archive_write_set_passphrase_callback(cpio->archive, cpio,
&passphrase_callback);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
/*
* The main loop: Copy each file into the output archive.
*/
r = archive_write_open_filename(cpio->archive, cpio->filename);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
lr = lafe_line_reader("-", cpio->option_null);
while ((p = lafe_line_reader_next(lr)) != NULL)
file_to_archive(cpio, p);
lafe_line_reader_free(lr);
/*
* The hardlink detection may have queued up a couple of entries
* that can now be flushed.
*/
entry = NULL;
archive_entry_linkify(cpio->linkresolver, &entry, &spare);
while (entry != NULL) {
entry_to_archive(cpio, entry);
archive_entry_free(entry);
entry = NULL;
archive_entry_linkify(cpio->linkresolver, &entry, &spare);
}
r = archive_write_close(cpio->archive);
if (cpio->dot)
fprintf(stderr, "\n");
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
if (!cpio->quiet) {
int64_t blocks =
(archive_filter_bytes(cpio->archive, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_write_free(cpio->archive);
}
static const char *
remove_leading_slash(const char *p)
{
const char *rp;
/* Remove leading "//./" or "//?/" or "//?/UNC/"
* (absolute path prefixes used by Windows API) */
if ((p[0] == '/' || p[0] == '\\') &&
(p[1] == '/' || p[1] == '\\') &&
(p[2] == '.' || p[2] == '?') &&
(p[3] == '/' || p[3] == '\\'))
{
if (p[2] == '?' &&
(p[4] == 'U' || p[4] == 'u') &&
(p[5] == 'N' || p[5] == 'n') &&
(p[6] == 'C' || p[6] == 'c') &&
(p[7] == '/' || p[7] == '\\'))
p += 8;
else
p += 4;
}
do {
rp = p;
/* Remove leading drive letter from archives created
* on Windows. */
if (((p[0] >= 'a' && p[0] <= 'z') ||
(p[0] >= 'A' && p[0] <= 'Z')) &&
p[1] == ':') {
p += 2;
}
/* Remove leading "/../", "//", etc. */
while (p[0] == '/' || p[0] == '\\') {
if (p[1] == '.' && p[2] == '.' &&
(p[3] == '/' || p[3] == '\\')) {
p += 3; /* Remove "/..", leave "/"
* for next pass. */
} else
p += 1; /* Remove "/". */
}
} while (rp != p);
return (p);
}
/*
* This is used by both out mode (to copy objects from disk into
* an archive) and pass mode (to copy objects from disk to
* an archive_write_disk "archive").
*/
static int
file_to_archive(struct cpio *cpio, const char *srcpath)
{
const char *destpath;
struct archive_entry *entry, *spare;
size_t len;
int r;
/*
* Create an archive_entry describing the source file.
*
*/
entry = archive_entry_new();
if (entry == NULL)
lafe_errc(1, 0, "Couldn't allocate entry");
archive_entry_copy_sourcepath(entry, srcpath);
r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
entry, -1, NULL);
if (r < ARCHIVE_FAILED)
lafe_errc(1, 0, "%s",
archive_error_string(cpio->archive_read_disk));
if (r < ARCHIVE_OK)
lafe_warnc(0, "%s",
archive_error_string(cpio->archive_read_disk));
if (r <= ARCHIVE_FAILED) {
cpio->return_value = 1;
return (r);
}
if (cpio->uid_override >= 0) {
archive_entry_set_uid(entry, cpio->uid_override);
archive_entry_set_uname(entry, cpio->uname_override);
}
if (cpio->gid_override >= 0) {
archive_entry_set_gid(entry, cpio->gid_override);
archive_entry_set_gname(entry, cpio->gname_override);
}
/*
* Generate a destination path for this entry.
* "destination path" is the name to which it will be copied in
* pass mode or the name that will go into the archive in
* output mode.
*/
destpath = srcpath;
if (cpio->destdir) {
len = strlen(cpio->destdir) + strlen(srcpath) + 8;
if (len >= cpio->pass_destpath_alloc) {
while (len >= cpio->pass_destpath_alloc) {
cpio->pass_destpath_alloc += 512;
cpio->pass_destpath_alloc *= 2;
}
free(cpio->pass_destpath);
cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
if (cpio->pass_destpath == NULL)
lafe_errc(1, ENOMEM,
"Can't allocate path buffer");
}
strcpy(cpio->pass_destpath, cpio->destdir);
strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
destpath = cpio->pass_destpath;
}
if (cpio->option_rename)
destpath = cpio_rename(destpath);
if (destpath == NULL)
return (0);
archive_entry_copy_pathname(entry, destpath);
/*
* If we're trying to preserve hardlinks, match them here.
*/
spare = NULL;
if (cpio->linkresolver != NULL
&& archive_entry_filetype(entry) != AE_IFDIR) {
archive_entry_linkify(cpio->linkresolver, &entry, &spare);
}
if (entry != NULL) {
r = entry_to_archive(cpio, entry);
archive_entry_free(entry);
if (spare != NULL) {
if (r == 0)
r = entry_to_archive(cpio, spare);
archive_entry_free(spare);
}
}
return (r);
}
static int
entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
{
const char *destpath = archive_entry_pathname(entry);
const char *srcpath = archive_entry_sourcepath(entry);
int fd = -1;
ssize_t bytes_read;
int r;
/* Print out the destination name to the user. */
if (cpio->verbose)
fprintf(stderr,"%s", destpath);
if (cpio->dot)
fprintf(stderr, ".");
/*
* Option_link only makes sense in pass mode and for
* regular files. Also note: if a link operation fails
* because of cross-device restrictions, we'll fall back
* to copy mode for that entry.
*
* TODO: Test other cpio implementations to see if they
* hard-link anything other than regular files here.
*/
if (cpio->option_link
&& archive_entry_filetype(entry) == AE_IFREG)
{
struct archive_entry *t;
/* Save the original entry in case we need it later. */
t = archive_entry_clone(entry);
if (t == NULL)
lafe_errc(1, ENOMEM, "Can't create link");
/* Note: link(2) doesn't create parent directories,
* so we use archive_write_header() instead as a
* convenience. */
archive_entry_set_hardlink(t, srcpath);
/* This is a straight link that carries no data. */
archive_entry_set_size(t, 0);
r = archive_write_header(cpio->archive, t);
archive_entry_free(t);
if (r != ARCHIVE_OK)
lafe_warnc(archive_errno(cpio->archive),
"%s", archive_error_string(cpio->archive));
if (r == ARCHIVE_FATAL)
exit(1);
#ifdef EXDEV
if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
/* Cross-device link: Just fall through and use
* the original entry to copy the file over. */
lafe_warnc(0, "Copying file instead");
} else
#endif
return (0);
}
/*
* Make sure we can open the file (if necessary) before
* trying to write the header.
*/
if (archive_entry_filetype(entry) == AE_IFREG) {
if (archive_entry_size(entry) > 0) {
fd = open(srcpath, O_RDONLY | O_BINARY);
if (fd < 0) {
lafe_warnc(errno,
"%s: could not open file", srcpath);
goto cleanup;
}
}
} else {
archive_entry_set_size(entry, 0);
}
r = archive_write_header(cpio->archive, entry);
if (r != ARCHIVE_OK)
lafe_warnc(archive_errno(cpio->archive),
"%s: %s",
srcpath,
archive_error_string(cpio->archive));
if (r == ARCHIVE_FATAL)
exit(1);
if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
while (bytes_read > 0) {
ssize_t bytes_write;
bytes_write = archive_write_data(cpio->archive,
cpio->buff, bytes_read);
if (bytes_write < 0)
lafe_errc(1, archive_errno(cpio->archive),
"%s", archive_error_string(cpio->archive));
if (bytes_write < bytes_read) {
lafe_warnc(0,
"Truncated write; file may have "
"grown while being archived.");
}
bytes_read = read(fd, cpio->buff,
(unsigned)cpio->buff_size);
}
}
fd = restore_time(cpio, entry, srcpath, fd);
cleanup:
if (cpio->verbose)
fprintf(stderr,"\n");
if (fd >= 0)
close(fd);
return (0);
}
static int
restore_time(struct cpio *cpio, struct archive_entry *entry,
const char *name, int fd)
{
#ifndef HAVE_UTIMES
static int warned = 0;
(void)cpio; /* UNUSED */
(void)entry; /* UNUSED */
(void)name; /* UNUSED */
if (!warned)
lafe_warnc(0, "Can't restore access times on this platform");
warned = 1;
return (fd);
#else
#if defined(_WIN32) && !defined(__CYGWIN__)
struct __timeval times[2];
#else
struct timeval times[2];
#endif
if (!cpio->option_atime_restore)
return (fd);
times[1].tv_sec = archive_entry_mtime(entry);
times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
times[0].tv_sec = archive_entry_atime(entry);
times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
#if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
if (fd >= 0 && futimes(fd, times) == 0)
return (fd);
#endif
/*
* Some platform cannot restore access times if the file descriptor
* is still opened.
*/
if (fd >= 0) {
close(fd);
fd = -1;
}
#ifdef HAVE_LUTIMES
if (lutimes(name, times) != 0)
#else
if ((AE_IFLNK != archive_entry_filetype(entry))
&& utimes(name, times) != 0)
#endif
lafe_warnc(errno, "Can't update time for %s", name);
#endif
return (fd);
}
static void
mode_in(struct cpio *cpio)
{
struct archive *a;
struct archive_entry *entry;
struct archive *ext;
const char *destpath;
int r;
ext = archive_write_disk_new();
if (ext == NULL)
lafe_errc(1, 0, "Couldn't allocate restore object");
r = archive_write_disk_set_options(ext, cpio->extract_flags);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(ext));
a = archive_read_new();
if (a == NULL)
lafe_errc(1, 0, "Couldn't allocate archive object");
archive_read_support_filter_all(a);
archive_read_support_format_all(a);
if (cpio->passphrase != NULL)
r = archive_read_add_passphrase(a, cpio->passphrase);
else
r = archive_read_set_passphrase_callback(a, cpio,
&passphrase_callback);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
if (archive_read_open_filename(a, cpio->filename,
cpio->bytes_per_block))
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
if (r != ARCHIVE_OK) {
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
}
if (archive_match_path_excluded(cpio->matching, entry))
continue;
if (cpio->option_rename) {
destpath = cpio_rename(archive_entry_pathname(entry));
archive_entry_set_pathname(entry, destpath);
} else
destpath = archive_entry_pathname(entry);
if (destpath == NULL)
continue;
if (cpio->verbose)
fprintf(stderr, "%s\n", destpath);
if (cpio->dot)
fprintf(stderr, ".");
if (cpio->uid_override >= 0)
archive_entry_set_uid(entry, cpio->uid_override);
if (cpio->gid_override >= 0)
archive_entry_set_gid(entry, cpio->gid_override);
r = archive_write_header(ext, entry);
if (r != ARCHIVE_OK) {
fprintf(stderr, "%s: %s\n",
archive_entry_pathname(entry),
archive_error_string(ext));
} else if (!archive_entry_size_is_set(entry)
|| archive_entry_size(entry) > 0) {
r = extract_data(a, ext);
if (r != ARCHIVE_OK)
cpio->return_value = 1;
}
}
r = archive_read_close(a);
if (cpio->dot)
fprintf(stderr, "\n");
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
r = archive_write_close(ext);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(ext));
if (!cpio->quiet) {
int64_t blocks = (archive_filter_bytes(a, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_read_free(a);
archive_write_free(ext);
exit(cpio->return_value);
}
/*
* Exits if there's a fatal error. Returns ARCHIVE_OK
* if everything is kosher.
*/
static int
extract_data(struct archive *ar, struct archive *aw)
{
int r;
size_t size;
const void *block;
int64_t offset;
for (;;) {
r = archive_read_data_block(ar, &block, &size, &offset);
if (r == ARCHIVE_EOF)
return (ARCHIVE_OK);
if (r != ARCHIVE_OK) {
lafe_warnc(archive_errno(ar),
"%s", archive_error_string(ar));
exit(1);
}
r = (int)archive_write_data_block(aw, block, size, offset);
if (r != ARCHIVE_OK) {
lafe_warnc(archive_errno(aw),
"%s", archive_error_string(aw));
return (r);
}
}
}
static void
mode_list(struct cpio *cpio)
{
struct archive *a;
struct archive_entry *entry;
int r;
a = archive_read_new();
if (a == NULL)
lafe_errc(1, 0, "Couldn't allocate archive object");
archive_read_support_filter_all(a);
archive_read_support_format_all(a);
if (cpio->passphrase != NULL)
r = archive_read_add_passphrase(a, cpio->passphrase);
else
r = archive_read_set_passphrase_callback(a, cpio,
&passphrase_callback);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
if (archive_read_open_filename(a, cpio->filename,
cpio->bytes_per_block))
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
if (r != ARCHIVE_OK) {
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
}
if (archive_match_path_excluded(cpio->matching, entry))
continue;
if (cpio->verbose)
list_item_verbose(cpio, entry);
else
fprintf(stdout, "%s\n", archive_entry_pathname(entry));
}
r = archive_read_close(a);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
if (!cpio->quiet) {
int64_t blocks = (archive_filter_bytes(a, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_read_free(a);
exit(0);
}
/*
* Display information about the current file.
*
* The format here roughly duplicates the output of 'ls -l'.
* This is based on SUSv2, where 'tar tv' is documented as
* listing additional information in an "unspecified format,"
* and 'pax -l' is documented as using the same format as 'ls -l'.
*/
static void
list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
{
char size[32];
char date[32];
char uids[16], gids[16];
const char *uname, *gname;
FILE *out = stdout;
const char *fmt;
time_t mtime;
static time_t now;
if (!now)
time(&now);
if (cpio->option_numeric_uid_gid) {
/* Format numeric uid/gid for display. */
strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
uname = uids;
strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
gname = gids;
} else {
/* Use uname if it's present, else lookup name from uid. */
uname = archive_entry_uname(entry);
if (uname == NULL)
uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
/* Use gname if it's present, else lookup name from gid. */
gname = archive_entry_gname(entry);
if (gname == NULL)
gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
}
/* Print device number or file size. */
if (archive_entry_filetype(entry) == AE_IFCHR
|| archive_entry_filetype(entry) == AE_IFBLK) {
snprintf(size, sizeof(size), "%lu,%lu",
(unsigned long)archive_entry_rdevmajor(entry),
(unsigned long)archive_entry_rdevminor(entry));
} else {
strcpy(size, cpio_i64toa(archive_entry_size(entry)));
}
/* Format the time using 'ls -l' conventions. */
mtime = archive_entry_mtime(entry);
#if defined(_WIN32) && !defined(__CYGWIN__)
/* Windows' strftime function does not support %e format. */
if (mtime - now > 365*86400/2
|| mtime - now < -365*86400/2)
fmt = cpio->day_first ? "%d %b %Y" : "%b %d %Y";
else
fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
#else
if (mtime - now > 365*86400/2
|| mtime - now < -365*86400/2)
fmt = cpio->day_first ? "%e %b %Y" : "%b %e %Y";
else
fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
#endif
strftime(date, sizeof(date), fmt, localtime(&mtime));
fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
archive_entry_strmode(entry),
archive_entry_nlink(entry),
uname, gname, size, date,
archive_entry_pathname(entry));
/* Extra information for links. */
if (archive_entry_hardlink(entry)) /* Hard link */
fprintf(out, " link to %s", archive_entry_hardlink(entry));
else if (archive_entry_symlink(entry)) /* Symbolic link */
fprintf(out, " -> %s", archive_entry_symlink(entry));
fprintf(out, "\n");
}
static void
mode_pass(struct cpio *cpio, const char *destdir)
{
struct lafe_line_reader *lr;
const char *p;
int r;
/* Ensure target dir has a trailing '/' to simplify path surgery. */
cpio->destdir = malloc(strlen(destdir) + 8);
strcpy(cpio->destdir, destdir);
if (destdir[strlen(destdir) - 1] != '/')
strcat(cpio->destdir, "/");
cpio->archive = archive_write_disk_new();
if (cpio->archive == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
cpio->linkresolver = archive_entry_linkresolver_new();
archive_write_disk_set_standard_lookup(cpio->archive);
cpio->archive_read_disk = archive_read_disk_new();
if (cpio->archive_read_disk == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
if (cpio->option_follow_links)
archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
else
archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
lr = lafe_line_reader("-", cpio->option_null);
while ((p = lafe_line_reader_next(lr)) != NULL)
file_to_archive(cpio, p);
lafe_line_reader_free(lr);
archive_entry_linkresolver_free(cpio->linkresolver);
r = archive_write_close(cpio->archive);
if (cpio->dot)
fprintf(stderr, "\n");
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
if (!cpio->quiet) {
int64_t blocks =
(archive_filter_bytes(cpio->archive, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_write_free(cpio->archive);
}
/*
* Prompt for a new name for this entry. Returns a pointer to the
* new name or NULL if the entry should not be copied. This
* implements the semantics defined in POSIX.1-1996, which specifies
* that an input of '.' means the name should be unchanged. GNU cpio
* treats '.' as a literal new name.
*/
static const char *
cpio_rename(const char *name)
{
static char buff[1024];
FILE *t;
char *p, *ret;
#if defined(_WIN32) && !defined(__CYGWIN__)
FILE *to;
t = fopen("CONIN$", "r");
if (t == NULL)
return (name);
to = fopen("CONOUT$", "w");
if (to == NULL) {
fclose(t);
return (name);
}
fprintf(to, "%s (Enter/./(new name))? ", name);
fclose(to);
#else
t = fopen("/dev/tty", "r+");
if (t == NULL)
return (name);
fprintf(t, "%s (Enter/./(new name))? ", name);
fflush(t);
#endif
p = fgets(buff, sizeof(buff), t);
fclose(t);
if (p == NULL)
/* End-of-file is a blank line. */
return (NULL);
while (*p == ' ' || *p == '\t')
++p;
if (*p == '\n' || *p == '\0')
/* Empty line. */
return (NULL);
if (*p == '.' && p[1] == '\n')
/* Single period preserves original name. */
return (name);
ret = p;
/* Trim the final newline. */
while (*p != '\0' && *p != '\n')
++p;
/* Overwrite the final \n with a null character. */
*p = '\0';
return (ret);
}
static void
free_cache(struct name_cache *cache)
{
size_t i;
if (cache != NULL) {
for (i = 0; i < cache->size; i++)
free(cache->cache[i].name);
free(cache);
}
}
/*
* Lookup uname/gname from uid/gid, return NULL if no match.
*/
static const char *
lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
{
char asnum[16];
struct name_cache *cache;
const char *name;
int slot;
if (*name_cache_variable == NULL) {
*name_cache_variable = malloc(sizeof(struct name_cache));
if (*name_cache_variable == NULL)
lafe_errc(1, ENOMEM, "No more memory");
memset(*name_cache_variable, 0, sizeof(struct name_cache));
(*name_cache_variable)->size = name_cache_size;
}
cache = *name_cache_variable;
cache->probes++;
slot = id % cache->size;
if (cache->cache[slot].name != NULL) {
if (cache->cache[slot].id == id) {
cache->hits++;
return (cache->cache[slot].name);
}
free(cache->cache[slot].name);
cache->cache[slot].name = NULL;
}
if (lookup_fn(cpio, &name, id) == 0) {
if (name == NULL || name[0] == '\0') {
/* If lookup failed, format it as a number. */
snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
name = asnum;
}
cache->cache[slot].name = strdup(name);
if (cache->cache[slot].name != NULL) {
cache->cache[slot].id = id;
return (cache->cache[slot].name);
}
/*
* Conveniently, NULL marks an empty slot, so
* if the strdup() fails, we've just failed to
* cache it. No recovery necessary.
*/
}
return (NULL);
}
static const char *
lookup_uname(struct cpio *cpio, uid_t uid)
{
return (lookup_name(cpio, &cpio->uname_cache,
&lookup_uname_helper, (id_t)uid));
}
static int
lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
{
struct passwd *pwent;
(void)cpio; /* UNUSED */
errno = 0;
pwent = getpwuid((uid_t)id);
if (pwent == NULL) {
*name = NULL;
if (errno != 0 && errno != ENOENT)
lafe_warnc(errno, "getpwuid(%s) failed",
cpio_i64toa((int64_t)id));
return (errno);
}
*name = pwent->pw_name;
return (0);
}
static const char *
lookup_gname(struct cpio *cpio, gid_t gid)
{
return (lookup_name(cpio, &cpio->gname_cache,
&lookup_gname_helper, (id_t)gid));
}
static int
lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
{
struct group *grent;
(void)cpio; /* UNUSED */
errno = 0;
grent = getgrgid((gid_t)id);
if (grent == NULL) {
*name = NULL;
if (errno != 0)
lafe_warnc(errno, "getgrgid(%s) failed",
cpio_i64toa((int64_t)id));
return (errno);
}
*name = grent->gr_name;
return (0);
}
/*
* It would be nice to just use printf() for formatting large numbers,
* but the compatibility problems are a big headache. Hence the
* following simple utility function.
*/
const char *
cpio_i64toa(int64_t n0)
{
/* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
* We also need 1 byte for '-' and 1 for '\0'.
*/
static char buff[22];
int64_t n = n0 < 0 ? -n0 : n0;
char *p = buff + sizeof(buff);
*--p = '\0';
do {
*--p = '0' + (int)(n % 10);
n /= 10;
} while (n > 0);
if (n0 < 0)
*--p = '-';
return p;
}
#define PPBUFF_SIZE 1024
static const char *
passphrase_callback(struct archive *a, void *_client_data)
{
struct cpio *cpio = (struct cpio *)_client_data;
(void)a; /* UNUSED */
if (cpio->ppbuff == NULL) {
cpio->ppbuff = malloc(PPBUFF_SIZE);
if (cpio->ppbuff == NULL)
lafe_errc(1, errno, "Out of memory");
}
return lafe_readpassphrase("Enter passphrase:",
cpio->ppbuff, PPBUFF_SIZE);
}
static void
passphrase_free(char *ppbuff)
{
if (ppbuff != NULL) {
memset(ppbuff, 0, PPBUFF_SIZE);
free(ppbuff);
}
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1520_1 |
crossvul-cpp_data_good_249_0 | /**
* @file
* IMAP helper functions
*
* @authors
* Copyright (C) 1996-1998,2010,2012-2013 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1996-1999 Brandon Long <blong@fiction.net>
* Copyright (C) 1999-2009,2012 Brendan Cully <brendan@kublai.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page imap_util IMAP helper functions
*
* IMAP helper functions
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "imap_private.h"
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "bcache.h"
#include "context.h"
#include "globals.h"
#include "header.h"
#include "imap/imap.h"
#include "mailbox.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_socket.h"
#include "mx.h"
#include "options.h"
#include "protos.h"
#include "url.h"
#ifdef USE_HCACHE
#include "hcache/hcache.h"
#endif
/**
* imap_expand_path - Canonicalise an IMAP path
* @param path Buffer containing path
* @param len Buffer length
* @retval 0 Success
* @retval -1 Error
*
* IMAP implementation of mutt_expand_path. Rewrite an IMAP path in canonical
* and absolute form. The buffer is rewritten in place with the canonical IMAP
* path.
*
* Function can fail if imap_parse_path() or url_tostring() fail,
* of if the buffer isn't large enough.
*/
int imap_expand_path(char *path, size_t len)
{
struct ImapMbox mx;
struct ImapData *idata = NULL;
struct Url url;
char fixedpath[LONG_STRING];
int rc;
if (imap_parse_path(path, &mx) < 0)
return -1;
idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW);
mutt_account_tourl(&mx.account, &url);
imap_fix_path(idata, mx.mbox, fixedpath, sizeof(fixedpath));
url.path = fixedpath;
rc = url_tostring(&url, path, len, U_DECODE_PASSWD);
FREE(&mx.mbox);
return rc;
}
/**
* imap_get_parent - Get an IMAP folder's parent
* @param output Buffer for the result
* @param mbox Mailbox whose parent is to be determined
* @param olen Length of the buffer
* @param delim Path delimiter
*/
void imap_get_parent(char *output, const char *mbox, size_t olen, char delim)
{
int n;
/* Make a copy of the mailbox name, but only if the pointers are different */
if (mbox != output)
mutt_str_strfcpy(output, mbox, olen);
n = mutt_str_strlen(output);
/* Let's go backwards until the next delimiter
*
* If output[n] is a '/', the first n-- will allow us
* to ignore it. If it isn't, then output looks like
* "/aaaaa/bbbb". There is at least one "b", so we can't skip
* the "/" after the 'a's.
*
* If output == '/', then n-- => n == 0, so the loop ends
* immediately
*/
for (n--; n >= 0 && output[n] != delim; n--)
;
/* We stopped before the beginning. There is a trailing
* slash.
*/
if (n > 0)
{
/* Strip the trailing delimiter. */
output[n] = '\0';
}
else
{
output[0] = (n == 0) ? delim : '\0';
}
}
/**
* imap_get_parent_path - Get the path of the parent folder
* @param output Buffer for the result
* @param path Mailbox whose parent is to be determined
* @param olen Length of the buffer
*
* Provided an imap path, returns in output the parent directory if
* existent. Else returns the same path.
*/
void imap_get_parent_path(char *output, const char *path, size_t olen)
{
struct ImapMbox mx;
struct ImapData *idata = NULL;
char mbox[LONG_STRING] = "";
if (imap_parse_path(path, &mx) < 0)
{
mutt_str_strfcpy(output, path, olen);
return;
}
idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW);
if (!idata)
{
mutt_str_strfcpy(output, path, olen);
return;
}
/* Stores a fixed path in mbox */
imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox));
/* Gets the parent mbox in mbox */
imap_get_parent(mbox, mbox, sizeof(mbox), idata->delim);
/* Returns a fully qualified IMAP url */
imap_qualify_path(output, olen, &mx, mbox);
FREE(&mx.mbox);
}
/**
* imap_clean_path - Cleans an IMAP path using imap_fix_path
* @param path Path to be cleaned
* @param plen Length of the buffer
*
* Does it in place.
*/
void imap_clean_path(char *path, size_t plen)
{
struct ImapMbox mx;
struct ImapData *idata = NULL;
char mbox[LONG_STRING] = "";
if (imap_parse_path(path, &mx) < 0)
return;
idata = imap_conn_find(&mx.account, MUTT_IMAP_CONN_NONEW);
if (!idata)
return;
/* Stores a fixed path in mbox */
imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox));
/* Returns a fully qualified IMAP url */
imap_qualify_path(path, plen, &mx, mbox);
}
#ifdef USE_HCACHE
/**
* imap_hcache_namer - Generate a filename for the header cache
* @param path Path for the header cache file
* @param dest Buffer for result
* @param dlen Length of buffer
* @retval num Chars written to dest
*/
static int imap_hcache_namer(const char *path, char *dest, size_t dlen)
{
return snprintf(dest, dlen, "%s.hcache", path);
}
/**
* imap_hcache_open - Open a header cache
* @param idata Server data
* @param path Path to the header cache
* @retval ptr HeaderCache
* @retval NULL Failure
*/
header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)
{
struct ImapMbox mx;
struct Url url;
char cachepath[PATH_MAX];
char mbox[PATH_MAX];
if (path)
imap_cachepath(idata, path, mbox, sizeof(mbox));
else
{
if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)
return NULL;
imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));
FREE(&mx.mbox);
}
if (strstr(mbox, "/../") || (strcmp(mbox, "..") == 0) || (strncmp(mbox, "../", 3) == 0))
return NULL;
size_t len = strlen(mbox);
if ((len > 3) && (strcmp(mbox + len - 3, "/..") == 0))
return NULL;
mutt_account_tourl(&idata->conn->account, &url);
url.path = mbox;
url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);
return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);
}
/**
* imap_hcache_close - Close the header cache
* @param idata Server data
*/
void imap_hcache_close(struct ImapData *idata)
{
if (!idata->hcache)
return;
mutt_hcache_close(idata->hcache);
idata->hcache = NULL;
}
/**
* imap_hcache_get - Get a header cache entry by its UID
* @param idata Server data
* @param uid UID to find
* @retval ptr Email Header
* @retval NULL Failure
*/
struct Header *imap_hcache_get(struct ImapData *idata, unsigned int uid)
{
char key[16];
void *uv = NULL;
struct Header *h = NULL;
if (!idata->hcache)
return NULL;
sprintf(key, "/%u", uid);
uv = mutt_hcache_fetch(idata->hcache, key, imap_hcache_keylen(key));
if (uv)
{
if (*(unsigned int *) uv == idata->uid_validity)
h = mutt_hcache_restore(uv);
else
mutt_debug(3, "hcache uidvalidity mismatch: %u\n", *(unsigned int *) uv);
mutt_hcache_free(idata->hcache, &uv);
}
return h;
}
/**
* imap_hcache_put - Add an entry to the header cache
* @param idata Server data
* @param h Email Header
* @retval 0 Success
* @retval -1 Failure
*/
int imap_hcache_put(struct ImapData *idata, struct Header *h)
{
char key[16];
if (!idata->hcache)
return -1;
sprintf(key, "/%u", HEADER_DATA(h)->uid);
return mutt_hcache_store(idata->hcache, key, imap_hcache_keylen(key), h, idata->uid_validity);
}
/**
* imap_hcache_del - Delete an item from the header cache
* @param idata Server data
* @param uid UID of entry to delete
* @retval 0 Success
* @retval -1 Failure
*/
int imap_hcache_del(struct ImapData *idata, unsigned int uid)
{
char key[16];
if (!idata->hcache)
return -1;
sprintf(key, "/%u", uid);
return mutt_hcache_delete(idata->hcache, key, imap_hcache_keylen(key));
}
#endif
/**
* imap_parse_path - Parse an IMAP mailbox name into name,host,port
* @param path Mailbox path to parse
* @param mx An IMAP mailbox
* @retval 0 Success
* @retval -1 Failure
*
* Given an IMAP mailbox name, return host, port and a path IMAP servers will
* recognize. mx.mbox is malloc'd, caller must free it
*/
int imap_parse_path(const char *path, struct ImapMbox *mx)
{
static unsigned short ImapPort = 0;
static unsigned short ImapsPort = 0;
struct servent *service = NULL;
struct Url url;
char *c = NULL;
if (!ImapPort)
{
service = getservbyname("imap", "tcp");
if (service)
ImapPort = ntohs(service->s_port);
else
ImapPort = IMAP_PORT;
mutt_debug(3, "Using default IMAP port %d\n", ImapPort);
}
if (!ImapsPort)
{
service = getservbyname("imaps", "tcp");
if (service)
ImapsPort = ntohs(service->s_port);
else
ImapsPort = IMAP_SSL_PORT;
mutt_debug(3, "Using default IMAPS port %d\n", ImapsPort);
}
/* Defaults */
memset(&mx->account, 0, sizeof(mx->account));
mx->account.port = ImapPort;
mx->account.type = MUTT_ACCT_TYPE_IMAP;
c = mutt_str_strdup(path);
url_parse(&url, c);
if (url.scheme == U_IMAP || url.scheme == U_IMAPS)
{
if (mutt_account_fromurl(&mx->account, &url) < 0 || !*mx->account.host)
{
url_free(&url);
FREE(&c);
return -1;
}
mx->mbox = mutt_str_strdup(url.path);
if (url.scheme == U_IMAPS)
mx->account.flags |= MUTT_ACCT_SSL;
url_free(&url);
FREE(&c);
}
/* old PINE-compatibility code */
else
{
url_free(&url);
FREE(&c);
char tmp[128];
if (sscanf(path, "{%127[^}]}", tmp) != 1)
return -1;
c = strchr(path, '}');
if (!c)
return -1;
else
{
/* walk past closing '}' */
mx->mbox = mutt_str_strdup(c + 1);
}
c = strrchr(tmp, '@');
if (c)
{
*c = '\0';
mutt_str_strfcpy(mx->account.user, tmp, sizeof(mx->account.user));
mutt_str_strfcpy(tmp, c + 1, sizeof(tmp));
mx->account.flags |= MUTT_ACCT_USER;
}
const int n = sscanf(tmp, "%127[^:/]%127s", mx->account.host, tmp);
if (n < 1)
{
mutt_debug(1, "NULL host in %s\n", path);
FREE(&mx->mbox);
return -1;
}
if (n > 1)
{
if (sscanf(tmp, ":%hu%127s", &(mx->account.port), tmp) >= 1)
mx->account.flags |= MUTT_ACCT_PORT;
if (sscanf(tmp, "/%s", tmp) == 1)
{
if (mutt_str_strncmp(tmp, "ssl", 3) == 0)
mx->account.flags |= MUTT_ACCT_SSL;
else
{
mutt_debug(1, "Unknown connection type in %s\n", path);
FREE(&mx->mbox);
return -1;
}
}
}
}
if ((mx->account.flags & MUTT_ACCT_SSL) && !(mx->account.flags & MUTT_ACCT_PORT))
mx->account.port = ImapsPort;
return 0;
}
/**
* imap_mxcmp - Compare mailbox names, giving priority to INBOX
* @param mx1 First mailbox name
* @param mx2 Second mailbox name
* @retval <0 First mailbox precedes Second mailbox
* @retval 0 Mailboxes are the same
* @retval >0 Second mailbox precedes First mailbox
*
* Like a normal sort function except that "INBOX" will be sorted to the
* beginning of the list.
*/
int imap_mxcmp(const char *mx1, const char *mx2)
{
char *b1 = NULL;
char *b2 = NULL;
int rc;
if (!mx1 || !*mx1)
mx1 = "INBOX";
if (!mx2 || !*mx2)
mx2 = "INBOX";
if ((mutt_str_strcasecmp(mx1, "INBOX") == 0) &&
(mutt_str_strcasecmp(mx2, "INBOX") == 0))
{
return 0;
}
b1 = mutt_mem_malloc(strlen(mx1) + 1);
b2 = mutt_mem_malloc(strlen(mx2) + 1);
imap_fix_path(NULL, mx1, b1, strlen(mx1) + 1);
imap_fix_path(NULL, mx2, b2, strlen(mx2) + 1);
rc = mutt_str_strcmp(b1, b2);
FREE(&b1);
FREE(&b2);
return rc;
}
/**
* imap_pretty_mailbox - Prettify an IMAP mailbox name
* @param path Mailbox name to be tidied
*
* Called by mutt_pretty_mailbox() to make IMAP paths look nice.
*/
void imap_pretty_mailbox(char *path)
{
struct ImapMbox home, target;
struct Url url;
char *delim = NULL;
int tlen;
int hlen = 0;
bool home_match = false;
if (imap_parse_path(path, &target) < 0)
return;
tlen = mutt_str_strlen(target.mbox);
/* check whether we can do '=' substitution */
if (mx_is_imap(Folder) && !imap_parse_path(Folder, &home))
{
hlen = mutt_str_strlen(home.mbox);
if (tlen && mutt_account_match(&home.account, &target.account) &&
(mutt_str_strncmp(home.mbox, target.mbox, hlen) == 0))
{
if (hlen == 0)
home_match = true;
else if (ImapDelimChars)
{
for (delim = ImapDelimChars; *delim != '\0'; delim++)
if (target.mbox[hlen] == *delim)
home_match = true;
}
}
FREE(&home.mbox);
}
/* do the '=' substitution */
if (home_match)
{
*path++ = '=';
/* copy remaining path, skipping delimiter */
if (hlen == 0)
hlen = -1;
memcpy(path, target.mbox + hlen + 1, tlen - hlen - 1);
path[tlen - hlen - 1] = '\0';
}
else
{
mutt_account_tourl(&target.account, &url);
url.path = target.mbox;
/* FIXME: That hard-coded constant is bogus. But we need the actual
* size of the buffer from mutt_pretty_mailbox. And these pretty
* operations usually shrink the result. Still... */
url_tostring(&url, path, 1024, 0);
}
FREE(&target.mbox);
}
/**
* imap_continue - display a message and ask the user if they want to go on
* @param msg Location of the error
* @param resp Message for user
* @retval num Result: #MUTT_YES, #MUTT_NO, #MUTT_ABORT
*/
int imap_continue(const char *msg, const char *resp)
{
imap_error(msg, resp);
return mutt_yesorno(_("Continue?"), 0);
}
/**
* imap_error - show an error and abort
* @param where Location of the error
* @param msg Message for user
*/
void imap_error(const char *where, const char *msg)
{
mutt_error("%s [%s]\n", where, msg);
}
/**
* imap_new_idata - Allocate and initialise a new ImapData structure
* @retval NULL Failure (no mem)
* @retval ptr New ImapData
*/
struct ImapData *imap_new_idata(void)
{
struct ImapData *idata = mutt_mem_calloc(1, sizeof(struct ImapData));
idata->cmdbuf = mutt_buffer_new();
idata->cmdslots = ImapPipelineDepth + 2;
idata->cmds = mutt_mem_calloc(idata->cmdslots, sizeof(*idata->cmds));
STAILQ_INIT(&idata->flags);
STAILQ_INIT(&idata->mboxcache);
return idata;
}
/**
* imap_free_idata - Release and clear storage in an ImapData structure
* @param idata Server data
*/
void imap_free_idata(struct ImapData **idata)
{
if (!idata)
return;
FREE(&(*idata)->capstr);
mutt_list_free(&(*idata)->flags);
imap_mboxcache_free(*idata);
mutt_buffer_free(&(*idata)->cmdbuf);
FREE(&(*idata)->buf);
mutt_bcache_close(&(*idata)->bcache);
FREE(&(*idata)->cmds);
FREE(idata);
}
/**
* imap_fix_path - Fix up the imap path
* @param idata Server data
* @param mailbox Mailbox path
* @param path Buffer for the result
* @param plen Length of buffer
* @retval ptr Fixed-up path
*
* This is necessary because the rest of neomutt assumes a hierarchy delimiter of
* '/', which is not necessarily true in IMAP. Additionally, the filesystem
* converts multiple hierarchy delimiters into a single one, ie "///" is equal
* to "/". IMAP servers are not required to do this.
* Moreover, IMAP servers may dislike the path ending with the delimiter.
*/
char *imap_fix_path(struct ImapData *idata, const char *mailbox, char *path, size_t plen)
{
int i = 0;
char delim = '\0';
if (idata)
delim = idata->delim;
while (mailbox && *mailbox && i < plen - 1)
{
if ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) || (delim && *mailbox == delim))
{
/* use connection delimiter if known. Otherwise use user delimiter */
if (!idata)
delim = *mailbox;
while (*mailbox && ((ImapDelimChars && strchr(ImapDelimChars, *mailbox)) ||
(delim && *mailbox == delim)))
{
mailbox++;
}
path[i] = delim;
}
else
{
path[i] = *mailbox;
mailbox++;
}
i++;
}
if (i && path[--i] != delim)
i++;
path[i] = '\0';
return path;
}
/**
* imap_cachepath - Generate a cache path for a mailbox
* @param idata Server data
* @param mailbox Mailbox name
* @param dest Buffer to store cache path
* @param dlen Length of buffer
*/
void imap_cachepath(struct ImapData *idata, const char *mailbox, char *dest, size_t dlen)
{
char *s = NULL;
const char *p = mailbox;
for (s = dest; p && *p && dlen; dlen--)
{
if (*p == idata->delim)
{
*s = '/';
/* simple way to avoid collisions with UIDs */
if (*(p + 1) >= '0' && *(p + 1) <= '9')
{
if (--dlen)
*++s = '_';
}
}
else
*s = *p;
p++;
s++;
}
*s = '\0';
}
/**
* imap_get_literal_count - write number of bytes in an IMAP literal into bytes
* @param[in] buf Number as a string
* @param[out] bytes Resulting number
* @retval 0 Success
* @retval -1 Failure
*/
int imap_get_literal_count(const char *buf, unsigned int *bytes)
{
char *pc = NULL;
char *pn = NULL;
if (!buf || !(pc = strchr(buf, '{')))
return -1;
pc++;
pn = pc;
while (isdigit((unsigned char) *pc))
pc++;
*pc = '\0';
if (mutt_str_atoui(pn, bytes) < 0)
return -1;
return 0;
}
/**
* imap_get_qualifier - Get the qualifier from a tagged response
* @param buf Command string to process
* @retval ptr Start of the qualifier
*
* In a tagged response, skip tag and status for the qualifier message.
* Used by imap_copy_message for TRYCREATE
*/
char *imap_get_qualifier(char *buf)
{
char *s = buf;
/* skip tag */
s = imap_next_word(s);
/* skip OK/NO/BAD response */
s = imap_next_word(s);
return s;
}
/**
* imap_next_word - Find where the next IMAP word begins
* @param s Command string to process
* @retval ptr Next IMAP word
*/
char *imap_next_word(char *s)
{
int quoted = 0;
while (*s)
{
if (*s == '\\')
{
s++;
if (*s)
s++;
continue;
}
if (*s == '\"')
quoted = quoted ? 0 : 1;
if (!quoted && ISSPACE(*s))
break;
s++;
}
SKIPWS(s);
return s;
}
/**
* imap_qualify_path - Make an absolute IMAP folder target
* @param dest Buffer for the result
* @param len Length of buffer
* @param mx Imap mailbox
* @param path Path relative to the mailbox
*
* given ImapMbox and relative path.
*/
void imap_qualify_path(char *dest, size_t len, struct ImapMbox *mx, char *path)
{
struct Url url;
mutt_account_tourl(&mx->account, &url);
url.path = path;
url_tostring(&url, dest, len, 0);
}
/**
* imap_quote_string - quote string according to IMAP rules
* @param dest Buffer for the result
* @param dlen Length of the buffer
* @param src String to be quoted
*
* Surround string with quotes, escape " and \ with backslash
*/
void imap_quote_string(char *dest, size_t dlen, const char *src, bool quote_backtick)
{
const char *quote = "`\"\\";
if (!quote_backtick)
quote++;
char *pt = dest;
const char *s = src;
*pt++ = '"';
/* save room for trailing quote-char */
dlen -= 2;
for (; *s && dlen; s++)
{
if (strchr(quote, *s))
{
dlen -= 2;
if (dlen == 0)
break;
*pt++ = '\\';
*pt++ = *s;
}
else
{
*pt++ = *s;
dlen--;
}
}
*pt++ = '"';
*pt = '\0';
}
/**
* imap_unquote_string - equally stupid unquoting routine
* @param s String to be unquoted
*/
void imap_unquote_string(char *s)
{
char *d = s;
if (*s == '\"')
s++;
else
return;
while (*s)
{
if (*s == '\"')
{
*d = '\0';
return;
}
if (*s == '\\')
{
s++;
}
if (*s)
{
*d = *s;
d++;
s++;
}
}
*d = '\0';
}
/**
* imap_munge_mbox_name - Quote awkward characters in a mailbox name
* @param idata Server data
* @param dest Buffer to store safe mailbox name
* @param dlen Length of buffer
* @param src Mailbox name
*/
void imap_munge_mbox_name(struct ImapData *idata, char *dest, size_t dlen, const char *src)
{
char *buf = mutt_str_strdup(src);
imap_utf_encode(idata, &buf);
imap_quote_string(dest, dlen, buf, false);
FREE(&buf);
}
/**
* imap_unmunge_mbox_name - Remove quoting from a mailbox name
* @param idata Server data
* @param s Mailbox name
*
* The string will be altered in-place.
*/
void imap_unmunge_mbox_name(struct ImapData *idata, char *s)
{
imap_unquote_string(s);
char *buf = mutt_str_strdup(s);
if (buf)
{
imap_utf_decode(idata, &buf);
strncpy(s, buf, strlen(s));
}
FREE(&buf);
}
/**
* imap_keepalive - poll the current folder to keep the connection alive
*/
void imap_keepalive(void)
{
struct Connection *conn = NULL;
struct ImapData *idata = NULL;
time_t now = time(NULL);
TAILQ_FOREACH(conn, mutt_socket_head(), entries)
{
if (conn->account.type == MUTT_ACCT_TYPE_IMAP)
{
idata = conn->data;
if (idata->state >= IMAP_AUTHENTICATED && now >= idata->lastread + ImapKeepalive)
{
imap_check(idata, 1);
}
}
}
}
/**
* imap_wait_keepalive - Wait for a process to change state
* @param pid Process ID to listen to
* @retval num 'wstatus' from waitpid()
*/
int imap_wait_keepalive(pid_t pid)
{
struct sigaction oldalrm;
struct sigaction act;
sigset_t oldmask;
int rc;
bool imap_passive = ImapPassive;
ImapPassive = true;
OptKeepQuiet = true;
sigprocmask(SIG_SETMASK, NULL, &oldmask);
sigemptyset(&act.sa_mask);
act.sa_handler = mutt_sig_empty_handler;
#ifdef SA_INTERRUPT
act.sa_flags = SA_INTERRUPT;
#else
act.sa_flags = 0;
#endif
sigaction(SIGALRM, &act, &oldalrm);
alarm(ImapKeepalive);
while (waitpid(pid, &rc, 0) < 0 && errno == EINTR)
{
alarm(0); /* cancel a possibly pending alarm */
imap_keepalive();
alarm(ImapKeepalive);
}
alarm(0); /* cancel a possibly pending alarm */
sigaction(SIGALRM, &oldalrm, NULL);
sigprocmask(SIG_SETMASK, &oldmask, NULL);
OptKeepQuiet = false;
if (!imap_passive)
ImapPassive = false;
return rc;
}
/**
* imap_allow_reopen - Allow re-opening a folder upon expunge
* @param ctx Context
*/
void imap_allow_reopen(struct Context *ctx)
{
struct ImapData *idata = NULL;
if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP)
return;
idata = ctx->data;
if (idata->ctx == ctx)
idata->reopen |= IMAP_REOPEN_ALLOW;
}
/**
* imap_disallow_reopen - Disallow re-opening a folder upon expunge
* @param ctx Context
*/
void imap_disallow_reopen(struct Context *ctx)
{
struct ImapData *idata = NULL;
if (!ctx || !ctx->data || ctx->magic != MUTT_IMAP)
return;
idata = ctx->data;
if (idata->ctx == ctx)
idata->reopen &= ~IMAP_REOPEN_ALLOW;
}
/**
* imap_account_match - Compare two Accounts
* @param a1 First Account
* @param a2 Second Account
* @retval true Accounts match
*/
int imap_account_match(const struct Account *a1, const struct Account *a2)
{
struct ImapData *a1_idata = imap_conn_find(a1, MUTT_IMAP_CONN_NONEW);
struct ImapData *a2_idata = imap_conn_find(a2, MUTT_IMAP_CONN_NONEW);
const struct Account *a1_canon = a1_idata == NULL ? a1 : &a1_idata->conn->account;
const struct Account *a2_canon = a2_idata == NULL ? a2 : &a2_idata->conn->account;
return mutt_account_match(a1_canon, a2_canon);
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_249_0 |
crossvul-cpp_data_bad_1520_1 | /*-
* Copyright (c) 2003-2007 Tim Kientzle
* 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
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpio_platform.h"
__FBSDID("$FreeBSD: src/usr.bin/cpio/cpio.c,v 1.15 2008/12/06 07:30:40 kientzle Exp $");
#include <sys/types.h>
#include <archive.h>
#include <archive_entry.h>
#ifdef HAVE_SYS_MKDEV_H
#include <sys/mkdev.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdio.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include "cpio.h"
#include "err.h"
#include "line_reader.h"
#include "passphrase.h"
/* Fixed size of uname/gname caches. */
#define name_cache_size 101
#ifndef O_BINARY
#define O_BINARY 0
#endif
struct name_cache {
int probes;
int hits;
size_t size;
struct {
id_t id;
char *name;
} cache[name_cache_size];
};
static int extract_data(struct archive *, struct archive *);
const char * cpio_i64toa(int64_t);
static const char *cpio_rename(const char *name);
static int entry_to_archive(struct cpio *, struct archive_entry *);
static int file_to_archive(struct cpio *, const char *);
static void free_cache(struct name_cache *cache);
static void list_item_verbose(struct cpio *, struct archive_entry *);
static void long_help(void);
static const char *lookup_gname(struct cpio *, gid_t gid);
static int lookup_gname_helper(struct cpio *,
const char **name, id_t gid);
static const char *lookup_uname(struct cpio *, uid_t uid);
static int lookup_uname_helper(struct cpio *,
const char **name, id_t uid);
static void mode_in(struct cpio *);
static void mode_list(struct cpio *);
static void mode_out(struct cpio *);
static void mode_pass(struct cpio *, const char *);
static const char *remove_leading_slash(const char *);
static int restore_time(struct cpio *, struct archive_entry *,
const char *, int fd);
static void usage(void);
static void version(void);
static const char * passphrase_callback(struct archive *, void *);
static void passphrase_free(char *);
int
main(int argc, char *argv[])
{
static char buff[16384];
struct cpio _cpio; /* Allocated on stack. */
struct cpio *cpio;
const char *errmsg;
int uid, gid;
int opt;
cpio = &_cpio;
memset(cpio, 0, sizeof(*cpio));
cpio->buff = buff;
cpio->buff_size = sizeof(buff);
#if defined(HAVE_SIGACTION) && defined(SIGPIPE)
{ /* Ignore SIGPIPE signals. */
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, NULL);
}
#endif
/* Set lafe_progname before calling lafe_warnc. */
lafe_setprogname(*argv, "bsdcpio");
#if HAVE_SETLOCALE
if (setlocale(LC_ALL, "") == NULL)
lafe_warnc(0, "Failed to set default locale");
#endif
cpio->uid_override = -1;
cpio->gid_override = -1;
cpio->argv = argv;
cpio->argc = argc;
cpio->mode = '\0';
cpio->verbose = 0;
cpio->compress = '\0';
cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
#if !defined(_WIN32) && !defined(__CYGWIN__)
if (geteuid() == 0)
cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
#endif
cpio->bytes_per_block = 512;
cpio->filename = NULL;
cpio->matching = archive_match_new();
if (cpio->matching == NULL)
lafe_errc(1, 0, "Out of memory");
while ((opt = cpio_getopt(cpio)) != -1) {
switch (opt) {
case '0': /* GNU convention: --null, -0 */
cpio->option_null = 1;
break;
case 'A': /* NetBSD/OpenBSD */
cpio->option_append = 1;
break;
case 'a': /* POSIX 1997 */
cpio->option_atime_restore = 1;
break;
case 'B': /* POSIX 1997 */
cpio->bytes_per_block = 5120;
break;
case OPTION_B64ENCODE:
cpio->add_filter = opt;
break;
case 'C': /* NetBSD/OpenBSD */
cpio->bytes_per_block = atoi(cpio->argument);
if (cpio->bytes_per_block <= 0)
lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
break;
case 'c': /* POSIX 1997 */
cpio->format = "odc";
break;
case 'd': /* POSIX 1997 */
cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
break;
case 'E': /* NetBSD/OpenBSD */
if (archive_match_include_pattern_from_file(
cpio->matching, cpio->argument,
cpio->option_null) != ARCHIVE_OK)
lafe_errc(1, 0, "Error : %s",
archive_error_string(cpio->matching));
break;
case 'F': /* NetBSD/OpenBSD/GNU cpio */
cpio->filename = cpio->argument;
break;
case 'f': /* POSIX 1997 */
if (archive_match_exclude_pattern(cpio->matching,
cpio->argument) != ARCHIVE_OK)
lafe_errc(1, 0, "Error : %s",
archive_error_string(cpio->matching));
break;
case OPTION_GRZIP:
cpio->compress = opt;
break;
case 'H': /* GNU cpio (also --format) */
cpio->format = cpio->argument;
break;
case 'h':
long_help();
break;
case 'I': /* NetBSD/OpenBSD */
cpio->filename = cpio->argument;
break;
case 'i': /* POSIX 1997 */
if (cpio->mode != '\0')
lafe_errc(1, 0,
"Cannot use both -i and -%c", cpio->mode);
cpio->mode = opt;
break;
case 'J': /* GNU tar, others */
cpio->compress = opt;
break;
case 'j': /* GNU tar, others */
cpio->compress = opt;
break;
case OPTION_INSECURE:
cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
break;
case 'L': /* GNU cpio */
cpio->option_follow_links = 1;
break;
case 'l': /* POSIX 1997 */
cpio->option_link = 1;
break;
case OPTION_LRZIP:
case OPTION_LZ4:
case OPTION_LZMA: /* GNU tar, others */
case OPTION_LZOP: /* GNU tar, others */
cpio->compress = opt;
break;
case 'm': /* POSIX 1997 */
cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
break;
case 'n': /* GNU cpio */
cpio->option_numeric_uid_gid = 1;
break;
case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
break;
case 'O': /* GNU cpio */
cpio->filename = cpio->argument;
break;
case 'o': /* POSIX 1997 */
if (cpio->mode != '\0')
lafe_errc(1, 0,
"Cannot use both -o and -%c", cpio->mode);
cpio->mode = opt;
break;
case 'p': /* POSIX 1997 */
if (cpio->mode != '\0')
lafe_errc(1, 0,
"Cannot use both -p and -%c", cpio->mode);
cpio->mode = opt;
cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
break;
case OPTION_PASSPHRASE:
cpio->passphrase = cpio->argument;
break;
case OPTION_PRESERVE_OWNER:
cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
break;
case OPTION_QUIET: /* GNU cpio */
cpio->quiet = 1;
break;
case 'R': /* GNU cpio, also --owner */
/* TODO: owner_parse should return uname/gname
* also; use that to set [ug]name_override. */
errmsg = owner_parse(cpio->argument, &uid, &gid);
if (errmsg) {
lafe_warnc(-1, "%s", errmsg);
usage();
}
if (uid != -1) {
cpio->uid_override = uid;
cpio->uname_override = NULL;
}
if (gid != -1) {
cpio->gid_override = gid;
cpio->gname_override = NULL;
}
break;
case 'r': /* POSIX 1997 */
cpio->option_rename = 1;
break;
case 't': /* POSIX 1997 */
cpio->option_list = 1;
break;
case 'u': /* POSIX 1997 */
cpio->extract_flags
&= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
break;
case OPTION_UUENCODE:
cpio->add_filter = opt;
break;
case 'v': /* POSIX 1997 */
cpio->verbose++;
break;
case 'V': /* GNU cpio */
cpio->dot++;
break;
case OPTION_VERSION: /* GNU convention */
version();
break;
#if 0
/*
* cpio_getopt() handles -W specially, so it's not
* available here.
*/
case 'W': /* Obscure, but useful GNU convention. */
break;
#endif
case 'y': /* tar convention */
cpio->compress = opt;
break;
case 'Z': /* tar convention */
cpio->compress = opt;
break;
case 'z': /* tar convention */
cpio->compress = opt;
break;
default:
usage();
}
}
/*
* Sanity-check args, error out on nonsensical combinations.
*/
/* -t implies -i if no mode was specified. */
if (cpio->option_list && cpio->mode == '\0')
cpio->mode = 'i';
/* -t requires -i */
if (cpio->option_list && cpio->mode != 'i')
lafe_errc(1, 0, "Option -t requires -i");
/* -n requires -it */
if (cpio->option_numeric_uid_gid && !cpio->option_list)
lafe_errc(1, 0, "Option -n requires -it");
/* Can only specify format when writing */
if (cpio->format != NULL && cpio->mode != 'o')
lafe_errc(1, 0, "Option --format requires -o");
/* -l requires -p */
if (cpio->option_link && cpio->mode != 'p')
lafe_errc(1, 0, "Option -l requires -p");
/* -v overrides -V */
if (cpio->dot && cpio->verbose)
cpio->dot = 0;
/* TODO: Flag other nonsensical combinations. */
switch (cpio->mode) {
case 'o':
/* TODO: Implement old binary format in libarchive,
use that here. */
if (cpio->format == NULL)
cpio->format = "odc"; /* Default format */
mode_out(cpio);
break;
case 'i':
while (*cpio->argv != NULL) {
if (archive_match_include_pattern(cpio->matching,
*cpio->argv) != ARCHIVE_OK)
lafe_errc(1, 0, "Error : %s",
archive_error_string(cpio->matching));
--cpio->argc;
++cpio->argv;
}
if (cpio->option_list)
mode_list(cpio);
else
mode_in(cpio);
break;
case 'p':
if (*cpio->argv == NULL || **cpio->argv == '\0')
lafe_errc(1, 0,
"-p mode requires a target directory");
mode_pass(cpio, *cpio->argv);
break;
default:
lafe_errc(1, 0,
"Must specify at least one of -i, -o, or -p");
}
archive_match_free(cpio->matching);
free_cache(cpio->gname_cache);
free_cache(cpio->uname_cache);
free(cpio->destdir);
passphrase_free(cpio->ppbuff);
return (cpio->return_value);
}
static void
usage(void)
{
const char *p;
p = lafe_getprogname();
fprintf(stderr, "Brief Usage:\n");
fprintf(stderr, " List: %s -it < archive\n", p);
fprintf(stderr, " Extract: %s -i < archive\n", p);
fprintf(stderr, " Create: %s -o < filenames > archive\n", p);
fprintf(stderr, " Help: %s --help\n", p);
exit(1);
}
static const char *long_help_msg =
"First option must be a mode specifier:\n"
" -i Input -o Output -p Pass\n"
"Common Options:\n"
" -v Verbose filenames -V one dot per file\n"
"Create: %p -o [options] < [list of files] > [archive]\n"
" -J,-y,-z,--lzma Compress archive with xz/bzip2/gzip/lzma\n"
" --format {odc|newc|ustar} Select archive format\n"
"List: %p -it < [archive]\n"
"Extract: %p -i [options] < [archive]\n";
/*
* Note that the word 'bsdcpio' will always appear in the first line
* of output.
*
* In particular, /bin/sh scripts that need to test for the presence
* of bsdcpio can use the following template:
*
* if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
* echo bsdcpio; else echo not bsdcpio; fi
*/
static void
long_help(void)
{
const char *prog;
const char *p;
prog = lafe_getprogname();
fflush(stderr);
p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
printf("%s%s: manipulate archive files\n", prog, p);
for (p = long_help_msg; *p != '\0'; p++) {
if (*p == '%') {
if (p[1] == 'p') {
fputs(prog, stdout);
p++;
} else
putchar('%');
} else
putchar(*p);
}
version();
}
static void
version(void)
{
fprintf(stdout,"bsdcpio %s -- %s\n",
BSDCPIO_VERSION_STRING,
archive_version_details());
exit(0);
}
static void
mode_out(struct cpio *cpio)
{
struct archive_entry *entry, *spare;
struct lafe_line_reader *lr;
const char *p;
int r;
if (cpio->option_append)
lafe_errc(1, 0, "Append mode not yet supported.");
cpio->archive_read_disk = archive_read_disk_new();
if (cpio->archive_read_disk == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
if (cpio->option_follow_links)
archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
else
archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
cpio->archive = archive_write_new();
if (cpio->archive == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
switch (cpio->compress) {
case OPTION_GRZIP:
r = archive_write_add_filter_grzip(cpio->archive);
break;
case 'J':
r = archive_write_add_filter_xz(cpio->archive);
break;
case OPTION_LRZIP:
r = archive_write_add_filter_lrzip(cpio->archive);
break;
case OPTION_LZ4:
r = archive_write_add_filter_lz4(cpio->archive);
break;
case OPTION_LZMA:
r = archive_write_add_filter_lzma(cpio->archive);
break;
case OPTION_LZOP:
r = archive_write_add_filter_lzop(cpio->archive);
break;
case 'j': case 'y':
r = archive_write_add_filter_bzip2(cpio->archive);
break;
case 'z':
r = archive_write_add_filter_gzip(cpio->archive);
break;
case 'Z':
r = archive_write_add_filter_compress(cpio->archive);
break;
default:
r = archive_write_add_filter_none(cpio->archive);
break;
}
if (r < ARCHIVE_WARN)
lafe_errc(1, 0, "Requested compression not available");
switch (cpio->add_filter) {
case 0:
r = ARCHIVE_OK;
break;
case OPTION_B64ENCODE:
r = archive_write_add_filter_b64encode(cpio->archive);
break;
case OPTION_UUENCODE:
r = archive_write_add_filter_uuencode(cpio->archive);
break;
}
if (r < ARCHIVE_WARN)
lafe_errc(1, 0, "Requested filter not available");
r = archive_write_set_format_by_name(cpio->archive, cpio->format);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
cpio->linkresolver = archive_entry_linkresolver_new();
archive_entry_linkresolver_set_strategy(cpio->linkresolver,
archive_format(cpio->archive));
if (cpio->passphrase != NULL)
r = archive_write_set_passphrase(cpio->archive,
cpio->passphrase);
else
r = archive_write_set_passphrase_callback(cpio->archive, cpio,
&passphrase_callback);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
/*
* The main loop: Copy each file into the output archive.
*/
r = archive_write_open_filename(cpio->archive, cpio->filename);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
lr = lafe_line_reader("-", cpio->option_null);
while ((p = lafe_line_reader_next(lr)) != NULL)
file_to_archive(cpio, p);
lafe_line_reader_free(lr);
/*
* The hardlink detection may have queued up a couple of entries
* that can now be flushed.
*/
entry = NULL;
archive_entry_linkify(cpio->linkresolver, &entry, &spare);
while (entry != NULL) {
entry_to_archive(cpio, entry);
archive_entry_free(entry);
entry = NULL;
archive_entry_linkify(cpio->linkresolver, &entry, &spare);
}
r = archive_write_close(cpio->archive);
if (cpio->dot)
fprintf(stderr, "\n");
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
if (!cpio->quiet) {
int64_t blocks =
(archive_filter_bytes(cpio->archive, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_write_free(cpio->archive);
}
static const char *
remove_leading_slash(const char *p)
{
const char *rp;
/* Remove leading "//./" or "//?/" or "//?/UNC/"
* (absolute path prefixes used by Windows API) */
if ((p[0] == '/' || p[0] == '\\') &&
(p[1] == '/' || p[1] == '\\') &&
(p[2] == '.' || p[2] == '?') &&
(p[3] == '/' || p[3] == '\\'))
{
if (p[2] == '?' &&
(p[4] == 'U' || p[4] == 'u') &&
(p[5] == 'N' || p[5] == 'n') &&
(p[6] == 'C' || p[6] == 'c') &&
(p[7] == '/' || p[7] == '\\'))
p += 8;
else
p += 4;
}
do {
rp = p;
/* Remove leading drive letter from archives created
* on Windows. */
if (((p[0] >= 'a' && p[0] <= 'z') ||
(p[0] >= 'A' && p[0] <= 'Z')) &&
p[1] == ':') {
p += 2;
}
/* Remove leading "/../", "//", etc. */
while (p[0] == '/' || p[0] == '\\') {
if (p[1] == '.' && p[2] == '.' &&
(p[3] == '/' || p[3] == '\\')) {
p += 3; /* Remove "/..", leave "/"
* for next pass. */
} else
p += 1; /* Remove "/". */
}
} while (rp != p);
return (p);
}
/*
* This is used by both out mode (to copy objects from disk into
* an archive) and pass mode (to copy objects from disk to
* an archive_write_disk "archive").
*/
static int
file_to_archive(struct cpio *cpio, const char *srcpath)
{
const char *destpath;
struct archive_entry *entry, *spare;
size_t len;
int r;
/*
* Create an archive_entry describing the source file.
*
*/
entry = archive_entry_new();
if (entry == NULL)
lafe_errc(1, 0, "Couldn't allocate entry");
archive_entry_copy_sourcepath(entry, srcpath);
r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
entry, -1, NULL);
if (r < ARCHIVE_FAILED)
lafe_errc(1, 0, "%s",
archive_error_string(cpio->archive_read_disk));
if (r < ARCHIVE_OK)
lafe_warnc(0, "%s",
archive_error_string(cpio->archive_read_disk));
if (r <= ARCHIVE_FAILED) {
cpio->return_value = 1;
return (r);
}
if (cpio->uid_override >= 0) {
archive_entry_set_uid(entry, cpio->uid_override);
archive_entry_set_uname(entry, cpio->uname_override);
}
if (cpio->gid_override >= 0) {
archive_entry_set_gid(entry, cpio->gid_override);
archive_entry_set_gname(entry, cpio->gname_override);
}
/*
* Generate a destination path for this entry.
* "destination path" is the name to which it will be copied in
* pass mode or the name that will go into the archive in
* output mode.
*/
destpath = srcpath;
if (cpio->destdir) {
len = strlen(cpio->destdir) + strlen(srcpath) + 8;
if (len >= cpio->pass_destpath_alloc) {
while (len >= cpio->pass_destpath_alloc) {
cpio->pass_destpath_alloc += 512;
cpio->pass_destpath_alloc *= 2;
}
free(cpio->pass_destpath);
cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
if (cpio->pass_destpath == NULL)
lafe_errc(1, ENOMEM,
"Can't allocate path buffer");
}
strcpy(cpio->pass_destpath, cpio->destdir);
strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
destpath = cpio->pass_destpath;
}
if (cpio->option_rename)
destpath = cpio_rename(destpath);
if (destpath == NULL)
return (0);
archive_entry_copy_pathname(entry, destpath);
/*
* If we're trying to preserve hardlinks, match them here.
*/
spare = NULL;
if (cpio->linkresolver != NULL
&& archive_entry_filetype(entry) != AE_IFDIR) {
archive_entry_linkify(cpio->linkresolver, &entry, &spare);
}
if (entry != NULL) {
r = entry_to_archive(cpio, entry);
archive_entry_free(entry);
if (spare != NULL) {
if (r == 0)
r = entry_to_archive(cpio, spare);
archive_entry_free(spare);
}
}
return (r);
}
static int
entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
{
const char *destpath = archive_entry_pathname(entry);
const char *srcpath = archive_entry_sourcepath(entry);
int fd = -1;
ssize_t bytes_read;
int r;
/* Print out the destination name to the user. */
if (cpio->verbose)
fprintf(stderr,"%s", destpath);
if (cpio->dot)
fprintf(stderr, ".");
/*
* Option_link only makes sense in pass mode and for
* regular files. Also note: if a link operation fails
* because of cross-device restrictions, we'll fall back
* to copy mode for that entry.
*
* TODO: Test other cpio implementations to see if they
* hard-link anything other than regular files here.
*/
if (cpio->option_link
&& archive_entry_filetype(entry) == AE_IFREG)
{
struct archive_entry *t;
/* Save the original entry in case we need it later. */
t = archive_entry_clone(entry);
if (t == NULL)
lafe_errc(1, ENOMEM, "Can't create link");
/* Note: link(2) doesn't create parent directories,
* so we use archive_write_header() instead as a
* convenience. */
archive_entry_set_hardlink(t, srcpath);
/* This is a straight link that carries no data. */
archive_entry_set_size(t, 0);
r = archive_write_header(cpio->archive, t);
archive_entry_free(t);
if (r != ARCHIVE_OK)
lafe_warnc(archive_errno(cpio->archive),
"%s", archive_error_string(cpio->archive));
if (r == ARCHIVE_FATAL)
exit(1);
#ifdef EXDEV
if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
/* Cross-device link: Just fall through and use
* the original entry to copy the file over. */
lafe_warnc(0, "Copying file instead");
} else
#endif
return (0);
}
/*
* Make sure we can open the file (if necessary) before
* trying to write the header.
*/
if (archive_entry_filetype(entry) == AE_IFREG) {
if (archive_entry_size(entry) > 0) {
fd = open(srcpath, O_RDONLY | O_BINARY);
if (fd < 0) {
lafe_warnc(errno,
"%s: could not open file", srcpath);
goto cleanup;
}
}
} else {
archive_entry_set_size(entry, 0);
}
r = archive_write_header(cpio->archive, entry);
if (r != ARCHIVE_OK)
lafe_warnc(archive_errno(cpio->archive),
"%s: %s",
srcpath,
archive_error_string(cpio->archive));
if (r == ARCHIVE_FATAL)
exit(1);
if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
while (bytes_read > 0) {
ssize_t bytes_write;
bytes_write = archive_write_data(cpio->archive,
cpio->buff, bytes_read);
if (bytes_write < 0)
lafe_errc(1, archive_errno(cpio->archive),
"%s", archive_error_string(cpio->archive));
if (bytes_write < bytes_read) {
lafe_warnc(0,
"Truncated write; file may have "
"grown while being archived.");
}
bytes_read = read(fd, cpio->buff,
(unsigned)cpio->buff_size);
}
}
fd = restore_time(cpio, entry, srcpath, fd);
cleanup:
if (cpio->verbose)
fprintf(stderr,"\n");
if (fd >= 0)
close(fd);
return (0);
}
static int
restore_time(struct cpio *cpio, struct archive_entry *entry,
const char *name, int fd)
{
#ifndef HAVE_UTIMES
static int warned = 0;
(void)cpio; /* UNUSED */
(void)entry; /* UNUSED */
(void)name; /* UNUSED */
if (!warned)
lafe_warnc(0, "Can't restore access times on this platform");
warned = 1;
return (fd);
#else
#if defined(_WIN32) && !defined(__CYGWIN__)
struct __timeval times[2];
#else
struct timeval times[2];
#endif
if (!cpio->option_atime_restore)
return (fd);
times[1].tv_sec = archive_entry_mtime(entry);
times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
times[0].tv_sec = archive_entry_atime(entry);
times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
#if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
if (fd >= 0 && futimes(fd, times) == 0)
return (fd);
#endif
/*
* Some platform cannot restore access times if the file descriptor
* is still opened.
*/
if (fd >= 0) {
close(fd);
fd = -1;
}
#ifdef HAVE_LUTIMES
if (lutimes(name, times) != 0)
#else
if ((AE_IFLNK != archive_entry_filetype(entry))
&& utimes(name, times) != 0)
#endif
lafe_warnc(errno, "Can't update time for %s", name);
#endif
return (fd);
}
static void
mode_in(struct cpio *cpio)
{
struct archive *a;
struct archive_entry *entry;
struct archive *ext;
const char *destpath;
int r;
ext = archive_write_disk_new();
if (ext == NULL)
lafe_errc(1, 0, "Couldn't allocate restore object");
r = archive_write_disk_set_options(ext, cpio->extract_flags);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(ext));
a = archive_read_new();
if (a == NULL)
lafe_errc(1, 0, "Couldn't allocate archive object");
archive_read_support_filter_all(a);
archive_read_support_format_all(a);
if (cpio->passphrase != NULL)
r = archive_read_add_passphrase(a, cpio->passphrase);
else
r = archive_read_set_passphrase_callback(a, cpio,
&passphrase_callback);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
if (archive_read_open_filename(a, cpio->filename,
cpio->bytes_per_block))
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
if (r != ARCHIVE_OK) {
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
}
if (archive_match_path_excluded(cpio->matching, entry))
continue;
if (cpio->option_rename) {
destpath = cpio_rename(archive_entry_pathname(entry));
archive_entry_set_pathname(entry, destpath);
} else
destpath = archive_entry_pathname(entry);
if (destpath == NULL)
continue;
if (cpio->verbose)
fprintf(stderr, "%s\n", destpath);
if (cpio->dot)
fprintf(stderr, ".");
if (cpio->uid_override >= 0)
archive_entry_set_uid(entry, cpio->uid_override);
if (cpio->gid_override >= 0)
archive_entry_set_gid(entry, cpio->gid_override);
r = archive_write_header(ext, entry);
if (r != ARCHIVE_OK) {
fprintf(stderr, "%s: %s\n",
archive_entry_pathname(entry),
archive_error_string(ext));
} else if (!archive_entry_size_is_set(entry)
|| archive_entry_size(entry) > 0) {
r = extract_data(a, ext);
if (r != ARCHIVE_OK)
cpio->return_value = 1;
}
}
r = archive_read_close(a);
if (cpio->dot)
fprintf(stderr, "\n");
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
r = archive_write_close(ext);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(ext));
if (!cpio->quiet) {
int64_t blocks = (archive_filter_bytes(a, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_read_free(a);
archive_write_free(ext);
exit(cpio->return_value);
}
/*
* Exits if there's a fatal error. Returns ARCHIVE_OK
* if everything is kosher.
*/
static int
extract_data(struct archive *ar, struct archive *aw)
{
int r;
size_t size;
const void *block;
int64_t offset;
for (;;) {
r = archive_read_data_block(ar, &block, &size, &offset);
if (r == ARCHIVE_EOF)
return (ARCHIVE_OK);
if (r != ARCHIVE_OK) {
lafe_warnc(archive_errno(ar),
"%s", archive_error_string(ar));
exit(1);
}
r = (int)archive_write_data_block(aw, block, size, offset);
if (r != ARCHIVE_OK) {
lafe_warnc(archive_errno(aw),
"%s", archive_error_string(aw));
return (r);
}
}
}
static void
mode_list(struct cpio *cpio)
{
struct archive *a;
struct archive_entry *entry;
int r;
a = archive_read_new();
if (a == NULL)
lafe_errc(1, 0, "Couldn't allocate archive object");
archive_read_support_filter_all(a);
archive_read_support_format_all(a);
if (cpio->passphrase != NULL)
r = archive_read_add_passphrase(a, cpio->passphrase);
else
r = archive_read_set_passphrase_callback(a, cpio,
&passphrase_callback);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
if (archive_read_open_filename(a, cpio->filename,
cpio->bytes_per_block))
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
for (;;) {
r = archive_read_next_header(a, &entry);
if (r == ARCHIVE_EOF)
break;
if (r != ARCHIVE_OK) {
lafe_errc(1, archive_errno(a),
"%s", archive_error_string(a));
}
if (archive_match_path_excluded(cpio->matching, entry))
continue;
if (cpio->verbose)
list_item_verbose(cpio, entry);
else
fprintf(stdout, "%s\n", archive_entry_pathname(entry));
}
r = archive_read_close(a);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(a));
if (!cpio->quiet) {
int64_t blocks = (archive_filter_bytes(a, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_read_free(a);
exit(0);
}
/*
* Display information about the current file.
*
* The format here roughly duplicates the output of 'ls -l'.
* This is based on SUSv2, where 'tar tv' is documented as
* listing additional information in an "unspecified format,"
* and 'pax -l' is documented as using the same format as 'ls -l'.
*/
static void
list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
{
char size[32];
char date[32];
char uids[16], gids[16];
const char *uname, *gname;
FILE *out = stdout;
const char *fmt;
time_t mtime;
static time_t now;
if (!now)
time(&now);
if (cpio->option_numeric_uid_gid) {
/* Format numeric uid/gid for display. */
strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
uname = uids;
strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
gname = gids;
} else {
/* Use uname if it's present, else lookup name from uid. */
uname = archive_entry_uname(entry);
if (uname == NULL)
uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
/* Use gname if it's present, else lookup name from gid. */
gname = archive_entry_gname(entry);
if (gname == NULL)
gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
}
/* Print device number or file size. */
if (archive_entry_filetype(entry) == AE_IFCHR
|| archive_entry_filetype(entry) == AE_IFBLK) {
snprintf(size, sizeof(size), "%lu,%lu",
(unsigned long)archive_entry_rdevmajor(entry),
(unsigned long)archive_entry_rdevminor(entry));
} else {
strcpy(size, cpio_i64toa(archive_entry_size(entry)));
}
/* Format the time using 'ls -l' conventions. */
mtime = archive_entry_mtime(entry);
#if defined(_WIN32) && !defined(__CYGWIN__)
/* Windows' strftime function does not support %e format. */
if (mtime - now > 365*86400/2
|| mtime - now < -365*86400/2)
fmt = cpio->day_first ? "%d %b %Y" : "%b %d %Y";
else
fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
#else
if (mtime - now > 365*86400/2
|| mtime - now < -365*86400/2)
fmt = cpio->day_first ? "%e %b %Y" : "%b %e %Y";
else
fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
#endif
strftime(date, sizeof(date), fmt, localtime(&mtime));
fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
archive_entry_strmode(entry),
archive_entry_nlink(entry),
uname, gname, size, date,
archive_entry_pathname(entry));
/* Extra information for links. */
if (archive_entry_hardlink(entry)) /* Hard link */
fprintf(out, " link to %s", archive_entry_hardlink(entry));
else if (archive_entry_symlink(entry)) /* Symbolic link */
fprintf(out, " -> %s", archive_entry_symlink(entry));
fprintf(out, "\n");
}
static void
mode_pass(struct cpio *cpio, const char *destdir)
{
struct lafe_line_reader *lr;
const char *p;
int r;
/* Ensure target dir has a trailing '/' to simplify path surgery. */
cpio->destdir = malloc(strlen(destdir) + 8);
strcpy(cpio->destdir, destdir);
if (destdir[strlen(destdir) - 1] != '/')
strcat(cpio->destdir, "/");
cpio->archive = archive_write_disk_new();
if (cpio->archive == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
cpio->linkresolver = archive_entry_linkresolver_new();
archive_write_disk_set_standard_lookup(cpio->archive);
cpio->archive_read_disk = archive_read_disk_new();
if (cpio->archive_read_disk == NULL)
lafe_errc(1, 0, "Failed to allocate archive object");
if (cpio->option_follow_links)
archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
else
archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
lr = lafe_line_reader("-", cpio->option_null);
while ((p = lafe_line_reader_next(lr)) != NULL)
file_to_archive(cpio, p);
lafe_line_reader_free(lr);
archive_entry_linkresolver_free(cpio->linkresolver);
r = archive_write_close(cpio->archive);
if (cpio->dot)
fprintf(stderr, "\n");
if (r != ARCHIVE_OK)
lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
if (!cpio->quiet) {
int64_t blocks =
(archive_filter_bytes(cpio->archive, 0) + 511)
/ 512;
fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
blocks == 1 ? "block" : "blocks");
}
archive_write_free(cpio->archive);
}
/*
* Prompt for a new name for this entry. Returns a pointer to the
* new name or NULL if the entry should not be copied. This
* implements the semantics defined in POSIX.1-1996, which specifies
* that an input of '.' means the name should be unchanged. GNU cpio
* treats '.' as a literal new name.
*/
static const char *
cpio_rename(const char *name)
{
static char buff[1024];
FILE *t;
char *p, *ret;
#if defined(_WIN32) && !defined(__CYGWIN__)
FILE *to;
t = fopen("CONIN$", "r");
if (t == NULL)
return (name);
to = fopen("CONOUT$", "w");
if (to == NULL) {
fclose(t);
return (name);
}
fprintf(to, "%s (Enter/./(new name))? ", name);
fclose(to);
#else
t = fopen("/dev/tty", "r+");
if (t == NULL)
return (name);
fprintf(t, "%s (Enter/./(new name))? ", name);
fflush(t);
#endif
p = fgets(buff, sizeof(buff), t);
fclose(t);
if (p == NULL)
/* End-of-file is a blank line. */
return (NULL);
while (*p == ' ' || *p == '\t')
++p;
if (*p == '\n' || *p == '\0')
/* Empty line. */
return (NULL);
if (*p == '.' && p[1] == '\n')
/* Single period preserves original name. */
return (name);
ret = p;
/* Trim the final newline. */
while (*p != '\0' && *p != '\n')
++p;
/* Overwrite the final \n with a null character. */
*p = '\0';
return (ret);
}
static void
free_cache(struct name_cache *cache)
{
size_t i;
if (cache != NULL) {
for (i = 0; i < cache->size; i++)
free(cache->cache[i].name);
free(cache);
}
}
/*
* Lookup uname/gname from uid/gid, return NULL if no match.
*/
static const char *
lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
{
char asnum[16];
struct name_cache *cache;
const char *name;
int slot;
if (*name_cache_variable == NULL) {
*name_cache_variable = malloc(sizeof(struct name_cache));
if (*name_cache_variable == NULL)
lafe_errc(1, ENOMEM, "No more memory");
memset(*name_cache_variable, 0, sizeof(struct name_cache));
(*name_cache_variable)->size = name_cache_size;
}
cache = *name_cache_variable;
cache->probes++;
slot = id % cache->size;
if (cache->cache[slot].name != NULL) {
if (cache->cache[slot].id == id) {
cache->hits++;
return (cache->cache[slot].name);
}
free(cache->cache[slot].name);
cache->cache[slot].name = NULL;
}
if (lookup_fn(cpio, &name, id) == 0) {
if (name == NULL || name[0] == '\0') {
/* If lookup failed, format it as a number. */
snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
name = asnum;
}
cache->cache[slot].name = strdup(name);
if (cache->cache[slot].name != NULL) {
cache->cache[slot].id = id;
return (cache->cache[slot].name);
}
/*
* Conveniently, NULL marks an empty slot, so
* if the strdup() fails, we've just failed to
* cache it. No recovery necessary.
*/
}
return (NULL);
}
static const char *
lookup_uname(struct cpio *cpio, uid_t uid)
{
return (lookup_name(cpio, &cpio->uname_cache,
&lookup_uname_helper, (id_t)uid));
}
static int
lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
{
struct passwd *pwent;
(void)cpio; /* UNUSED */
errno = 0;
pwent = getpwuid((uid_t)id);
if (pwent == NULL) {
*name = NULL;
if (errno != 0 && errno != ENOENT)
lafe_warnc(errno, "getpwuid(%s) failed",
cpio_i64toa((int64_t)id));
return (errno);
}
*name = pwent->pw_name;
return (0);
}
static const char *
lookup_gname(struct cpio *cpio, gid_t gid)
{
return (lookup_name(cpio, &cpio->gname_cache,
&lookup_gname_helper, (id_t)gid));
}
static int
lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
{
struct group *grent;
(void)cpio; /* UNUSED */
errno = 0;
grent = getgrgid((gid_t)id);
if (grent == NULL) {
*name = NULL;
if (errno != 0)
lafe_warnc(errno, "getgrgid(%s) failed",
cpio_i64toa((int64_t)id));
return (errno);
}
*name = grent->gr_name;
return (0);
}
/*
* It would be nice to just use printf() for formatting large numbers,
* but the compatibility problems are a big headache. Hence the
* following simple utility function.
*/
const char *
cpio_i64toa(int64_t n0)
{
/* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
* We also need 1 byte for '-' and 1 for '\0'.
*/
static char buff[22];
int64_t n = n0 < 0 ? -n0 : n0;
char *p = buff + sizeof(buff);
*--p = '\0';
do {
*--p = '0' + (int)(n % 10);
n /= 10;
} while (n > 0);
if (n0 < 0)
*--p = '-';
return p;
}
#define PPBUFF_SIZE 1024
static const char *
passphrase_callback(struct archive *a, void *_client_data)
{
struct cpio *cpio = (struct cpio *)_client_data;
(void)a; /* UNUSED */
if (cpio->ppbuff == NULL) {
cpio->ppbuff = malloc(PPBUFF_SIZE);
if (cpio->ppbuff == NULL)
lafe_errc(1, errno, "Out of memory");
}
return lafe_readpassphrase("Enter passphrase:",
cpio->ppbuff, PPBUFF_SIZE);
}
static void
passphrase_free(char *ppbuff)
{
if (ppbuff != NULL) {
memset(ppbuff, 0, PPBUFF_SIZE);
free(ppbuff);
}
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1520_1 |
crossvul-cpp_data_bad_422_1 | #ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mspack.h>
#include <ctype.h>
#include <sys/stat.h>
#include <error.h>
#if HAVE_MKDIR
# if MKDIR_TAKES_ONE_ARG
# define mkdir(a, b) mkdir(a)
# endif
#else
# if HAVE__MKDIR
# define mkdir(a, b) _mkdir(a)
# else
# error "Don't know how to create a directory on this system."
# endif
#endif
mode_t user_umask;
#define FILENAME ".test.chmx"
/**
* Ensures that all directory components in a filepath exist. New directory
* components are created, if necessary.
*
* @param path the filepath to check
* @return non-zero if all directory components in a filepath exist, zero
* if components do not exist and cannot be created
*/
static int ensure_filepath(char *path) {
struct stat st_buf;
char *p;
int ok;
for (p = &path[1]; *p; p++) {
if (*p != '/') continue;
*p = '\0';
ok = (stat(path, &st_buf) == 0) && S_ISDIR(st_buf.st_mode);
if (!ok) ok = (mkdir(path, 0777 & ~user_umask) == 0);
*p = '/';
if (!ok) return 0;
}
return 1;
}
/**
* Creates a UNIX filename from the internal CAB filename and the given
* parameters.
*
* @param fname the internal CAB filename.
* @param dir a directory path to prepend to the output filename.
* @param lower if non-zero, filename should be made lower-case.
* @param isunix if zero, MS-DOS path seperators are used in the internal
* CAB filename. If non-zero, UNIX path seperators are used.
* @param utf8 if non-zero, the internal CAB filename is encoded in UTF8.
* @return a freshly allocated and created filename, or NULL if there was
* not enough memory.
* @see unix_path_seperators()
*/
static char *create_output_name(unsigned char *fname, unsigned char *dir,
int lower, int isunix, int utf8)
{
unsigned char *p, *name, c, *fe, sep, slash;
unsigned int x;
sep = (isunix) ? '/' : '\\'; /* the path-seperator */
slash = (isunix) ? '\\' : '/'; /* the other slash */
/* length of filename */
x = strlen((char *) fname);
/* UTF8 worst case scenario: tolower() expands all chars from 1 to 3 bytes */
if (utf8) x *= 3;
/* length of output directory */
if (dir) x += strlen((char *) dir);
if (!(name = (unsigned char *) malloc(x + 2))) {
fprintf(stderr, "out of memory!\n");
return NULL;
}
/* start with blank name */
*name = '\0';
/* add output directory if needed */
if (dir) {
strcpy((char *) name, (char *) dir);
strcat((char *) name, "/");
}
/* remove leading slashes */
while (*fname == sep) fname++;
/* copy from fi->filename to new name, converting MS-DOS slashes to UNIX
* slashes as we go. Also lowercases characters if needed.
*/
p = &name[strlen((char *)name)];
fe = &fname[strlen((char *)fname)];
if (utf8) {
/* UTF8 translates two-byte unicode characters into 1, 2 or 3 bytes.
* %000000000xxxxxxx -> %0xxxxxxx
* %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy
* %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz
*
* Therefore, the inverse is as follows:
* First char:
* 0x00 - 0x7F = one byte char
* 0x80 - 0xBF = invalid
* 0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid)
* 0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid)
* 0xF0 - 0xFF = invalid
*/
do {
if (fname >= fe) {
free(name);
return NULL;
}
/* get next UTF8 char */
if ((c = *fname++) < 0x80) x = c;
else {
if ((c >= 0xC0) && (c < 0xE0)) {
x = (c & 0x1F) << 6;
x |= *fname++ & 0x3F;
}
else if ((c >= 0xE0) && (c < 0xF0)) {
x = (c & 0xF) << 12;
x |= (*fname++ & 0x3F) << 6;
x |= *fname++ & 0x3F;
}
else x = '?';
}
/* whatever is the path seperator -> '/'
* whatever is the other slash -> '\\'
* otherwise, if lower is set, the lowercase version */
if (x == sep) x = '/';
else if (x == slash) x = '\\';
else if (lower) x = (unsigned int) tolower((int) x);
/* integer back to UTF8 */
if (x < 0x80) {
*p++ = (unsigned char) x;
}
else if (x < 0x800) {
*p++ = 0xC0 | (x >> 6);
*p++ = 0x80 | (x & 0x3F);
}
else {
*p++ = 0xE0 | (x >> 12);
*p++ = 0x80 | ((x >> 6) & 0x3F);
*p++ = 0x80 | (x & 0x3F);
}
} while (x);
}
else {
/* regular non-utf8 version */
do {
c = *fname++;
if (c == sep) c = '/';
else if (c == slash) c = '\\';
else if (lower) c = (unsigned char) tolower((int) c);
} while ((*p++ = c));
}
return (char *) name;
}
static int sortfunc(const void *a, const void *b) {
off_t diff =
((* ((struct mschmd_file **) a))->offset) -
((* ((struct mschmd_file **) b))->offset);
return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0);
}
int main(int argc, char *argv[]) {
struct mschm_decompressor *chmd;
struct mschmd_header *chm;
struct mschmd_file *file, **f;
unsigned int numf, i;
setbuf(stdout, NULL);
setbuf(stderr, NULL);
user_umask = umask(0); umask(user_umask);
MSPACK_SYS_SELFTEST(i);
if (i) return 0;
if ((chmd = mspack_create_chm_decompressor(NULL))) {
for (argv++; *argv; argv++) {
printf("%s\n", *argv);
if ((chm = chmd->open(chmd, *argv))) {
/* build an ordered list of files for maximum extraction speed */
for (numf=0, file=chm->files; file; file = file->next) numf++;
if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) {
for (i=0, file=chm->files; file; file = file->next) f[i++] = file;
qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc);
for (i = 0; i < numf; i++) {
char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0);
printf("Extracting %s\n", outname);
ensure_filepath(outname);
if (chmd->extract(chmd, f[i], outname)) {
printf("%s: extract error on \"%s\": %s\n",
*argv, f[i]->filename, ERROR(chmd));
}
free(outname);
}
free(f);
}
chmd->close(chmd, chm);
}
else {
printf("%s: can't open -- %s\n", *argv, ERROR(chmd));
}
}
mspack_destroy_chm_decompressor(chmd);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_422_1 |
crossvul-cpp_data_bad_1567_0 | /*
Copyright (C) 2010 ABRT team
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, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "problem_api.h"
#include "libabrt.h"
/* Maximal length of backtrace. */
#define MAX_BACKTRACE_SIZE (1024*1024)
/* Amount of data received from one client for a message before reporting error. */
#define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE)
/* Maximal number of characters read from socket at once. */
#define INPUT_BUFFER_SIZE (8*1024)
/* We exit after this many seconds */
#define TIMEOUT 10
/*
Unix socket in ABRT daemon for creating new dump directories.
Why to use socket for creating dump dirs? Security. When a Python
script throws unexpected exception, ABRT handler catches it, running
as a part of that broken Python application. The application is running
with certain SELinux privileges, for example it can not execute other
programs, or to create files in /var/cache or anything else required
to properly fill a problem directory. Adding these privileges to every
application would weaken the security.
The most suitable solution is for the Python application
to open a socket where ABRT daemon is listening, write all relevant
data to that socket, and close it. ABRT daemon handles the rest.
** Protocol
Initializing new dump:
open /var/run/abrt.socket
Providing dump data (hook writes to the socket):
MANDATORY ITEMS:
-> "PID="
number 0 - PID_MAX (/proc/sys/kernel/pid_max)
\0
-> "EXECUTABLE="
string
\0
-> "BACKTRACE="
string
\0
-> "ANALYZER="
string
\0
-> "BASENAME="
string (no slashes)
\0
-> "REASON="
string
\0
You can send more messages using the same KEY=value format.
*/
static unsigned total_bytes_read = 0;
static uid_t client_uid = (uid_t)-1L;
static bool dir_is_in_dump_location(const char *dump_dir_name)
{
unsigned len = strlen(g_settings_dump_location);
if (strncmp(dump_dir_name, g_settings_dump_location, len) == 0
&& dump_dir_name[len] == '/'
/* must not contain "/." anywhere (IOW: disallow ".." component) */
&& !strstr(dump_dir_name + len, "/.")
) {
return 1;
}
return 0;
}
/* Remove dump dir */
static int delete_path(const char *dump_dir_name)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dump_dir_name))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location);
return 400; /* Bad Request */
}
if (!dump_dir_accessible_by_uid(dump_dir_name, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dump_dir_name);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid);
return 403; /* Forbidden */
}
delete_dump_dir(dump_dir_name);
return 0; /* success */
}
static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp)
{
char *args[7];
args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event";
/* Do not forward ASK_* messages to parent*/
args[1] = (char *) "-i";
args[2] = (char *) "-e";
args[3] = (char *) event_name;
args[4] = (char *) "--";
args[5] = (char *) dump_dir_name;
args[6] = NULL;
int pipeout[2];
int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT;
VERB1 flags &= ~EXECFLG_QUIET;
char *env_vec[2];
/* Intercept ASK_* messages in Client API -> don't wait for user response */
env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1");
env_vec[1] = NULL;
pid_t child = fork_execv_on_steroids(flags, args, pipeout,
env_vec, /*dir:*/ NULL,
/*uid(unused):*/ 0);
if (fdp)
*fdp = pipeout[0];
return child;
}
static int run_post_create(const char *dirname)
{
/* If doesn't start with "g_settings_dump_location/"... */
if (!dir_is_in_dump_location(dirname))
{
/* Then refuse to operate on it (someone is attacking us??) */
error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location);
return 400; /* Bad Request */
}
if (g_settings_privatereports)
{
struct stat statbuf;
if (lstat(dirname, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
{
error_msg("Path '%s' isn't directory", dirname);
return 404; /* Not Found */
}
/* Get ABRT's group gid */
struct group *gr = getgrnam("abrt");
if (!gr)
{
error_msg("Group 'abrt' does not exist");
return 500;
}
if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname);
return 403;
}
struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY);
const bool complete = dd && problem_dump_dir_is_complete(dd);
dd_close(dd);
if (complete)
{
error_msg("Problem directory '%s' has already been processed", dirname);
return 403;
}
}
else if (!dump_dir_accessible_by_uid(dirname, client_uid))
{
if (errno == ENOTDIR)
{
error_msg("Path '%s' isn't problem directory", dirname);
return 404; /* Not Found */
}
error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid);
return 403; /* Forbidden */
}
int child_stdout_fd;
int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd);
char *dup_of_dir = NULL;
struct strbuf *cmd_output = strbuf_new();
bool child_is_post_create = 1; /* else it is a notify child */
read_child_output:
//log("Reading from event fd %d", child_stdout_fd);
/* Read streamed data and split lines */
for (;;)
{
char buf[250]; /* usually we get one line, no need to have big buf */
errno = 0;
int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1);
if (r <= 0)
break;
buf[r] = '\0';
/* split lines in the current buffer */
char *raw = buf;
char *newline;
while ((newline = strchr(raw, '\n')) != NULL)
{
*newline = '\0';
strbuf_append_str(cmd_output, raw);
char *msg = cmd_output->buf;
/* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */
log("%s", msg);
if (child_is_post_create
&& prefixcmp(msg, "DUP_OF_DIR: ") == 0
) {
free(dup_of_dir);
dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: "));
}
strbuf_clear(cmd_output);
/* jump to next line */
raw = newline + 1;
}
/* beginning of next line. the line continues by next read */
strbuf_append_str(cmd_output, raw);
}
/* EOF/error */
/* Wait for child to actually exit, collect status */
int status = 0;
if (safe_waitpid(child_pid, &status, 0) <= 0)
/* should not happen */
perror_msg("waitpid(%d)", child_pid);
/* If it was a "notify[-dup]" event, then we're done */
if (!child_is_post_create)
goto ret;
/* exit 0 means "this is a good, non-dup dir" */
/* exit with 1 + "DUP_OF_DIR: dir" string => dup */
if (status != 0)
{
if (WIFSIGNALED(status))
{
log("'post-create' on '%s' killed by signal %d",
dirname, WTERMSIG(status));
goto delete_bad_dir;
}
/* else: it is WIFEXITED(status) */
if (!dup_of_dir)
{
log("'post-create' on '%s' exited with %d",
dirname, WEXITSTATUS(status));
goto delete_bad_dir;
}
}
const char *work_dir = (dup_of_dir ? dup_of_dir : dirname);
/* Load problem_data (from the *first dir* if this one is a dup) */
struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0);
if (!dd)
/* dd_opendir already emitted error msg */
goto delete_bad_dir;
/* Update count */
char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT);
unsigned long count = strtoul(count_str, NULL, 10);
/* Don't increase crash count if we are working with newly uploaded
* directory (remote crash) which already has its crash count set.
*/
if ((status != 0 && dup_of_dir) || count == 0)
{
count++;
char new_count_str[sizeof(long)*3 + 2];
sprintf(new_count_str, "%lu", count);
dd_save_text(dd, FILENAME_COUNT, new_count_str);
/* This condition can be simplified to either
* (status * != 0 && * dup_of_dir) or (count == 1). But the
* chosen form is much more reliable and safe. We must not call
* dd_opendir() to locked dd otherwise we go into a deadlock.
*/
if (strcmp(dd->dd_dirname, dirname) != 0)
{
/* Update the last occurrence file by the time file of the new problem */
struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY);
char *last_ocr = NULL;
if (new_dd)
{
/* TIME must exists in a valid dump directory but we don't want to die
* due to broken duplicated dump directory */
last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME,
DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT);
dd_close(new_dd);
}
else
{ /* dd_opendir() already produced a message with good information about failure */
error_msg("Can't read the last occurrence file from the new dump directory.");
}
if (!last_ocr)
{ /* the new dump directory may lie in the dump location for some time */
log("Using current time for the last occurrence file which may be incorrect.");
time_t t = time(NULL);
last_ocr = xasprintf("%lu", (long)t);
}
dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr);
free(last_ocr);
}
}
/* Reset mode/uig/gid to correct values for all files created by event run */
dd_sanitize_mode_and_owner(dd);
dd_close(dd);
if (!dup_of_dir)
log_notice("New problem directory %s, processing", work_dir);
else
{
log_warning("Deleting problem directory %s (dup of %s)",
strrchr(dirname, '/') + 1,
strrchr(dup_of_dir, '/') + 1);
delete_dump_dir(dirname);
}
/* Run "notify[-dup]" event */
int fd;
child_pid = spawn_event_handler_child(
work_dir,
(dup_of_dir ? "notify-dup" : "notify"),
&fd
);
//log("Started notify, fd %d -> %d", fd, child_stdout_fd);
xmove_fd(fd, child_stdout_fd);
child_is_post_create = 0;
strbuf_clear(cmd_output);
free(dup_of_dir);
dup_of_dir = NULL;
goto read_child_output;
delete_bad_dir:
log_warning("Deleting problem directory '%s'", dirname);
delete_dump_dir(dirname);
ret:
strbuf_free(cmd_output);
free(dup_of_dir);
close(child_stdout_fd);
return 0;
}
/* Create a new problem directory from client session.
* Caller must ensure that all fields in struct client
* are properly filled.
*/
static int create_problem_dir(GHashTable *problem_info, unsigned pid)
{
/* Exit if free space is less than 1/4 of MaxCrashReportsSize */
if (g_settings_nMaxCrashReportsSize > 0)
{
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
exit(1);
}
/* Create temp directory with the problem data.
* This directory is renamed to final directory name after
* all files have been stored into it.
*/
gchar *dir_basename = g_hash_table_lookup(problem_info, "basename");
if (!dir_basename)
dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE);
char *path = xasprintf("%s/%s-%s-%u.new",
g_settings_dump_location,
dir_basename,
iso_date_string(NULL),
pid);
/* This item is useless, don't save it */
g_hash_table_remove(problem_info, "basename");
/* No need to check the path length, as all variables used are limited,
* and dd_create() fails if the path is too long.
*/
struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE);
if (!dd)
{
error_msg_and_die("Error creating problem directory '%s'", path);
}
dd_create_basic_files(dd, client_uid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE);
if (!gpkey)
{
/* Obtain and save the command line. */
char *cmdline = get_cmdline(pid);
if (cmdline)
{
dd_save_text(dd, FILENAME_CMDLINE, cmdline);
free(cmdline);
}
}
/* Store id of the user whose application crashed. */
char uid_str[sizeof(long) * 3 + 2];
sprintf(uid_str, "%lu", (long)client_uid);
dd_save_text(dd, FILENAME_UID, uid_str);
GHashTableIter iter;
gpointer gpvalue;
g_hash_table_iter_init(&iter, problem_info);
while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue))
{
dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue);
}
dd_close(dd);
/* Not needing it anymore */
g_hash_table_destroy(problem_info);
/* Move the completely created problem directory
* to final directory.
*/
char *newpath = xstrndup(path, strlen(path) - strlen(".new"));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log_notice("Saved problem directory of pid %u to '%s'", pid, path);
/* We let the peer know that problem dir was created successfully
* _before_ we run potentially long-running post-create.
*/
printf("HTTP/1.1 201 Created\r\n\r\n");
fflush(NULL);
close(STDOUT_FILENO);
xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */
/* Trim old problem directories if necessary */
if (g_settings_nMaxCrashReportsSize > 0)
{
trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path);
}
run_post_create(path);
/* free(path); */
exit(0);
}
/* Checks if a string contains only printable characters. */
static gboolean printable_str(const char *str)
{
do {
if ((unsigned char)(*str) < ' ' || *str == 0x7f)
return FALSE;
str++;
} while (*str);
return TRUE;
}
static gboolean is_correct_filename(const char *value)
{
return printable_str(value) && !strchr(value, '/') && !strchr(value, '.');
}
static gboolean key_value_ok(gchar *key, gchar *value)
{
char *i;
/* check key, it has to be valid filename and will end up in the
* bugzilla */
for (i = key; *i != 0; i++)
{
if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' '))
return FALSE;
}
/* check value of 'basename', it has to be valid non-hidden directory
* name */
if (strcmp(key, "basename") == 0
|| strcmp(key, FILENAME_TYPE) == 0
)
{
if (!is_correct_filename(value))
{
error_msg("Value of '%s' ('%s') is not a valid directory name",
key, value);
return FALSE;
}
}
return TRUE;
}
/* Handles a message received from client over socket. */
static void process_message(GHashTable *problem_info, char *message)
{
gchar *key, *value;
value = strchr(message, '=');
if (value)
{
key = g_ascii_strdown(message, value - message); /* result is malloced */
//TODO: is it ok? it uses g_malloc, not malloc!
value++;
if (key_value_ok(key, value))
{
if (strcmp(key, FILENAME_UID) == 0)
{
error_msg("Ignoring value of %s, will be determined later",
FILENAME_UID);
}
else
{
g_hash_table_insert(problem_info, key, xstrdup(value));
/* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */
if (strcmp(key, FILENAME_TYPE) == 0)
g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value));
/* Prevent freeing key later: */
key = NULL;
}
}
else
{
/* should use error_msg_and_die() here? */
error_msg("Invalid key or value format: %s", message);
}
free(key);
}
else
{
/* should use error_msg_and_die() here? */
error_msg("Invalid message format: '%s'", message);
}
}
static void die_if_data_is_missing(GHashTable *problem_info)
{
gboolean missing_data = FALSE;
gchar **pstring;
static const gchar *const needed[] = {
FILENAME_TYPE,
FILENAME_REASON,
/* FILENAME_BACKTRACE, - ECC errors have no such elements */
/* FILENAME_EXECUTABLE, */
NULL
};
for (pstring = (gchar**) needed; *pstring; pstring++)
{
if (!g_hash_table_lookup(problem_info, *pstring))
{
error_msg("Element '%s' is missing", *pstring);
missing_data = TRUE;
}
}
if (missing_data)
error_msg_and_die("Some data is missing, aborting");
}
/*
* Takes hash table, looks for key FILENAME_PID and tries to convert its value
* to int.
*/
unsigned convert_pid(GHashTable *problem_info)
{
long ret;
gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID);
char *err_pos;
if (!pid_str)
error_msg_and_die("PID data is missing, aborting");
errno = 0;
ret = strtol(pid_str, &err_pos, 10);
if (errno || pid_str == err_pos || *err_pos != '\0'
|| ret > UINT_MAX || ret < 1)
error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str);
return (unsigned) ret;
}
static int perform_http_xact(void)
{
/* use free instead of g_free so that we can use xstr* functions from
* libreport/lib/xfuncs.c
*/
GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal,
free, free);
/* Read header */
char *body_start = NULL;
char *messagebuf_data = NULL;
unsigned messagebuf_len = 0;
/* Loop until EOF/error/timeout/end_of_header */
while (1)
{
messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE);
char *p = messagebuf_data + messagebuf_len;
int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE);
if (rd < 0)
{
if (errno == EINTR) /* SIGALRM? */
error_msg_and_die("Timed out");
perror_msg_and_die("read");
}
if (rd == 0)
break;
log_debug("Received %u bytes of data", rd);
messagebuf_len += rd;
total_bytes_read += rd;
if (total_bytes_read > MAX_MESSAGE_SIZE)
error_msg_and_die("Message is too long, aborting");
/* Check whether we see end of header */
/* Note: we support both [\r]\n\r\n and \n\n */
char *past_end = messagebuf_data + messagebuf_len;
if (p > messagebuf_data+1)
p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */
while (p < past_end)
{
p = memchr(p, '\n', past_end - p);
if (!p)
break;
p++;
if (p >= past_end)
break;
if (*p == '\n'
|| (*p == '\r' && p+1 < past_end && p[1] == '\n')
) {
body_start = p + 1 + (*p == '\r');
*p = '\0';
goto found_end_of_header;
}
}
} /* while (read) */
found_end_of_header: ;
log_debug("Request: %s", messagebuf_data);
/* Sanitize and analyze header.
* Header now is in messagebuf_data, NUL terminated string,
* with last empty line deleted (by placement of NUL).
* \r\n are not (yet) converted to \n, multi-line headers also
* not converted.
*/
/* First line must be "op<space>[http://host]/path<space>HTTP/n.n".
* <space> is exactly one space char.
*/
if (prefixcmp(messagebuf_data, "DELETE ") == 0)
{
messagebuf_data += strlen("DELETE ");
char *space = strchr(messagebuf_data, ' ');
if (!space || prefixcmp(space+1, "HTTP/") != 0)
return 400; /* Bad Request */
*space = '\0';
//decode_url(messagebuf_data); %20 => ' '
alarm(0);
return delete_path(messagebuf_data);
}
/* We erroneously used "PUT /" to create new problems.
* POST is the correct request in this case:
* "PUT /" implies creation or replace of resource named "/"!
* Delete PUT in 2014.
*/
if (prefixcmp(messagebuf_data, "PUT ") != 0
&& prefixcmp(messagebuf_data, "POST ") != 0
) {
return 400; /* Bad Request */
}
enum {
CREATION_NOTIFICATION,
CREATION_REQUEST,
};
int url_type;
char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */
if (prefixcmp(url, "/creation_notification ") == 0)
url_type = CREATION_NOTIFICATION;
else if (prefixcmp(url, "/ ") == 0)
url_type = CREATION_REQUEST;
else
return 400; /* Bad Request */
/* Read body */
if (!body_start)
{
log_warning("Premature EOF detected, exiting");
return 400; /* Bad Request */
}
messagebuf_len -= (body_start - messagebuf_data);
memmove(messagebuf_data, body_start, messagebuf_len);
log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data);
/* Loop until EOF/error/timeout */
while (1)
{
if (url_type == CREATION_REQUEST)
{
while (1)
{
unsigned len = strnlen(messagebuf_data, messagebuf_len);
if (len >= messagebuf_len)
break;
/* messagebuf has at least one NUL - process the line */
process_message(problem_info, messagebuf_data);
messagebuf_len -= (len + 1);
memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len);
}
}
messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1);
int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE);
if (rd < 0)
{
if (errno == EINTR) /* SIGALRM? */
error_msg_and_die("Timed out");
perror_msg_and_die("read");
}
if (rd == 0)
break;
log_debug("Received %u bytes of data", rd);
messagebuf_len += rd;
total_bytes_read += rd;
if (total_bytes_read > MAX_MESSAGE_SIZE)
error_msg_and_die("Message is too long, aborting");
}
/* Body received, EOF was seen. Don't let alarm to interrupt after this. */
alarm(0);
if (url_type == CREATION_NOTIFICATION)
{
messagebuf_data[messagebuf_len] = '\0';
return run_post_create(messagebuf_data);
}
/* Save problem dir */
int ret = 0;
unsigned pid = convert_pid(problem_info);
die_if_data_is_missing(problem_info);
char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE);
if (executable)
{
char *last_file = concat_path_file(g_settings_dump_location, "last-via-server");
int repeating_crash = check_recent_crash_file(last_file, executable);
free(last_file);
if (repeating_crash) /* Only pretend that we saved it */
goto out; /* ret is 0: "success" */
}
#if 0
//TODO:
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(problem_info);
//...the problem being that problem_info here is not a problem_data_t!
#endif
create_problem_dir(problem_info, pid);
/* does not return */
out:
g_hash_table_destroy(problem_info);
return ret; /* Used as HTTP response code */
}
static void dummy_handler(int sig_unused) {}
int main(int argc, char **argv)
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
abrt_init(argv);
/* Can't keep these strings/structs static: _() doesn't support that */
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_u = 1 << 1,
OPT_s = 1 << 2,
OPT_p = 1 << 3,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")),
OPT_BOOL( 's', NULL, NULL , _("Log to syslog")),
OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")),
OPT_END()
};
unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(opts & OPT_p);
msg_prefix = xasprintf("%s[%u]", g_progname, getpid());
if (opts & OPT_s)
{
logmode = LOGMODE_JOURNAL;
}
/* Set up timeout handling */
/* Part 1 - need this to make SIGALRM interrupt syscalls
* (as opposed to restarting them): I want read syscall to be interrupted
*/
struct sigaction sa;
/* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */
memset(&sa, 0, sizeof(sa));
sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */
sigaction(SIGALRM, &sa, NULL);
/* Part 2 - set the timeout per se */
alarm(TIMEOUT);
if (client_uid == (uid_t)-1L)
{
/* Get uid of the connected client */
struct ucred cr;
socklen_t crlen = sizeof(cr);
if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen))
perror_msg_and_die("getsockopt(SO_PEERCRED)");
if (crlen != sizeof(cr))
error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen);
client_uid = cr.uid;
}
load_abrt_conf();
int r = perform_http_xact();
if (r == 0)
r = 200;
free_abrt_conf_data();
printf("HTTP/1.1 %u \r\n\r\n", r);
return (r >= 400); /* Error if 400+ */
}
#if 0
// TODO: example of SSLed connection
#include <openssl/ssl.h>
#include <openssl/err.h>
if (flags & OPT_SSL) {
/* load key and cert files */
SSL_CTX *ctx;
SSL *ssl;
ctx = init_ssl_context();
if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0
|| SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0
) {
ERR_print_errors_fp(stderr);
error_msg_and_die("SSL certificates err\n");
}
if (!SSL_CTX_check_private_key(ctx)) {
error_msg_and_die("Private key does not match public key\n");
}
(void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
//TODO more errors?
ssl = SSL_new(ctx);
SSL_set_fd(ssl, sockfd_in);
//SSL_set_accept_state(ssl);
if (SSL_accept(ssl) == 1) {
//while whatever serve
while (serve(ssl, flags))
continue;
//TODO errors
SSL_shutdown(ssl);
}
SSL_free(ssl);
SSL_CTX_free(ctx);
} else {
while (serve(&sockfd_in, flags))
continue;
}
err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1):
read(*(int*)sock, buffer, READ_BUF-1);
if ( err < 0 ) {
//TODO handle errno || SSL_get_error(ssl,err);
break;
}
if ( err == 0 ) break;
if (!head) {
buffer[err] = '\0';
clean[i%2] = delete_cr(buffer);
cut = g_strstr_len(buffer, -1, "\n\n");
if ( cut == NULL ) {
g_string_append(headers, buffer);
} else {
g_string_append_len(headers, buffer, cut-buffer);
}
}
/* end of header section? */
if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) {
parse_head(&request, headers);
head = TRUE;
c_len = has_body(&request);
if ( c_len ) {
//if we want to read body some day - this will be the right place to begin
//malloc body append rest of the (fixed) buffer at the beginning of a body
//if clean buffer[1];
} else {
break;
}
break; //because we don't support body yet
} else if ( head == TRUE ) {
/* body-reading stuff
* read body, check content-len
* save body to request
*/
break;
} else {
// count header size
len += err;
if ( len > READ_BUF-1 ) {
//TODO header is too long
break;
}
}
i++;
}
g_string_free(headers, true); //because we allocated it
rt = generate_response(&request, &response);
/* write headers */
if ( flags & OPT_SSL ) {
//TODO err
err = SSL_write(sock, response.response_line, strlen(response.response_line));
err = SSL_write(sock, response.head->str , strlen(response.head->str));
err = SSL_write(sock, "\r\n", 2);
} else {
//TODO err
err = write(*(int*)sock, response.response_line, strlen(response.response_line));
err = write(*(int*)sock, response.head->str , strlen(response.head->str));
err = write(*(int*)sock, "\r\n", 2);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1567_0 |
crossvul-cpp_data_good_1568_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
bool allowed_problem_dir(const char *dir_name)
{
if (!dir_is_in_dump_location(dir_name))
{
error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location);
return false;
}
/* We cannot test correct permissions yet because we still need to chown
* dump directories before reporting and Chowing changes the file owner to
* the reporter, which causes this test to fail and prevents users from
* getting problem data after reporting it.
*
* Fortunately, libreport has been hardened against hard link and symbolic
* link attacks and refuses to work with such files, so this test isn't
* really necessary, however, we will use it once we get rid of the
* chowning files.
*
* abrt-server refuses to run post-create on directories that have
* incorrect owner (not "root:(abrt|root)"), incorrect permissions (other
* bits are not 0) and are complete (post-create finished). So, there is no
* way to run security sensitive event scripts (post-create) on crafted
* problem directories.
*/
#if 0
if (!dir_has_correct_permissions(dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name);
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
char *problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
int dir_fd = dd_openfd(problem_id);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
return NULL;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
close(dir_fd);
return NULL;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
close(dir_fd);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (!str_is_correct_filename(element))
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
if (!str_is_correct_filename(element))
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
int dir_fd = dd_openfd(dir_name);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", dir_name);
return_InvalidProblemDir_error(invocation, dir_name);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
close(dir_fd);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
close(dir_fd);
continue;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0);
if (dd)
{
if (dd_delete(dd) != 0)
{
error_msg("Failed to delete problem directory '%s'", dir_name);
dd_close(dd);
}
}
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_1568_0 |
crossvul-cpp_data_bad_1570_1 | /*
* Utility routines.
*
* Copyright (C) 2001 Erik Andersen
*
* 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, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "internal_libreport.h"
/* Concatenate path and filename to new allocated buffer.
* Add '/' only as needed (no duplicate // are produced).
* If path is NULL, it is assumed to be "/".
* filename should not be NULL.
*/
char *concat_path_file(const char *path, const char *filename)
{
if (!path)
path = "";
const char *end = path + strlen(path);
while (*filename == '/')
filename++;
return xasprintf("%s%s%s", path, (end != path && end[-1] != '/' ? "/" : ""), filename);
}
char *concat_path_basename(const char *path, const char *filename)
{
char *abspath = realpath(filename, NULL);
char *base = strrchr((abspath ? abspath : filename), '/');
/* If realpath failed and filename is malicious (say, "/foo/.."),
* we may end up tricked into doing some bad things. Don't allow that.
*/
char buf[sizeof("tmp-"LIBREPORT_ISO_DATE_STRING_SAMPLE"-%lu")];
if (base && base[1] != '\0' && base[1] != '.')
{
/* We have a slash and it's not "foo/" or "foo/.<something>" */
base++;
}
else
{
sprintf(buf, "tmp-%s-%lu", iso_date_string(NULL), (long)getpid());
base = buf;
}
char *name = concat_path_file(path, base);
free(abspath);
return name;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1570_1 |
crossvul-cpp_data_bad_1568_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
bool allowed_problem_dir(const char *dir_name)
{
if (!dir_is_in_dump_location(dir_name))
{
error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location);
return false;
}
/* We cannot test correct permissions yet because we still need to chown
* dump directories before reporting and Chowing changes the file owner to
* the reporter, which causes this test to fail and prevents users from
* getting problem data after reporting it.
*
* Fortunately, libreport has been hardened against hard link and symbolic
* link attacks and refuses to work with such files, so this test isn't
* really necessary, however, we will use it once we get rid of the
* chowning files.
*
* abrt-server refuses to run post-create on directories that have
* incorrect owner (not "root:(abrt|root)"), incorrect permissions (other
* bits are not 0) and are complete (post-create finished). So, there is no
* way to run security sensitive event scripts (post-create) on crafted
* problem directories.
*/
#if 0
if (!dir_has_correct_permissions(dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name);
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
char *problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
int dir_fd = dd_openfd(problem_id);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
return NULL;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
close(dir_fd);
return NULL;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
close(dir_fd);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (element == NULL || element[0] == '\0' || strlen(element) > 64)
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
int dir_fd = dd_openfd(dir_name);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", dir_name);
return_InvalidProblemDir_error(invocation, dir_name);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
close(dir_fd);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
close(dir_fd);
continue;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0);
if (dd)
{
if (dd_delete(dd) != 0)
{
error_msg("Failed to delete problem directory '%s'", dir_name);
dd_close(dd);
}
}
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1568_0 |
crossvul-cpp_data_bad_5866_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-22/c/bad_5866_0 |
crossvul-cpp_data_bad_1566_0 | #include <gio/gio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include "libabrt.h"
#include "abrt-polkit.h"
#include "abrt_glib.h"
#include <libreport/dump_dir.h>
#include "problem_api.h"
static GMainLoop *loop;
static guint g_timeout_source;
/* default, settable with -t: */
static unsigned g_timeout_value = 120;
/* ---------------------------------------------------------------------------------------------------- */
static GDBusNodeInfo *introspection_data = NULL;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='"ABRT_DBUS_IFACE"'>"
" <method name='NewProblem'>"
" <arg type='a{ss}' name='problem_data' direction='in'/>"
" <arg type='s' name='problem_id' direction='out'/>"
" </method>"
" <method name='GetProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetAllProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetForeignProblems'>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='GetInfo'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='as' name='element_names' direction='in'/>"
" <arg type='a{ss}' name='response' direction='out'/>"
" </method>"
" <method name='SetElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" </method>"
" <method name='DeleteElement'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" </method>"
" <method name='ChownProblemDir'>"
" <arg type='s' name='problem_dir' direction='in'/>"
" </method>"
" <method name='DeleteProblem'>"
" <arg type='as' name='problem_dir' direction='in'/>"
" </method>"
" <method name='FindProblemByElementInTimeRange'>"
" <arg type='s' name='element' direction='in'/>"
" <arg type='s' name='value' direction='in'/>"
" <arg type='x' name='timestamp_from' direction='in'/>"
" <arg type='x' name='timestamp_to' direction='in'/>"
" <arg type='b' name='all_users' direction='in'/>"
" <arg type='as' name='response' direction='out'/>"
" </method>"
" <method name='Quit' />"
" </interface>"
"</node>";
/* ---------------------------------------------------------------------------------------------------- */
/* forward */
static gboolean on_timeout_cb(gpointer user_data);
static void reset_timeout(void)
{
if (g_timeout_source > 0)
{
log_info("Removing timeout");
g_source_remove(g_timeout_source);
}
log_info("Setting a new timeout");
g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL);
}
static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller)
{
GError *error = NULL;
guint caller_uid;
GDBusProxy * proxy = g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
NULL,
&error);
GVariant *result = g_dbus_proxy_call_sync(proxy,
"GetConnectionUnixUser",
g_variant_new ("(s)", caller),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
if (result == NULL)
{
/* we failed to get the uid, so return (uid_t) -1 to indicate the error
*/
if (error)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
error->message);
g_error_free(error);
}
else
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidUser",
_("Unknown error"));
}
return (uid_t) -1;
}
g_variant_get(result, "(u)", &caller_uid);
g_variant_unref(result);
log_info("Caller uid: %i", caller_uid);
return caller_uid;
}
bool allowed_problem_dir(const char *dir_name)
{
if (!dir_is_in_dump_location(dir_name))
{
error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location);
return false;
}
/* We cannot test correct permissions yet because we still need to chown
* dump directories before reporting and Chowing changes the file owner to
* the reporter, which causes this test to fail and prevents users from
* getting problem data after reporting it.
*
* Fortunately, libreport has been hardened against hard link and symbolic
* link attacks and refuses to work with such files, so this test isn't
* really necessary, however, we will use it once we get rid of the
* chowning files.
*
* abrt-server refuses to run post-create on directories that have
* incorrect owner (not "root:(abrt|root)"), incorrect permissions (other
* bits are not 0) and are complete (post-create finished). So, there is no
* way to run security sensitive event scripts (post-create) on crafted
* problem directories.
*/
#if 0
if (!dir_has_correct_permissions(dir_name))
{
error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name);
return false;
}
#endif
return true;
}
static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error)
{
char *problem_id = NULL;
problem_data_t *pd = problem_data_new();
GVariantIter *iter;
g_variant_get(problem_info, "a{ss}", &iter);
gchar *key, *value;
while (g_variant_iter_loop(iter, "{ss}", &key, &value))
{
if (allowed_new_user_problem_entry(caller_uid, key, value) == false)
{
*error = xasprintf("You are not allowed to create element '%s' containing '%s'", key, value);
goto finito;
}
problem_data_add_text_editable(pd, key, value);
}
if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL)
{ /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */
log_info("Adding UID %d to problem data", caller_uid);
char buf[sizeof(uid_t) * 3 + 2];
snprintf(buf, sizeof(buf), "%d", caller_uid);
problem_data_add_text_noteditable(pd, FILENAME_UID, buf);
}
/* At least it should generate local problem identifier UUID */
problem_data_add_basics(pd);
problem_id = problem_data_save(pd);
if (problem_id)
notify_new_path(problem_id);
else if (error)
*error = xasprintf("Cannot create a new problem");
finito:
problem_data_free(pd);
return problem_id;
}
static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name)
{
char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidProblemDir",
msg);
free(msg);
}
/*
* Checks element's rights and does not open directory if element is protected.
* Checks problem's rights and does not open directory if user hasn't got
* access to a problem.
*
* Returns a dump directory opend for writing or NULL.
*
* If any operation from the above listed fails, immediately returns D-Bus
* error to a D-Bus caller.
*/
static struct dump_dir *open_directory_for_modification_of_element(
GDBusMethodInvocation *invocation,
uid_t caller_uid,
const char *problem_id,
const char *element)
{
static const char *const protected_elements[] = {
FILENAME_TIME,
FILENAME_UID,
NULL,
};
for (const char *const *protected = protected_elements; *protected; ++protected)
{
if (strcmp(*protected, element) == 0)
{
log_notice("'%s' element of '%s' can't be modified", element, problem_id);
char *error = xasprintf(_("'%s' element can't be modified"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ProtectedElement",
error);
free(error);
return NULL;
}
}
int dir_fd = dd_openfd(problem_id);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
return NULL;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("'%s' is not a valid problem directory", problem_id);
return_InvalidProblemDir_error(invocation, problem_id);
}
else
{
log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
}
close(dir_fd);
return NULL;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_id, /* flags : */ 0);
if (!dd)
{ /* This should not happen because of the access check above */
log_notice("Can't access the problem '%s' for modification", problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("Can't access the problem for modification"));
return NULL;
}
return dd;
}
/*
* Lists problems which have given element and were seen in given time interval
*/
struct field_and_time_range {
GList *list;
const char *element;
const char *value;
unsigned long timestamp_from;
unsigned long timestamp_to;
};
static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg)
{
struct field_and_time_range *me = arg;
char *field_data = dd_load_text(dd, me->element);
int brk = (strcmp(field_data, me->value) != 0);
free(field_data);
if (brk)
return 0;
field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE);
long val = atol(field_data);
free(field_data);
if (val < me->timestamp_from || val > me->timestamp_to)
return 0;
me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname));
return 0;
}
static GList *get_problem_dirs_for_element_in_time(uid_t uid,
const char *element,
const char *value,
unsigned long timestamp_from,
unsigned long timestamp_to)
{
if (timestamp_to == 0) /* not sure this is possible, but... */
timestamp_to = time(NULL);
struct field_and_time_range me = {
.list = NULL,
.element = element,
.value = value,
.timestamp_from = timestamp_from,
.timestamp_to = timestamp_to,
};
for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me);
return g_list_reverse(me.list);
}
static void handle_method_call(GDBusConnection *connection,
const gchar *caller,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
reset_timeout();
uid_t caller_uid;
GVariant *response;
caller_uid = get_caller_uid(connection, invocation, caller);
log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name);
if (caller_uid == (uid_t) -1)
return;
if (g_strcmp0(method_name, "NewProblem") == 0)
{
char *error = NULL;
char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error);
if (!problem_id)
{
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
/* else */
response = g_variant_new("(s)", problem_id);
g_dbus_method_invocation_return_value(invocation, response);
free(problem_id);
return;
}
if (g_strcmp0(method_name, "GetProblems") == 0)
{
GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
//I was told that g_dbus_method frees the response
//g_variant_unref(response);
return;
}
if (g_strcmp0(method_name, "GetAllProblems") == 0)
{
/*
- so, we have UID,
- if it's 0, then we don't have to check anything and just return all directories
- if uid != 0 then we want to ask for authorization
*/
if (caller_uid != 0)
{
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
}
GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "GetForeignProblems") == 0)
{
GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "ChownProblemDir") == 0)
{
const gchar *problem_dir;
g_variant_get(parameters, "(&s)", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid);
if (ddstat < 0)
{
if (errno == ENOTDIR)
{
log_notice("requested directory does not exist '%s'", problem_dir);
}
else
{
perror_msg("can't get stat of '%s'", problem_dir);
}
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (ddstat & DD_STAT_OWNED_BY_UID)
{ //caller seems to be in group with access to this dir, so no action needed
log_notice("caller has access to the requested directory %s", problem_dir);
g_dbus_method_invocation_return_value(invocation, NULL);
close(dir_fd);
return;
}
if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 &&
polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int chown_res = dd_chown(dd, caller_uid);
if (chown_res != 0)
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.ChownError",
_("Chowning directory failed. Check system logs for more details."));
else
g_dbus_method_invocation_return_value(invocation, NULL);
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "GetInfo") == 0)
{
/* Parameter tuple is (sas) */
/* Get 1st param - problem dir name */
const gchar *problem_dir;
g_variant_get_child(parameters, 0, "&s", &problem_dir);
log_notice("problem_dir:'%s'", problem_dir);
if (!allowed_problem_dir(problem_dir))
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
int dir_fd = dd_openfd(problem_dir);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", problem_dir);
return_InvalidProblemDir_error(invocation, problem_dir);
close(dir_fd);
return;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{
log_notice("not authorized");
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.AuthFailure",
_("Not Authorized"));
close(dir_fd);
return;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES);
if (!dd)
{
return_InvalidProblemDir_error(invocation, problem_dir);
return;
}
/* Get 2nd param - vector of element names */
GVariant *array = g_variant_get_child_value(parameters, 1);
GList *elements = string_list_from_variant(array);
g_variant_unref(array);
GVariantBuilder *builder = NULL;
for (GList *l = elements; l; l = l->next)
{
const char *element_name = (const char*)l->data;
char *value = dd_load_text_ext(dd, element_name, 0
| DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE
| DD_FAIL_QUIETLY_ENOENT
| DD_FAIL_QUIETLY_EACCES);
log_notice("element '%s' %s", element_name, value ? "fetched" : "not found");
if (value)
{
if (!builder)
builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
/* g_variant_builder_add makes a copy. No need to xstrdup here */
g_variant_builder_add(builder, "{ss}", element_name, value);
free(value);
}
}
list_free_with_free(elements);
dd_close(dd);
/* It is OK to call g_variant_new("(a{ss})", NULL) because */
/* G_VARIANT_TYPE_TUPLE allows NULL value */
GVariant *response = g_variant_new("(a{ss})", builder);
if (builder)
g_variant_builder_unref(builder);
log_info("GetInfo: returning value for '%s'", problem_dir);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "SetElement") == 0)
{
const char *problem_id;
const char *element;
const char *value;
g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value);
if (!str_is_correct_filename(element))
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
/* Is it good idea to make it static? Is it possible to change the max size while a single run? */
const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024);
const long item_size = dd_get_item_size(dd, element);
if (item_size < 0)
{
log_notice("Can't get size of '%s/%s'", problem_id, element);
char *error = xasprintf(_("Can't get size of '%s'"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
return;
}
const double requested_size = (double)strlen(value) - item_size;
/* Don't want to check the size limit in case of reducing of size */
if (requested_size > 0
&& requested_size > (max_dir_size - get_dirsize(g_settings_dump_location)))
{
log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
_("No problem space left"));
}
else
{
dd_save_text(dd, element, value);
g_dbus_method_invocation_return_value(invocation, NULL);
}
dd_close(dd);
return;
}
if (g_strcmp0(method_name, "DeleteElement") == 0)
{
const char *problem_id;
const char *element;
g_variant_get(parameters, "(&s&s)", &problem_id, &element);
if (!str_is_correct_filename(element))
{
log_notice("'%s' is not a valid element name of '%s'", element, problem_id);
char *error = xasprintf(_("'%s' is not a valid element name"), element);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.InvalidElement",
error);
free(error);
return;
}
struct dump_dir *dd = open_directory_for_modification_of_element(
invocation, caller_uid, problem_id, element);
if (!dd)
/* Already logged from open_directory_for_modification_of_element() */
return;
const int res = dd_delete_item(dd, element);
dd_close(dd);
if (res != 0)
{
log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id);
char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id);
g_dbus_method_invocation_return_dbus_error(invocation,
"org.freedesktop.problems.Failure",
error);
free(error);
return;
}
g_dbus_method_invocation_return_value(invocation, NULL);
return;
}
if (g_strcmp0(method_name, "DeleteProblem") == 0)
{
/* Dbus parameters are always tuples.
* In this case, it's (as) - a tuple of one element (array of strings).
* Need to fetch the array:
*/
GVariant *array = g_variant_get_child_value(parameters, 0);
GList *problem_dirs = string_list_from_variant(array);
g_variant_unref(array);
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
log_notice("dir_name:'%s'", dir_name);
if (!allowed_problem_dir(dir_name))
{
return_InvalidProblemDir_error(invocation, dir_name);
goto ret;
}
}
for (GList *l = problem_dirs; l; l = l->next)
{
const char *dir_name = (const char*)l->data;
int dir_fd = dd_openfd(dir_name);
if (dir_fd < 0)
{
perror_msg("can't open problem directory '%s'", dir_name);
return_InvalidProblemDir_error(invocation, dir_name);
return;
}
if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid))
{
if (errno == ENOTDIR)
{
log_notice("Requested directory does not exist '%s'", dir_name);
close(dir_fd);
continue;
}
if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes)
{ // if user didn't provide correct credentials, just move to the next dir
close(dir_fd);
continue;
}
}
struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0);
if (dd)
{
if (dd_delete(dd) != 0)
{
error_msg("Failed to delete problem directory '%s'", dir_name);
dd_close(dd);
}
}
}
g_dbus_method_invocation_return_value(invocation, NULL);
ret:
list_free_with_free(problem_dirs);
return;
}
if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0)
{
const gchar *element;
const gchar *value;
glong timestamp_from;
glong timestamp_to;
gboolean all;
g_variant_get_child(parameters, 0, "&s", &element);
g_variant_get_child(parameters, 1, "&s", &value);
g_variant_get_child(parameters, 2, "x", ×tamp_from);
g_variant_get_child(parameters, 3, "x", ×tamp_to);
g_variant_get_child(parameters, 4, "b", &all);
if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes)
caller_uid = 0;
GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from,
timestamp_to);
response = variant_from_string_list(dirs);
list_free_with_free(dirs);
g_dbus_method_invocation_return_value(invocation, response);
return;
}
if (g_strcmp0(method_name, "Quit") == 0)
{
g_dbus_method_invocation_return_value(invocation, NULL);
g_main_loop_quit(loop);
return;
}
}
static gboolean on_timeout_cb(gpointer user_data)
{
g_main_loop_quit(loop);
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable =
{
.method_call = handle_method_call,
.get_property = NULL,
.set_property = NULL,
};
static void on_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
guint registration_id;
registration_id = g_dbus_connection_register_object(connection,
ABRT_DBUS_OBJECT,
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
reset_timeout();
}
/* not used
static void on_name_acquired (GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
}
*/
static void on_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
g_print(_("The name '%s' has been lost, please check if other "
"service owning the name is not running.\n"), name);
exit(1);
}
int main(int argc, char *argv[])
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
guint owner_id;
abrt_init(argv);
const char *program_usage_string = _(
"& [options]"
);
enum {
OPT_v = 1 << 0,
OPT_t = 1 << 1,
};
/* Keep enum above and order of options below in sync! */
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")),
OPT_END()
};
/*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string);
export_abrt_envvars(0);
/* When dbus daemon starts us, it doesn't set PATH
* (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE).
* In this case, set something sane:
*/
const char *env_path = getenv("PATH");
if (!env_path || !env_path[0])
putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin");
msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */
if (getuid() != 0)
error_msg_and_die(_("This program must be run as root."));
glib_init();
/* We are lazy here - we don't want to manually provide
* the introspection data structures - so we just build
* them from XML.
*/
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
ABRT_DBUS_NAME,
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired,
NULL,
on_name_lost,
NULL,
NULL);
/* initialize the g_settings_dump_location */
load_abrt_conf();
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
log_notice("Cleaning up");
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
free_abrt_conf_data();
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_1566_0 |
crossvul-cpp_data_good_4261_0 | /* Common methods shared between FTP and TFTP engines
*
* Copyright (c) 2014-2019 Joachim Nilsson <troglobit@gmail.com>
*
* 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.
*/
#include "uftpd.h"
int chrooted = 0;
/* Protect against common directory traversal attacks, for details see
* https://en.wikipedia.org/wiki/Directory_traversal_attack
*
* Example: /srv/ftp/ ../../etc/passwd => /etc/passwd
* .~~~~~~~~ .~~~~~~~~~
* / /
* Server dir ------' /
* User input ---------------'
*
* Forced dir ------> /srv/ftp/etc
*/
char *compose_path(ctrl_t *ctrl, char *path)
{
struct stat st;
static char rpath[PATH_MAX];
char *name, *ptr;
char dir[PATH_MAX] = { 0 };
strlcpy(dir, ctrl->cwd, sizeof(dir));
DBG("Compose path from cwd: %s, arg: %s", ctrl->cwd, path ?: "");
if (!path || !strlen(path))
goto check;
if (path) {
if (path[0] != '/') {
if (dir[strlen(dir) - 1] != '/')
strlcat(dir, "/", sizeof(dir));
}
strlcat(dir, path, sizeof(dir));
}
check:
while ((ptr = strstr(dir, "//")))
memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);
if (!chrooted) {
size_t len = strlen(home);
DBG("Server path from CWD: %s", dir);
if (len > 0 && home[len - 1] == '/')
len--;
memmove(dir + len, dir, strlen(dir) + 1);
memcpy(dir, home, len);
DBG("Resulting non-chroot path: %s", dir);
}
/*
* Handle directories slightly differently, since dirname() on a
* directory returns the parent directory. So, just squash ..
*/
if (!stat(dir, &st) && S_ISDIR(st.st_mode)) {
if (!realpath(dir, rpath))
return NULL;
} else {
/*
* Check realpath() of directory containing the file, a
* STOR may want to save a new file. Then append the
* file and return it.
*/
name = basename(path);
ptr = dirname(dir);
memset(rpath, 0, sizeof(rpath));
if (!realpath(ptr, rpath)) {
INFO("Failed realpath(%s): %m", ptr);
return NULL;
}
if (rpath[1] != 0)
strlcat(rpath, "/", sizeof(rpath));
strlcat(rpath, name, sizeof(rpath));
}
if (!chrooted && strncmp(rpath, home, strlen(home))) {
DBG("Failed non-chroot dir:%s vs home:%s", dir, home);
return NULL;
}
return rpath;
}
char *compose_abspath(ctrl_t *ctrl, char *path)
{
char *ptr;
char cwd[sizeof(ctrl->cwd)];
if (path && path[0] == '/') {
strlcpy(cwd, ctrl->cwd, sizeof(cwd));
memset(ctrl->cwd, 0, sizeof(ctrl->cwd));
}
ptr = compose_path(ctrl, path);
if (path && path[0] == '/')
strlcpy(ctrl->cwd, cwd, sizeof(ctrl->cwd));
return ptr;
}
int set_nonblock(int fd)
{
int flags;
flags = fcntl(fd, F_GETFL, 0);
if (!flags)
(void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
return fd;
}
int open_socket(int port, int type, char *desc)
{
int sd, err, val = 1;
socklen_t len = sizeof(struct sockaddr);
struct sockaddr_in server;
sd = socket(AF_INET, type | SOCK_NONBLOCK, 0);
if (sd < 0) {
WARN(errno, "Failed creating %s server socket", desc);
return -1;
}
err = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
if (err != 0)
WARN(errno, "Failed setting SO_REUSEADDR on %s socket", type == SOCK_DGRAM ? "TFTP" : "FTP");
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
if (bind(sd, (struct sockaddr *)&server, len) < 0) {
if (EACCES != errno) {
WARN(errno, "Failed binding to port %d, maybe another %s server is already running", port, desc);
}
close(sd);
return -1;
}
if (port && type != SOCK_DGRAM) {
if (-1 == listen(sd, 20))
WARN(errno, "Failed starting %s server", desc);
}
DBG("Opened socket for port %d", port);
return sd;
}
void convert_address(struct sockaddr_storage *ss, char *buf, size_t len)
{
switch (ss->ss_family) {
case AF_INET:
inet_ntop(ss->ss_family,
&((struct sockaddr_in *)ss)->sin_addr, buf, len);
break;
case AF_INET6:
inet_ntop(ss->ss_family,
&((struct sockaddr_in6 *)ss)->sin6_addr, buf, len);
break;
}
}
/* Inactivity timer, bye bye */
static void inactivity_cb(uev_t *w, void *arg, int events)
{
uev_ctx_t *ctx = (uev_ctx_t *)arg;
INFO("Inactivity timer, exiting ...");
uev_exit(ctx);
}
ctrl_t *new_session(uev_ctx_t *ctx, int sd, int *rc)
{
ctrl_t *ctrl = NULL;
static int privs_dropped = 0;
if (!inetd) {
pid_t pid = fork();
if (pid) {
DBG("Created new client session as PID %d", pid);
*rc = pid;
return NULL;
}
/*
* Set process group to parent, so uftpd can call
* killpg() on all of us when it exits.
*/
setpgid(0, getppid());
/* Create new uEv context for the child. */
ctx = calloc(1, sizeof(uev_ctx_t));
if (!ctx) {
ERR(errno, "Failed allocating session event context");
exit(1);
}
uev_init(ctx);
}
ctrl = calloc(1, sizeof(ctrl_t));
if (!ctrl) {
ERR(errno, "Failed allocating session context");
goto fail;
}
ctrl->sd = set_nonblock(sd);
ctrl->ctx = ctx;
strlcpy(ctrl->cwd, "/", sizeof(ctrl->cwd));
/* Chroot to FTP root */
if (!chrooted && geteuid() == 0) {
if (chroot(home) || chdir("/")) {
ERR(errno, "Failed chrooting to FTP root, %s, aborting", home);
goto fail;
}
chrooted = 1;
} else if (!chrooted) {
if (chdir(home)) {
WARN(errno, "Failed changing to FTP root, %s, aborting", home);
goto fail;
}
}
/* If ftp user exists and we're running as root we can drop privs */
if (!privs_dropped && pw && geteuid() == 0) {
int fail1, fail2;
initgroups(pw->pw_name, pw->pw_gid);
if ((fail1 = setegid(pw->pw_gid)))
WARN(errno, "Failed dropping group privileges to gid %d", pw->pw_gid);
if ((fail2 = seteuid(pw->pw_uid)))
WARN(errno, "Failed dropping user privileges to uid %d", pw->pw_uid);
setenv("HOME", pw->pw_dir, 1);
if (!fail1 && !fail2)
INFO("Successfully dropped privilges to %d:%d (uid:gid)", pw->pw_uid, pw->pw_gid);
/*
* Check we don't have write access to the FTP root,
* unless explicitly allowed
*/
if (!do_insecure && !access(home, W_OK)) {
ERR(0, "FTP root %s writable, possible security violation, aborting session!", home);
goto fail;
}
/* On failure, we tried at least. Only warn once. */
privs_dropped = 1;
}
/* Session timeout handler */
uev_timer_init(ctrl->ctx, &ctrl->timeout_watcher, inactivity_cb, ctrl->ctx, INACTIVITY_TIMER, 0);
return ctrl;
fail:
if (ctrl)
free(ctrl);
if (!inetd)
free(ctx);
*rc = -1;
return NULL;
}
int del_session(ctrl_t *ctrl, int isftp)
{
DBG("%sFTP Client session ended.", isftp ? "": "T" );
if (!ctrl)
return -1;
if (isftp && ctrl->sd > 0) {
shutdown(ctrl->sd, SHUT_RDWR);
close(ctrl->sd);
}
if (ctrl->data_listen_sd > 0) {
shutdown(ctrl->data_listen_sd, SHUT_RDWR);
close(ctrl->data_listen_sd);
}
if (ctrl->data_sd > 0) {
shutdown(ctrl->data_sd, SHUT_RDWR);
close(ctrl->data_sd);
}
if (ctrl->buf)
free(ctrl->buf);
if (!inetd && ctrl->ctx)
free(ctrl->ctx);
free(ctrl);
return 0;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_4261_0 |
crossvul-cpp_data_bad_4261_0 | /* Common methods shared between FTP and TFTP engines
*
* Copyright (c) 2014-2019 Joachim Nilsson <troglobit@gmail.com>
*
* 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.
*/
#include "uftpd.h"
int chrooted = 0;
/* Protect against common directory traversal attacks, for details see
* https://en.wikipedia.org/wiki/Directory_traversal_attack
*
* Example: /srv/ftp/ ../../etc/passwd => /etc/passwd
* .~~~~~~~~ .~~~~~~~~~
* / /
* Server dir ------' /
* User input ---------------'
*
* Forced dir ------> /srv/ftp/etc
*/
char *compose_path(ctrl_t *ctrl, char *path)
{
struct stat st;
static char rpath[PATH_MAX];
char *name, *ptr;
char dir[PATH_MAX] = { 0 };
strlcpy(dir, ctrl->cwd, sizeof(dir));
DBG("Compose path from cwd: %s, arg: %s", ctrl->cwd, path ?: "");
if (!path || !strlen(path))
goto check;
if (path) {
if (path[0] != '/') {
if (dir[strlen(dir) - 1] != '/')
strlcat(dir, "/", sizeof(dir));
}
strlcat(dir, path, sizeof(dir));
}
check:
while ((ptr = strstr(dir, "//")))
memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);
if (!chrooted) {
size_t len = strlen(home);
DBG("Server path from CWD: %s", dir);
if (len > 0 && home[len - 1] == '/')
len--;
memmove(dir + len, dir, strlen(dir) + 1);
memcpy(dir, home, len);
DBG("Resulting non-chroot path: %s", dir);
}
/*
* Handle directories slightly differently, since dirname() on a
* directory returns the parent directory. So, just squash ..
*/
if (!stat(dir, &st) && S_ISDIR(st.st_mode)) {
if (!realpath(dir, rpath))
return NULL;
} else {
/*
* Check realpath() of directory containing the file, a
* STOR may want to save a new file. Then append the
* file and return it.
*/
name = basename(path);
ptr = dirname(dir);
memset(rpath, 0, sizeof(rpath));
if (!realpath(ptr, rpath)) {
INFO("Failed realpath(%s): %m", ptr);
return NULL;
}
if (rpath[1] != 0)
strlcat(rpath, "/", sizeof(rpath));
strlcat(rpath, name, sizeof(rpath));
}
if (!chrooted && strncmp(dir, home, strlen(home))) {
DBG("Failed non-chroot dir:%s vs home:%s", dir, home);
return NULL;
}
return rpath;
}
char *compose_abspath(ctrl_t *ctrl, char *path)
{
char *ptr;
char cwd[sizeof(ctrl->cwd)];
if (path && path[0] == '/') {
strlcpy(cwd, ctrl->cwd, sizeof(cwd));
memset(ctrl->cwd, 0, sizeof(ctrl->cwd));
}
ptr = compose_path(ctrl, path);
if (path && path[0] == '/')
strlcpy(ctrl->cwd, cwd, sizeof(ctrl->cwd));
return ptr;
}
int set_nonblock(int fd)
{
int flags;
flags = fcntl(fd, F_GETFL, 0);
if (!flags)
(void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
return fd;
}
int open_socket(int port, int type, char *desc)
{
int sd, err, val = 1;
socklen_t len = sizeof(struct sockaddr);
struct sockaddr_in server;
sd = socket(AF_INET, type | SOCK_NONBLOCK, 0);
if (sd < 0) {
WARN(errno, "Failed creating %s server socket", desc);
return -1;
}
err = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
if (err != 0)
WARN(errno, "Failed setting SO_REUSEADDR on %s socket", type == SOCK_DGRAM ? "TFTP" : "FTP");
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
if (bind(sd, (struct sockaddr *)&server, len) < 0) {
if (EACCES != errno) {
WARN(errno, "Failed binding to port %d, maybe another %s server is already running", port, desc);
}
close(sd);
return -1;
}
if (port && type != SOCK_DGRAM) {
if (-1 == listen(sd, 20))
WARN(errno, "Failed starting %s server", desc);
}
DBG("Opened socket for port %d", port);
return sd;
}
void convert_address(struct sockaddr_storage *ss, char *buf, size_t len)
{
switch (ss->ss_family) {
case AF_INET:
inet_ntop(ss->ss_family,
&((struct sockaddr_in *)ss)->sin_addr, buf, len);
break;
case AF_INET6:
inet_ntop(ss->ss_family,
&((struct sockaddr_in6 *)ss)->sin6_addr, buf, len);
break;
}
}
/* Inactivity timer, bye bye */
static void inactivity_cb(uev_t *w, void *arg, int events)
{
uev_ctx_t *ctx = (uev_ctx_t *)arg;
INFO("Inactivity timer, exiting ...");
uev_exit(ctx);
}
ctrl_t *new_session(uev_ctx_t *ctx, int sd, int *rc)
{
ctrl_t *ctrl = NULL;
static int privs_dropped = 0;
if (!inetd) {
pid_t pid = fork();
if (pid) {
DBG("Created new client session as PID %d", pid);
*rc = pid;
return NULL;
}
/*
* Set process group to parent, so uftpd can call
* killpg() on all of us when it exits.
*/
setpgid(0, getppid());
/* Create new uEv context for the child. */
ctx = calloc(1, sizeof(uev_ctx_t));
if (!ctx) {
ERR(errno, "Failed allocating session event context");
exit(1);
}
uev_init(ctx);
}
ctrl = calloc(1, sizeof(ctrl_t));
if (!ctrl) {
ERR(errno, "Failed allocating session context");
goto fail;
}
ctrl->sd = set_nonblock(sd);
ctrl->ctx = ctx;
strlcpy(ctrl->cwd, "/", sizeof(ctrl->cwd));
/* Chroot to FTP root */
if (!chrooted && geteuid() == 0) {
if (chroot(home) || chdir("/")) {
ERR(errno, "Failed chrooting to FTP root, %s, aborting", home);
goto fail;
}
chrooted = 1;
} else if (!chrooted) {
if (chdir(home)) {
WARN(errno, "Failed changing to FTP root, %s, aborting", home);
goto fail;
}
}
/* If ftp user exists and we're running as root we can drop privs */
if (!privs_dropped && pw && geteuid() == 0) {
int fail1, fail2;
initgroups(pw->pw_name, pw->pw_gid);
if ((fail1 = setegid(pw->pw_gid)))
WARN(errno, "Failed dropping group privileges to gid %d", pw->pw_gid);
if ((fail2 = seteuid(pw->pw_uid)))
WARN(errno, "Failed dropping user privileges to uid %d", pw->pw_uid);
setenv("HOME", pw->pw_dir, 1);
if (!fail1 && !fail2)
INFO("Successfully dropped privilges to %d:%d (uid:gid)", pw->pw_uid, pw->pw_gid);
/*
* Check we don't have write access to the FTP root,
* unless explicitly allowed
*/
if (!do_insecure && !access(home, W_OK)) {
ERR(0, "FTP root %s writable, possible security violation, aborting session!", home);
goto fail;
}
/* On failure, we tried at least. Only warn once. */
privs_dropped = 1;
}
/* Session timeout handler */
uev_timer_init(ctrl->ctx, &ctrl->timeout_watcher, inactivity_cb, ctrl->ctx, INACTIVITY_TIMER, 0);
return ctrl;
fail:
if (ctrl)
free(ctrl);
if (!inetd)
free(ctx);
*rc = -1;
return NULL;
}
int del_session(ctrl_t *ctrl, int isftp)
{
DBG("%sFTP Client session ended.", isftp ? "": "T" );
if (!ctrl)
return -1;
if (isftp && ctrl->sd > 0) {
shutdown(ctrl->sd, SHUT_RDWR);
close(ctrl->sd);
}
if (ctrl->data_listen_sd > 0) {
shutdown(ctrl->data_listen_sd, SHUT_RDWR);
close(ctrl->data_listen_sd);
}
if (ctrl->data_sd > 0) {
shutdown(ctrl->data_sd, SHUT_RDWR);
close(ctrl->data_sd);
}
if (ctrl->buf)
free(ctrl->buf);
if (!inetd && ctrl->ctx)
free(ctrl->ctx);
free(ctrl);
return 0;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-22/c/bad_4261_0 |
crossvul-cpp_data_good_5866_0 | /*
* DidiWiki - a small lightweight wiki engine.
*
* Copyright 2004 Matthew Allum <mallum@o-hand.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, 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 "didi.h"
#include "wikitext.h"
static char* CssData = STYLESHEET;
static char *
get_line_from_string(char **lines, int *line_len)
{
int i;
char *z = *lines;
if( z[0] == '\0' ) return NULL;
for (i=0; z[i]; i++)
{
if (z[i] == '\n')
{
if (i > 0 && z[i-1]=='\r')
{ z[i-1] = '\0'; }
else
{ z[i] = '\0'; }
i++;
break;
}
}
/* advance lines on */
*lines = &z[i];
*line_len -= i;
return z;
}
static char*
check_for_link(char *line, int *skip_chars)
{
char *start = line;
char *p = line;
char *url = NULL;
char *title = NULL;
char *result = NULL;
int found = 0;
if (*p == '[') /* [ link [title] ] */
{
/* XXX TODO XXX
* Allow links like [the Main page] ( covert to the_main_page )
*/
url = start+1; *p = '\0'; p++;
while ( *p != ']' && *p != '\0' && !isspace(*p) ) p++;
if (isspace(*p))
{
*p = '\0';
title = ++p;
while ( *p != ']' && *p != '\0' )
p++;
}
*p = '\0';
p++;
}
else if (!strncasecmp(p, "http://", 7)
|| !strncasecmp(p, "mailto://", 9)
|| !strncasecmp(p, "file://", 7))
{
while ( *p != '\0' && !isspace(*p) ) p++;
found = 1;
}
else if (isupper(*p)) /* Camel-case */
{
int num_upper_char = 1;
p++;
while ( *p != '\0' && isalnum(*p) )
{
if (isupper(*p))
{ found = 1; num_upper_char++; }
p++;
}
if (num_upper_char == (p-start)) /* Dont make ALLCAPS links */
return NULL;
}
if (found) /* cant really set http/camel links in place */
{
url = malloc(sizeof(char) * ((p - start) + 2) );
memset(url, 0, sizeof(char) * ((p - start) + 2));
strncpy(url, start, p - start);
*start = '\0';
}
if (url != NULL)
{
int len = strlen(url);
*skip_chars = p - start;
/* is it an image ? */
if (!strncmp(url+len-4, ".gif", 4) || !strncmp(url+len-4, ".png", 4)
|| !strncmp(url+len-4, ".jpg", 4) || !strncmp(url+len-5, ".jpeg", 5))
{
if (title)
asprintf(&result, "<a href='%s'><img src='%s' border='0'></a>",
title, url);
else
asprintf(&result, "<img src='%s' border='0'>", url);
}
else
{
char *extra_attr = "";
if (!strncasecmp(url, "http://", 7))
extra_attr = " title='WWW link' ";
if (title)
asprintf(&result,"<a %s href='%s'>%s</a>", extra_attr, url, title);
else
asprintf(&result, "<a %s href='%s'>%s</a>", extra_attr, url, url);
}
return result;
}
return NULL;
}
static char *
file_read(char *filename)
{
struct stat st;
FILE* fp;
char* str;
int len;
/* Get the file size. */
if (stat(filename, &st))
return NULL;
if (!(fp = fopen(filename, "rb")))
return NULL;
str = (char *)malloc(sizeof(char)*(st.st_size + 1));
len = fread(str, 1, st.st_size, fp);
if (len >= 0) str[len] = '\0';
fclose(fp);
return str;
}
static int
file_write(char *filename, char *data)
{
FILE* fp;
int bytes_written = 0;
int len = strlen(data); /* clip off extra '\0' */
if (!(fp = fopen(filename, "wb")))
return -1;
while ( len > 0 )
{
bytes_written = fwrite(data, sizeof(char), len, fp);
len = len - bytes_written;
data = data + bytes_written;
}
fclose(fp);
return 1;
}
static int
is_wiki_format_char_or_space(char c)
{
if (isspace(c)) return 1;
if (strchr("/*_-", c)) return 1;
return 0;
}
void
wiki_print_data_as_html(HttpResponse *res, char *raw_page_data)
{
char *p = raw_page_data; /* accumalates non marked up text */
char *q = NULL, *link = NULL; /* temporary scratch stuff */
char *line = NULL;
int line_len;
int i, j, skip_chars;
/* flags, mainly for open tag states */
int bold_on = 0;
int italic_on = 0;
int underline_on = 0;
int strikethrough_on = 0;
int open_para = 0;
int pre_on = 0;
int table_on = 0;
#define ULIST 0
#define OLIST 1
#define NUM_LIST_TYPES 2
struct { char ident; int depth; char *tag; } listtypes[] = {
{ '*', 0, "ul" },
{ '#', 0, "ol" }
};
q = p; /* p accumalates non marked up text, q is just a pointer
* to the end of the current line - used by below func.
*/
while ( (line = get_line_from_string(&q, &line_len)) )
{
int header_level = 0;
char *line_start = line;
int skip_to_content = 0;
/*
* process any initial wiki chars at line beginning
*/
if (pre_on && !isspace(*line) && *line != '\0')
{
/* close any preformatting if already on*/
http_response_printf(res, "\n</pre>\n") ;
pre_on = 0;
}
/* Handle ordered & unordered list, code is a bit mental.. */
for (i=0; i<NUM_LIST_TYPES; i++)
{
/* extra checks avoid bolding */
if ( *line == listtypes[i].ident
&& ( *(line+1) == listtypes[i].ident || isspace(*(line+1)) ) )
{
int item_depth = 0;
if (listtypes[!i].depth)
{
for (j=0; j<listtypes[!i].depth; j++)
http_response_printf(res, "</%s>\n", listtypes[!i].tag);
listtypes[!i].depth = 0;
}
while ( *line == listtypes[i].ident ) { line++; item_depth++; }
if (item_depth < listtypes[i].depth)
{
for (j = 0; j < (listtypes[i].depth - item_depth); j++)
http_response_printf(res, "</%s>\n", listtypes[i].tag);
}
else
{
for (j = 0; j < (item_depth - listtypes[i].depth); j++)
http_response_printf(res, "<%s>\n", listtypes[i].tag);
}
http_response_printf(res, "<li>");
listtypes[i].depth = item_depth;
skip_to_content = 1;
}
else if (listtypes[i].depth && !listtypes[!i].depth)
{
/* close current list */
for (j=0; j<listtypes[i].depth; j++)
http_response_printf(res, "</%s>\n", listtypes[i].tag);
listtypes[i].depth = 0;
}
}
if (skip_to_content)
goto line_content; /* skip parsing any more initial chars */
/* Tables */
if (*line == '|')
{
if (table_on==0)
http_response_printf(res, "<table class='wikitable' cellspacing='0' cellpadding='4'>\n");
line++;
http_response_printf(res, "<tr><td>");
table_on = 1;
goto line_content;
}
else
{
if(table_on)
{
http_response_printf(res, "</table>\n");
table_on = 0;
}
}
/* pre formated */
if ( (isspace(*line) || *line == '\0'))
{
int n_spaces = 0;
while ( isspace(*line) ) { line++; n_spaces++; }
if (*line == '\0') /* empty line - para */
{
if (pre_on)
{
http_response_printf(res, "\n") ;
continue;
}
else if (open_para)
{
http_response_printf(res, "\n</p><p>\n") ;
}
else
{
http_response_printf(res, "\n<p>\n") ;
open_para = 1;
}
}
else /* starts with space so Pre formatted, see above for close */
{
if (!pre_on)
http_response_printf(res, "<pre>\n") ;
pre_on = 1;
line = line - ( n_spaces - 1 ); /* rewind so extra spaces
they matter to pre */
http_response_printf(res, "%s\n", line);
continue;
}
}
else if ( *line == '=' )
{
while (*line == '=')
{ header_level++; line++; }
http_response_printf(res, "<h%d>", header_level);
p = line;
}
else if ( *line == '-' && *(line+1) == '-' )
{
/* rule */
http_response_printf(res, "<hr/>\n");
while ( *line == '-' ) line++;
}
line_content:
/*
* now process rest of the line
*/
p = line;
while ( *line != '\0' )
{
if ( *line == '!' && !isspace(*(line+1)))
{ /* escape next word - skip it */
*line = '\0';
http_response_printf(res, "%s", p);
p = ++line;
while (*line != '\0' && !isspace(*line)) line++;
if (*line == '\0')
continue;
}
else if ((link = check_for_link(line, &skip_chars)) != NULL)
{
http_response_printf(res, "%s", p);
http_response_printf(res, "%s", link);
line += skip_chars;
p = line;
continue;
}
/* TODO: Below is getting bloated and messy, need rewriting more
* compactly ( and efficently ).
*/
else if (*line == '*')
{
/* Try and be smart about what gets bolded */
if (line_start != line
&& !is_wiki_format_char_or_space(*(line-1))
&& !bold_on)
{ line++; continue; }
if ((isspace(*(line+1)) && !bold_on))
{ line++; continue; }
/* bold */
*line = '\0';
http_response_printf(res, "%s%s\n", p, bold_on ? "</b>" : "<b>");
bold_on ^= 1; /* reset flag */
p = line+1;
}
else if (*line == '_' )
{
if (line_start != line
&& !is_wiki_format_char_or_space(*(line-1))
&& !underline_on)
{ line++; continue; }
if (isspace(*(line+1)) && !underline_on)
{ line++; continue; }
/* underline */
*line = '\0';
http_response_printf(res, "%s%s\n", p, underline_on ? "</u>" : "<u>");
underline_on ^= 1; /* reset flag */
p = line+1;
}
else if (*line == '-')
{
if (line_start != line
&& !is_wiki_format_char_or_space(*(line-1))
&& !strikethrough_on)
{ line++; continue; }
if (isspace(*(line+1)) && !strikethrough_on)
{ line++; continue; }
/* strikethrough */
*line = '\0';
http_response_printf(res, "%s%s\n", p, strikethrough_on ? "</del>" : "<del>");
strikethrough_on ^= 1; /* reset flag */
p = line+1;
}
else if (*line == '/' )
{
if (line_start != line
&& !is_wiki_format_char_or_space(*(line-1))
&& !italic_on)
{ line++; continue; }
if (isspace(*(line+1)) && !italic_on)
{ line++; continue; }
/* crude path detection */
if (line_start != line && isspace(*(line-1)) && !italic_on)
{
char *tmp = line+1;
int slashes = 0;
/* Hack to escape out file paths */
while (*tmp != '\0' && !isspace(*tmp))
{
if (*tmp == '/') slashes++;
tmp++;
}
if (slashes > 1 || (slashes == 1 && *(tmp-1) != '/'))
{ line = tmp; continue; }
}
if (*(line+1) == '/')
line++; /* escape out common '//' - eg urls */
else
{
/* italic */
*line = '\0';
http_response_printf(res, "%s%s\n", p, italic_on ? "</i>" : "<i>");
italic_on ^= 1; /* reset flag */
p = line+1;
}
}
else if (*line == '|' && table_on) /* table column */
{
*line = '\0';
http_response_printf(res, "%s", p);
http_response_printf(res, "</td><td>\n");
p = line+1;
}
line++;
} /* next word */
if (*p != '\0') /* accumalated text left over */
http_response_printf(res, "%s", p);
/* close any html tags that could be still open */
if (listtypes[ULIST].depth)
http_response_printf(res, "</li>");
if (listtypes[OLIST].depth)
http_response_printf(res, "</li>");
if (table_on)
http_response_printf(res, "</td></tr>\n");
if (header_level)
http_response_printf(res, "</h%d>\n", header_level);
else
http_response_printf(res, "\n");
} /* next line */
/* clean up anything thats still open */
if (pre_on)
http_response_printf(res, "</pre>\n");
/* close any open lists */
for (i=0; i<listtypes[ULIST].depth; i++)
http_response_printf(res, "</ul>\n");
for (i=0; i<listtypes[OLIST].depth; i++)
http_response_printf(res, "</ol>\n");
/* close any open paras */
if (open_para)
http_response_printf(res, "</p>\n");
/* tables */
if (table_on)
http_response_printf(res, "</table>\n");
}
int
wiki_redirect(HttpResponse *res, char *location)
{
int header_len = strlen(location) + 14;
char *header = alloca(sizeof(char)*header_len);
snprintf(header, header_len, "Location: %s\r\n", location);
http_response_append_header(res, header);
http_response_printf(res, "<html>\n<p>Redirect to %s</p>\n</html>\n",
location);
http_response_set_status(res, 302, "Moved Temporarily");
http_response_send(res);
exit(0);
}
void
wiki_show_page(HttpResponse *res, char *wikitext, char *page)
{
char *html_clean_wikitext = NULL;
http_response_printf_alloc_buffer(res, strlen(wikitext)*2);
wiki_show_header(res, page, TRUE);
html_clean_wikitext = util_htmlize(wikitext, strlen(wikitext));
wiki_print_data_as_html(res, html_clean_wikitext);
wiki_show_footer(res);
http_response_send(res);
exit(0);
}
void
wiki_show_edit_page(HttpResponse *res, char *wikitext, char *page)
{
wiki_show_header(res, page, FALSE);
if (wikitext == NULL) wikitext = "";
http_response_printf(res, EDITFORM, page, wikitext);
wiki_show_footer(res);
http_response_send(res);
exit(0);
}
void
wiki_show_create_page(HttpResponse *res)
{
wiki_show_header(res, "Create New Page", FALSE);
http_response_printf(res, "%s", CREATEFORM);
wiki_show_footer(res);
http_response_send(res);
exit(0);
}
static int
changes_compar(const struct dirent **d1, const struct dirent **d2)
{
struct stat st1, st2;
stat((*d1)->d_name, &st1);
stat((*d2)->d_name, &st2);
if (st1.st_mtime > st2.st_mtime)
return 1;
else
return -1;
}
WikiPageList**
wiki_get_pages(int *n_pages, char *expr)
{
WikiPageList **pages;
struct dirent **namelist;
int n, i = 0;
struct stat st;
n = scandir(".", &namelist, 0, (void *)changes_compar);
pages = malloc(sizeof(WikiPageList*)*n);
while(n--)
{
if ((namelist[n]->d_name)[0] == '.'
|| !strcmp(namelist[n]->d_name, "styles.css"))
goto cleanup;
if (expr != NULL)
{ /* Super Simple Search */
char *data = NULL;
if ((data = file_read(namelist[n]->d_name)) != NULL)
if (strstr(data, expr) == NULL)
if (strcmp(namelist[n]->d_name, expr) != 0)
goto cleanup;
}
stat(namelist[n]->d_name, &st);
/* ignore anything but regular readable files */
if (S_ISREG(st.st_mode) && access(namelist[n]->d_name, R_OK) == 0)
{
pages[i] = malloc(sizeof(WikiPageList));
pages[i]->name = strdup (namelist[n]->d_name);
pages[i]->mtime = st.st_mtime;
i++;
}
cleanup:
free(namelist[n]);
}
*n_pages = i;
free(namelist);
if (i==0) return NULL;
return pages;
}
void
wiki_show_changes_page(HttpResponse *res)
{
WikiPageList **pages = NULL;
int n_pages, i;
wiki_show_header(res, "Changes", FALSE);
pages = wiki_get_pages(&n_pages, NULL);
for (i=0; i<n_pages; i++)
{
struct tm *pTm;
char datebuf[64];
pTm = localtime(&pages[i]->mtime);
strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
http_response_printf(res, "<a href='%s'>%s</a> %s<br />\n",
pages[i]->name,
pages[i]->name,
datebuf);
}
wiki_show_footer(res);
http_response_send(res);
exit(0);
}
void
wiki_show_changes_page_rss(HttpResponse *res)
{
WikiPageList **pages = NULL;
int n_pages, i;
/*char *html_clean_wikitext = NULL;
char *wikitext; */
pages = wiki_get_pages(&n_pages, NULL);
http_response_printf(res, "<?xml version=\"1.0\"encoding=\"ISO-8859-1\"?>\n"
"<rss version=\"2.0\">\n"
"<channel><title>DidiWiki Changes feed</title>\n");
for (i=0; i<n_pages; i++)
{
struct tm *pTm;
char datebuf[64];
pTm = localtime(&pages[i]->mtime);
strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
http_response_printf(res,
"<item><title>%s</title>"
"<link>%s%s</link><description>"
"Modified %s\n",
pages[i]->name,
getenv("DIDIWIKI_URL_PREFIX") ? getenv("DIDIWIKI_URL_PREFIX") : "",
pages[i]->name,
datebuf);
/*
wikitext = file_read(pages[i]->name);
http_response_printf_alloc_buffer(res, strlen(wikitext)*2);
html_clean_wikitext = util_htmlize(wikitext, strlen(wikitext));
wiki_print_data_as_html(res, html_clean_wikitext);
*/
http_response_printf(res, "</description></item>\n");
}
http_response_printf(res, "</channel>\n</rss>");
http_response_send(res);
exit(0);
}
void
wiki_show_search_results_page(HttpResponse *res, char *expr)
{
WikiPageList **pages = NULL;
int n_pages, i;
if (expr == NULL || strlen(expr) == 0)
{
wiki_show_header(res, "Search", FALSE);
http_response_printf(res, "No Search Terms supplied");
wiki_show_footer(res);
http_response_send(res);
exit(0);
}
pages = wiki_get_pages(&n_pages, expr);
if (pages)
{
for (i=0; i<n_pages; i++)
if (!strcmp(pages[i]->name, expr)) /* redirect on page name match */
wiki_redirect(res, pages[i]->name);
wiki_show_header(res, "Search", FALSE);
for (i=0; i<n_pages; i++)
{
http_response_printf(res, "<a href='%s'>%s</a><br />\n",
pages[i]->name,
pages[i]->name);
}
}
else
{
wiki_show_header(res, "Search", FALSE);
http_response_printf(res, "No matches");
}
wiki_show_footer(res);
http_response_send(res);
exit(0);
}
void
wiki_show_template(HttpResponse *res, char *template_data)
{
/* 4 templates - header.html, footer.html,
header-noedit.html, footer-noedit.html
Vars;
$title - page title.
$include() - ?
$pages
*/
}
void
wiki_show_header(HttpResponse *res, char *page_title, int want_edit)
{
http_response_printf(res,
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns='http://www.w3.org/1999/xhtml'>\n"
"<head>\n"
"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />\n"
"<link rel='SHORTCUT ICON' href='favicon.ico' />\n"
"<link media='all' href='styles.css' rel='stylesheet' type='text/css' />\n"
"<title>%s</title>\n"
"</head>\n"
"<body>\n", page_title
);
http_response_printf(res, PAGEHEADER, page_title,
(want_edit) ? " ( <a href='?edit' title='Edit this wiki page contents. [alt-j]' accesskey='j'>Edit</a> ) " : "" );
}
void
wiki_show_footer(HttpResponse *res)
{
http_response_printf(res, "%s", PAGEFOOTER);
http_response_printf(res,
"</body>\n"
"</html>\n"
);
}
int page_name_is_good(char* page_name)
{
/* We should give access only to subdirs of didiwiki root.
I guess that check for absense of '/' is enough.
TODO: Use realpath()
*/
if (!page_name)
return FALSE;
if (!isalnum(page[0]))
return FALSE;
if (strstr(page, ".."))
return FALSE;
return TRUE;
}
void
wiki_handle_rest_call(HttpRequest *req,
HttpResponse *res,
char *func)
{
if (func != NULL && *func != '\0')
{
if (!strcmp(func, "page/get"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && page_name_is_good(page) && (access(page, R_OK) == 0))
{
http_response_printf(res, "%s", file_read(page));
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/set"))
{
char *wikitext = NULL, *page = NULL;
if( ( (wikitext = http_request_param_get(req, "text")) != NULL)
&& ( (page = http_request_param_get(req, "page")) != NULL))
{
if (page_name_is_good(page))
{
file_write(page, wikitext);
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
}
else if (!strcmp(func, "page/delete"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && page_name_is_good(page) && (unlink(page) > 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/exists"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && page_name_is_good(page) && (access(page, R_OK) == 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "pages") || !strcmp(func, "search"))
{
WikiPageList **pages = NULL;
int n_pages, i;
char *expr = http_request_param_get(req, "expr");
if (expr == NULL)
expr = http_request_get_query_string(req);
pages = wiki_get_pages(&n_pages, expr);
if (pages)
{
for (i=0; i<n_pages; i++)
{
struct tm *pTm;
char datebuf[64];
pTm = localtime(&pages[i]->mtime);
strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf);
}
http_response_send(res);
return;
}
}
}
http_response_set_status(res, 500, "Error");
http_response_printf(res, "<html><body>Failed</body></html>\n");
http_response_send(res);
return;
}
void
wiki_handle_http_request(HttpRequest *req)
{
HttpResponse *res = http_response_new(req);
char *page = http_request_get_path_info(req);
char *command = http_request_get_query_string(req);
char *wikitext = "";
util_dehttpize(page); /* remove any encoding on the requested
page name. */
if (!strcmp(page, "/"))
{
if (access("WikiHome", R_OK) != 0)
wiki_redirect(res, "/WikiHome?create");
page = "/WikiHome";
}
if (!strcmp(page, "/styles.css"))
{
/* Return CSS page */
http_response_set_content_type(res, "text/css");
http_response_printf(res, "%s", CssData);
http_response_send(res);
exit(0);
}
if (!strcmp(page, "/favicon.ico"))
{
/* Return favicon */
http_response_set_content_type(res, "image/ico");
http_response_set_data(res, FaviconData, FaviconDataLen);
http_response_send(res);
exit(0);
}
page = page + 1; /* skip slash */
if (!strncmp(page, "api/", 4))
{
char *p;
page += 4;
for (p=page; *p != '\0'; p++)
if (*p=='?') { *p ='\0'; break; }
wiki_handle_rest_call(req, res, page);
exit(0);
}
/* A little safety. issue a malformed request for any paths,
* There shouldn't need to be any..
*/
if (!page_name_is_good(page))
{
http_response_set_status(res, 404, "Not Found");
http_response_printf(res, "<html><body>404 Not Found</body></html>\n");
http_response_send(res);
exit(0);
}
if (!strcmp(page, "Changes"))
{
wiki_show_changes_page(res);
}
else if (!strcmp(page, "ChangesRss"))
{
wiki_show_changes_page_rss(res);
}
else if (!strcmp(page, "Search"))
{
wiki_show_search_results_page(res, http_request_param_get(req, "expr"));
}
else if (!strcmp(page, "Create"))
{
if ( (wikitext = http_request_param_get(req, "title")) != NULL)
{
/* create page and redirect */
wiki_redirect(res, http_request_param_get(req, "title"));
}
else
{
/* show create page form */
wiki_show_create_page(res);
}
}
else
{
/* TODO: dont blindly write wikitext data to disk */
if ( (wikitext = http_request_param_get(req, "wikitext")) != NULL)
{
file_write(page, wikitext);
}
if (access(page, R_OK) == 0) /* page exists */
{
wikitext = file_read(page);
if (!strcmp(command, "edit"))
{
/* print edit page */
wiki_show_edit_page(res, wikitext, page);
}
else
{
wiki_show_page(res, wikitext, page);
}
}
else
{
if (!strcmp(command, "create"))
{
wiki_show_edit_page(res, NULL, page);
}
else
{
char buf[1024];
snprintf(buf, 1024, "%s?create", page);
wiki_redirect(res, buf);
}
}
}
}
int
wiki_init(void)
{
char datadir[512] = { 0 };
struct stat st;
if (getenv("DIDIWIKIHOME"))
{
snprintf(datadir, 512, getenv("DIDIWIKIHOME"));
}
else
{
if (getenv("HOME") == NULL)
{
fprintf(stderr, "Unable to get home directory, is HOME set?\n");
exit(1);
}
snprintf(datadir, 512, "%s/.didiwiki", getenv("HOME"));
}
/* Check if ~/.didiwiki exists and create if not */
if (stat(datadir, &st) != 0 )
{
if (mkdir(datadir, 0755) == -1)
{
fprintf(stderr, "Unable to create '%s', giving up.\n", datadir);
exit(1);
}
}
chdir(datadir);
/* Write Default Help + Home page if it doesn't exist */
if (access("WikiHelp", R_OK) != 0)
file_write("WikiHelp", HELPTEXT);
if (access("WikiHome", R_OK) != 0)
file_write("WikiHome", HOMETEXT);
/* Read in optional CSS data */
if (access("styles.css", R_OK) == 0)
CssData = file_read("styles.css");
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-22/c/good_5866_0 |
crossvul-cpp_data_bad_2610_0 | /* imzmq3.c
*
* This input plugin enables rsyslog to read messages from a ZeroMQ
* queue.
*
* Copyright 2012 Talksum, Inc.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* Authors:
* David Kelly <davidk@talksum.com>
* Hongfei Cheng <hongfeic@talksum.com>
*/
#include "config.h"
#include "rsyslog.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "cfsysline.h"
#include "dirty.h"
#include "errmsg.h"
#include "glbl.h"
#include "module-template.h"
#include "msg.h"
#include "net.h"
#include "parser.h"
#include "prop.h"
#include "ruleset.h"
#include "srUtils.h"
#include "unicode-helper.h"
#include <czmq.h>
MODULE_TYPE_INPUT
MODULE_TYPE_NOKEEP
MODULE_CNFNAME("imzmq3");
/* convienent symbols to denote a socket we want to bind
* vs one we want to just connect to
*/
#define ACTION_CONNECT 1
#define ACTION_BIND 2
/* Module static data */
DEF_IMOD_STATIC_DATA
DEFobjCurrIf(errmsg)
DEFobjCurrIf(glbl)
DEFobjCurrIf(prop)
DEFobjCurrIf(ruleset)
/* ----------------------------------------------------------------------------
* structs to describe sockets
*/
typedef struct _socket_type {
char* name;
int type;
} socket_type;
/* more overkill, but seems nice to be consistent.*/
typedef struct _socket_action {
char* name;
int action;
} socket_action;
typedef struct _poller_data {
ruleset_t* ruleset;
thrdInfo_t* thread;
} poller_data;
/* a linked-list of subscription topics */
typedef struct sublist_t {
char* subscribe;
struct sublist_t* next;
} sublist;
struct instanceConf_s {
int type;
int action;
char* description;
int sndHWM; /* if you want more than 2^32 messages, */
int rcvHWM; /* then pass in 0 (the default). */
char* identity;
sublist* subscriptions;
int sndBuf;
int rcvBuf;
int linger;
int backlog;
int sndTimeout;
int rcvTimeout;
int maxMsgSize;
int rate;
int recoveryIVL;
int multicastHops;
int reconnectIVL;
int reconnectIVLMax;
int ipv4Only;
int affinity;
uchar* pszBindRuleset;
ruleset_t* pBindRuleset;
struct instanceConf_s* next;
};
struct modConfData_s {
rsconf_t* pConf;
instanceConf_t* root;
instanceConf_t* tail;
int io_threads;
};
struct lstn_s {
struct lstn_s* next;
void* sock;
ruleset_t* pRuleset;
};
/* ----------------------------------------------------------------------------
* Static definitions/initializations.
*/
static modConfData_t* runModConf = NULL;
static struct lstn_s* lcnfRoot = NULL;
static struct lstn_s* lcnfLast = NULL;
static prop_t* s_namep = NULL;
static zloop_t* s_zloop = NULL;
static zctx_t* s_context = NULL;
static socket_type socketTypes[] = {
{"SUB", ZMQ_SUB },
{"PULL", ZMQ_PULL },
{"ROUTER", ZMQ_ROUTER },
{"XSUB", ZMQ_XSUB }
};
static socket_action socketActions[] = {
{"BIND", ACTION_BIND},
{"CONNECT", ACTION_CONNECT},
};
static struct cnfparamdescr modpdescr[] = {
{ "ioThreads", eCmdHdlrInt, 0 },
};
static struct cnfparamblk modpblk = {
CNFPARAMBLK_VERSION,
sizeof(modpdescr)/sizeof(struct cnfparamdescr),
modpdescr
};
static struct cnfparamdescr inppdescr[] = {
{ "description", eCmdHdlrGetWord, 0 },
{ "sockType", eCmdHdlrGetWord, 0 },
{ "subscribe", eCmdHdlrGetWord, 0 },
{ "ruleset", eCmdHdlrGetWord, 0 },
{ "action", eCmdHdlrGetWord, 0 },
{ "sndHWM", eCmdHdlrInt, 0 },
{ "rcvHWM", eCmdHdlrInt, 0 },
{ "identity", eCmdHdlrGetWord, 0 },
{ "sndBuf", eCmdHdlrInt, 0 },
{ "rcvBuf", eCmdHdlrInt, 0 },
{ "linger", eCmdHdlrInt, 0 },
{ "backlog", eCmdHdlrInt, 0 },
{ "sndTimeout", eCmdHdlrInt, 0 },
{ "rcvTimeout", eCmdHdlrInt, 0 },
{ "maxMsgSize", eCmdHdlrInt, 0 },
{ "rate", eCmdHdlrInt, 0 },
{ "recoveryIVL", eCmdHdlrInt, 0 },
{ "multicastHops", eCmdHdlrInt, 0 },
{ "reconnectIVL", eCmdHdlrInt, 0 },
{ "reconnectIVLMax", eCmdHdlrInt, 0 },
{ "ipv4Only", eCmdHdlrInt, 0 },
{ "affinity", eCmdHdlrInt, 0 }
};
static struct cnfparamblk inppblk = {
CNFPARAMBLK_VERSION,
sizeof(inppdescr)/sizeof(struct cnfparamdescr),
inppdescr
};
#include "im-helper.h" /* must be included AFTER the type definitions! */
/* ----------------------------------------------------------------------------
* Helper functions
*/
/* get the name of a socket type, return the ZMQ_XXX type
or -1 if not a supported type (see above)
*/
static int getSocketType(char* name) {
int type = -1;
uint i;
/* match name with known socket type */
for(i=0; i<sizeof(socketTypes)/sizeof(socket_type); ++i) {
if( !strcmp(socketTypes[i].name, name) ) {
type = socketTypes[i].type;
break;
}
}
/* whine if no match was found. */
if (type == -1)
errmsg.LogError(0, NO_ERRCODE, "unknown type %s",name);
return type;
}
static int getSocketAction(char* name) {
int action = -1;
uint i;
/* match name with known socket action */
for(i=0; i < sizeof(socketActions)/sizeof(socket_action); ++i) {
if(!strcmp(socketActions[i].name, name)) {
action = socketActions[i].action;
break;
}
}
/* whine if no matching action was found */
if (action == -1)
errmsg.LogError(0, NO_ERRCODE, "unknown action %s",name);
return action;
}
static void setDefaults(instanceConf_t* info) {
info->type = -1;
info->action = -1;
info->description = NULL;
info->sndHWM = -1;
info->rcvHWM = -1;
info->identity = NULL;
info->subscriptions = NULL;
info->pszBindRuleset = NULL;
info->pBindRuleset = NULL;
info->sndBuf = -1;
info->rcvBuf = -1;
info->linger = -1;
info->backlog = -1;
info->sndTimeout = -1;
info->rcvTimeout = -1;
info->maxMsgSize = -1;
info->rate = -1;
info->recoveryIVL = -1;
info->multicastHops = -1;
info->reconnectIVL = -1;
info->reconnectIVLMax = -1;
info->ipv4Only = -1;
info->affinity = -1;
info->next = NULL;
};
/* given a comma separated list of subscriptions, create a char* array of them
* to set later
*/
static rsRetVal parseSubscriptions(char* subscribes, sublist** subList){
char* tok = strtok(subscribes, ",");
sublist* currentSub;
sublist* head;
DEFiRet;
/* create empty list */
CHKmalloc(*subList = (sublist*)MALLOC(sizeof(sublist)));
head = *subList;
head->next = NULL;
head->subscribe=NULL;
currentSub=head;
if(tok) {
head->subscribe=strdup(tok);
for(tok=strtok(NULL, ","); tok!=NULL;tok=strtok(NULL, ",")) {
CHKmalloc(currentSub->next = (sublist*)MALLOC(sizeof(sublist)));
currentSub=currentSub->next;
currentSub->subscribe=strdup(tok);
currentSub->next=NULL;
}
} else {
/* make empty subscription ie subscribe="" */
head->subscribe=strdup("");
}
/* TODO: temporary logging */
currentSub = head;
DBGPRINTF("imzmq3: Subscriptions:");
for(currentSub = head; currentSub != NULL; currentSub=currentSub->next) {
DBGPRINTF("'%s'", currentSub->subscribe);
}
DBGPRINTF("\n");
finalize_it:
RETiRet;
}
static rsRetVal validateConfig(instanceConf_t* info) {
if (info->type == -1) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"you entered an invalid type");
return RS_RET_INVALID_PARAMS;
}
if (info->action == -1) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"you entered an invalid action");
return RS_RET_INVALID_PARAMS;
}
if (info->description == NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"you didn't enter a description");
return RS_RET_INVALID_PARAMS;
}
if(info->type == ZMQ_SUB && info->subscriptions == NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"SUB sockets need a subscription");
return RS_RET_INVALID_PARAMS;
}
if(info->type != ZMQ_SUB && info->subscriptions != NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"only SUB sockets can have subscriptions");
return RS_RET_INVALID_PARAMS;
}
return RS_RET_OK;
}
static rsRetVal createContext() {
if (s_context == NULL) {
DBGPRINTF("imzmq3: creating zctx...");
zsys_handler_set(NULL);
s_context = zctx_new();
if (s_context == NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"zctx_new failed: %s",
zmq_strerror(errno));
/* DK: really should do better than invalid params...*/
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("success!\n");
if (runModConf->io_threads > 1) {
DBGPRINTF("setting io worker threads to %d\n", runModConf->io_threads);
zctx_set_iothreads(s_context, runModConf->io_threads);
}
}
return RS_RET_OK;
}
static rsRetVal createSocket(instanceConf_t* info, void** sock) {
int rv;
sublist* sub;
*sock = zsocket_new(s_context, info->type);
if (!sock) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zsocket_new failed: %s, for type %d",
zmq_strerror(errno),info->type);
/* DK: invalid params seems right here */
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: socket of type %d created successfully\n", info->type)
/* Set options *before* the connect/bind. */
if (info->identity) zsocket_set_identity(*sock, info->identity);
if (info->sndBuf > -1) zsocket_set_sndbuf(*sock, info->sndBuf);
if (info->rcvBuf > -1) zsocket_set_rcvbuf(*sock, info->rcvBuf);
if (info->linger > -1) zsocket_set_linger(*sock, info->linger);
if (info->backlog > -1) zsocket_set_backlog(*sock, info->backlog);
if (info->sndTimeout > -1) zsocket_set_sndtimeo(*sock, info->sndTimeout);
if (info->rcvTimeout > -1) zsocket_set_rcvtimeo(*sock, info->rcvTimeout);
if (info->maxMsgSize > -1) zsocket_set_maxmsgsize(*sock, info->maxMsgSize);
if (info->rate > -1) zsocket_set_rate(*sock, info->rate);
if (info->recoveryIVL > -1) zsocket_set_recovery_ivl(*sock, info->recoveryIVL);
if (info->multicastHops > -1) zsocket_set_multicast_hops(*sock, info->multicastHops);
if (info->reconnectIVL > -1) zsocket_set_reconnect_ivl(*sock, info->reconnectIVL);
if (info->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(*sock, info->reconnectIVLMax);
if (info->ipv4Only > -1) zsocket_set_ipv4only(*sock, info->ipv4Only);
if (info->affinity > -1) zsocket_set_affinity(*sock, info->affinity);
if (info->sndHWM > -1 ) zsocket_set_sndhwm(*sock, info->sndHWM);
if (info->rcvHWM > -1 ) zsocket_set_rcvhwm(*sock, info->rcvHWM);
/* Set subscriptions.*/
if (info->type == ZMQ_SUB) {
for(sub = info->subscriptions; sub!=NULL; sub=sub->next) {
zsocket_set_subscribe(*sock, sub->subscribe);
}
}
/* Do the bind/connect... */
if (info->action==ACTION_CONNECT) {
rv = zsocket_connect(*sock, info->description);
if (rv == -1) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zmq_connect using %s failed: %s",
info->description, zmq_strerror(errno));
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: connect for %s successful\n",info->description);
} else {
rv = zsocket_bind(*sock, info->description);
if (rv == -1) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zmq_bind using %s failed: %s",
info->description, zmq_strerror(errno));
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: bind for %s successful\n",info->description);
}
return RS_RET_OK;
}
/* ----------------------------------------------------------------------------
* Module endpoints
*/
/* add an actual endpoint
*/
static rsRetVal createInstance(instanceConf_t** pinst) {
DEFiRet;
instanceConf_t* inst;
CHKmalloc(inst = MALLOC(sizeof(instanceConf_t)));
/* set defaults into new instance config struct */
setDefaults(inst);
/* add this to the config */
if (runModConf->root == NULL || runModConf->tail == NULL) {
runModConf->tail = runModConf->root = inst;
} else {
runModConf->tail->next = inst;
runModConf->tail = inst;
}
*pinst = inst;
finalize_it:
RETiRet;
}
static rsRetVal createListener(struct cnfparamvals* pvals) {
instanceConf_t* inst;
int i;
DEFiRet;
CHKiRet(createInstance(&inst));
for(i = 0 ; i < inppblk.nParams ; ++i) {
if(!pvals[i].bUsed)
continue;
if(!strcmp(inppblk.descr[i].name, "ruleset")) {
inst->pszBindRuleset = (uchar *)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(inppblk.descr[i].name, "description")) {
inst->description = es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(inppblk.descr[i].name, "sockType")){
inst->type = getSocketType(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if(!strcmp(inppblk.descr[i].name, "action")){
inst->action = getSocketAction(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if(!strcmp(inppblk.descr[i].name, "sndHWM")) {
inst->sndHWM = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rcvHWM")) {
inst->rcvHWM = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "subscribe")) {
char *subscribes = es_str2cstr(pvals[i].val.d.estr, NULL);
rsRetVal ret = parseSubscriptions(subscribes, &inst->subscriptions);
free(subscribes);
CHKiRet(ret);
} else if(!strcmp(inppblk.descr[i].name, "identity")){
inst->identity = es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(inppblk.descr[i].name, "sndBuf")) {
inst->sndBuf = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rcvBuf")) {
inst->rcvBuf = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "linger")) {
inst->linger = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "backlog")) {
inst->backlog = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "sndTimeout")) {
inst->sndTimeout = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rcvTimeout")) {
inst->rcvTimeout = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "maxMsgSize")) {
inst->maxMsgSize = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rate")) {
inst->rate = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "recoveryIVL")) {
inst->recoveryIVL = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "multicastHops")) {
inst->multicastHops = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "reconnectIVL")) {
inst->reconnectIVL = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "reconnectIVLMax")) {
inst->reconnectIVLMax = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "ipv4Only")) {
inst->ipv4Only = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "affinity")) {
inst->affinity = (int) pvals[i].val.d.n;
} else {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: program error, non-handled "
"param '%s'\n", inppblk.descr[i].name);
}
}
finalize_it:
RETiRet;
}
static rsRetVal addListener(instanceConf_t* inst){
/* create the socket */
void* sock;
struct lstn_s* newcnfinfo;
DEFiRet;
CHKiRet(createSocket(inst, &sock));
/* now create new lstn_s struct */
CHKmalloc(newcnfinfo=(struct lstn_s*)MALLOC(sizeof(struct lstn_s)));
newcnfinfo->next = NULL;
newcnfinfo->sock = sock;
newcnfinfo->pRuleset = inst->pBindRuleset;
/* add this struct to the global */
if(lcnfRoot == NULL) {
lcnfRoot = newcnfinfo;
}
if(lcnfLast == NULL) {
lcnfLast = newcnfinfo;
} else {
lcnfLast->next = newcnfinfo;
lcnfLast = newcnfinfo;
}
finalize_it:
RETiRet;
}
static int handlePoll(zloop_t __attribute__((unused)) * loop, zmq_pollitem_t *poller, void* pd) {
smsg_t* pMsg;
poller_data* pollerData = (poller_data*)pd;
char* buf = zstr_recv(poller->socket);
if (msgConstruct(&pMsg) == RS_RET_OK) {
MsgSetRawMsg(pMsg, buf, strlen(buf));
MsgSetInputName(pMsg, s_namep);
MsgSetHOSTNAME(pMsg, glbl.GetLocalHostName(), ustrlen(glbl.GetLocalHostName()));
MsgSetRcvFrom(pMsg, glbl.GetLocalHostNameProp());
MsgSetRcvFromIP(pMsg, glbl.GetLocalHostIP());
MsgSetMSGoffs(pMsg, 0);
MsgSetFlowControlType(pMsg, eFLOWCTL_NO_DELAY);
MsgSetRuleset(pMsg, pollerData->ruleset);
pMsg->msgFlags = NEEDS_PARSING | PARSE_HOSTNAME;
submitMsg2(pMsg);
}
/* gotta free the string returned from zstr_recv() */
free(buf);
if( pollerData->thread->bShallStop == TRUE) {
/* a handler that returns -1 will terminate the
czmq reactor loop
*/
return -1;
}
return 0;
}
/* called when runInput is called by rsyslog
*/
static rsRetVal rcv_loop(thrdInfo_t* pThrd){
size_t n_items = 0;
size_t i;
int rv;
zmq_pollitem_t* items = NULL;
poller_data* pollerData = NULL;
struct lstn_s* current;
instanceConf_t* inst;
DEFiRet;
/* now add listeners. This actually creates the sockets, etc... */
for (inst = runModConf->root; inst != NULL; inst=inst->next) {
addListener(inst);
}
if (lcnfRoot == NULL) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: no listeners were "
"started, input not activated.\n");
ABORT_FINALIZE(RS_RET_NO_RUN);
}
/* count the # of items first */
for(current=lcnfRoot;current!=NULL;current=current->next)
n_items++;
/* make arrays of pollitems, pollerdata so they are easy to delete later */
/* create the poll items*/
CHKmalloc(items = (zmq_pollitem_t*)MALLOC(sizeof(zmq_pollitem_t)*n_items));
/* create poller data (stuff to pass into the zmq closure called when we get a message)*/
CHKmalloc(pollerData = (poller_data*)MALLOC(sizeof(poller_data)*n_items));
/* loop through and initialize the poll items and poller_data arrays...*/
for(i=0, current = lcnfRoot; current != NULL; current = current->next, i++) {
/* create the socket, update items.*/
items[i].socket=current->sock;
items[i].events = ZMQ_POLLIN;
/* now update the poller_data for this item */
pollerData[i].thread = pThrd;
pollerData[i].ruleset = current->pRuleset;
}
s_zloop = zloop_new();
for(i=0; i<n_items; ++i) {
rv = zloop_poller(s_zloop, &items[i], handlePoll, &pollerData[i]);
if (rv) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: zloop_poller failed for item %zu: %s", i, zmq_strerror(errno));
}
}
DBGPRINTF("imzmq3: zloop_poller starting...");
zloop_start(s_zloop);
zloop_destroy(&s_zloop);
DBGPRINTF("imzmq3: zloop_poller stopped.");
finalize_it:
zctx_destroy(&s_context);
free(items);
free(pollerData);
RETiRet;
}
/* ----------------------------------------------------------------------------
* input module functions
*/
BEGINrunInput
CODESTARTrunInput
CHKiRet(rcv_loop(pThrd));
finalize_it:
RETiRet;
ENDrunInput
/* initialize and return if will run or not */
BEGINwillRun
CODESTARTwillRun
/* we need to create the inputName property (only once during our
lifetime) */
CHKiRet(prop.Construct(&s_namep));
CHKiRet(prop.SetString(s_namep,
UCHAR_CONSTANT("imzmq3"),
sizeof("imzmq3") - 1));
CHKiRet(prop.ConstructFinalize(s_namep));
finalize_it:
ENDwillRun
BEGINafterRun
CODESTARTafterRun
/* do cleanup here */
if (s_namep != NULL)
prop.Destruct(&s_namep);
ENDafterRun
BEGINmodExit
CODESTARTmodExit
/* release what we no longer need */
objRelease(errmsg, CORE_COMPONENT);
objRelease(glbl, CORE_COMPONENT);
objRelease(prop, CORE_COMPONENT);
objRelease(ruleset, CORE_COMPONENT);
ENDmodExit
BEGINisCompatibleWithFeature
CODESTARTisCompatibleWithFeature
if (eFeat == sFEATURENonCancelInputTermination)
iRet = RS_RET_OK;
ENDisCompatibleWithFeature
BEGINbeginCnfLoad
CODESTARTbeginCnfLoad
/* After endCnfLoad() (BEGINendCnfLoad...ENDendCnfLoad) is called,
* the pModConf pointer must not be used to change the in-memory
* config object. It's safe to use the same pointer for accessing
* the config object until freeCnf() (BEGINfreeCnf...ENDfreeCnf). */
runModConf = pModConf;
runModConf->pConf = pConf;
/* init module config */
runModConf->io_threads = 0; /* 0 means don't set it */
ENDbeginCnfLoad
BEGINsetModCnf
struct cnfparamvals* pvals = NULL;
int i;
CODESTARTsetModCnf
pvals = nvlstGetParams(lst, &modpblk, NULL);
if (NULL == pvals) {
errmsg.LogError(0, RS_RET_MISSING_CNFPARAMS, "imzmq3: error processing module "
" config parameters ['module(...)']");
ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
}
for (i=0; i < modpblk.nParams; ++i) {
if (!pvals[i].bUsed)
continue;
if (!strcmp(modpblk.descr[i].name, "ioThreads")) {
runModConf->io_threads = (int)pvals[i].val.d.n;
} else {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"imzmq3: config error, unknown "
"param %s in setModCnf\n",
modpblk.descr[i].name);
}
}
finalize_it:
if (pvals != NULL)
cnfparamvalsDestruct(pvals, &modpblk);
ENDsetModCnf
BEGINendCnfLoad
CODESTARTendCnfLoad
/* Last chance to make changes to the in-memory config object for this
* input module. After this call, the config object must no longer be
* changed. */
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
assert(pModConf == runModConf);
ENDendCnfLoad
/* function to generate error message if framework does not find requested ruleset */
static inline void
std_checkRuleset_genErrMsg(__attribute__((unused)) modConfData_t *modConf, instanceConf_t *inst)
{
errmsg.LogError(0, NO_ERRCODE, "imzmq3: ruleset '%s' for socket %s not found - "
"using default ruleset instead", inst->pszBindRuleset,
inst->description);
}
BEGINcheckCnf
instanceConf_t* inst;
CODESTARTcheckCnf
for(inst = pModConf->root; inst!=NULL; inst=inst->next) {
std_checkRuleset(pModConf, inst);
/* now, validate the instanceConf */
CHKiRet(validateConfig(inst));
}
finalize_it:
RETiRet;
ENDcheckCnf
BEGINactivateCnfPrePrivDrop
CODESTARTactivateCnfPrePrivDrop
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
assert(pModConf == runModConf);
/* first create the context */
createContext();
/* could setup context here, and set the global worker threads
and so on... */
ENDactivateCnfPrePrivDrop
BEGINactivateCnf
CODESTARTactivateCnf
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
assert(pModConf == runModConf);
ENDactivateCnf
BEGINfreeCnf
struct lstn_s *lstn, *lstn_r;
instanceConf_t *inst, *inst_r;
sublist *sub, *sub_r;
CODESTARTfreeCnf
DBGPRINTF("imzmq3: BEGINfreeCnf ...\n");
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
for (lstn = lcnfRoot; lstn != NULL; ) {
lstn_r = lstn;
lstn = lstn_r->next;
free(lstn_r);
}
for (inst = pModConf->root ; inst != NULL ; ) {
for (sub = inst->subscriptions; sub != NULL; ) {
free(sub->subscribe);
sub_r = sub;
sub = sub_r->next;
free(sub_r);
}
free(inst->pszBindRuleset);
inst_r = inst;
inst = inst->next;
free(inst_r);
}
ENDfreeCnf
BEGINnewInpInst
struct cnfparamvals* pvals;
CODESTARTnewInpInst
DBGPRINTF("newInpInst (imzmq3)\n");
pvals = nvlstGetParams(lst, &inppblk, NULL);
if(NULL==pvals) {
errmsg.LogError(0, RS_RET_MISSING_CNFPARAMS,
"imzmq3: required parameters are missing\n");
ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
}
DBGPRINTF("imzmq3: input param blk:\n");
cnfparamsPrint(&inppblk, pvals);
/* now, parse the config params and so on... */
CHKiRet(createListener(pvals));
finalize_it:
CODE_STD_FINALIZERnewInpInst
cnfparamvalsDestruct(pvals, &inppblk);
ENDnewInpInst
BEGINqueryEtryPt
CODESTARTqueryEtryPt
CODEqueryEtryPt_STD_IMOD_QUERIES
CODEqueryEtryPt_STD_CONF2_QUERIES
CODEqueryEtryPt_STD_CONF2_setModCnf_QUERIES
CODEqueryEtryPt_STD_CONF2_PREPRIVDROP_QUERIES
CODEqueryEtryPt_STD_CONF2_IMOD_QUERIES
CODEqueryEtryPt_IsCompatibleWithFeature_IF_OMOD_QUERIES
ENDqueryEtryPt
BEGINmodInit()
CODESTARTmodInit
/* we only support the current interface specification */
*ipIFVersProvided = CURR_MOD_IF_VERSION;
CODEmodInit_QueryRegCFSLineHdlr
CHKiRet(objUse(errmsg, CORE_COMPONENT));
CHKiRet(objUse(glbl, CORE_COMPONENT));
CHKiRet(objUse(prop, CORE_COMPONENT));
CHKiRet(objUse(ruleset, CORE_COMPONENT));
ENDmodInit
| ./CrossVul/dataset_final_sorted/CWE-134/c/bad_2610_0 |
crossvul-cpp_data_bad_2266_0 | /****************************************************************************
* RRDtool 1.4.8 Copyright by Tobi Oetiker, 1997-2013
****************************************************************************
* rrd__graph.c produce graphs from data in rrdfiles
****************************************************************************/
#include <sys/stat.h>
#ifdef WIN32
#include "strftime.h"
#endif
#include "rrd_tool.h"
/* for basename */
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#else
#include "plbasename.h"
#endif
#if defined(WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
#include <io.h>
#include <fcntl.h>
#endif
#include <time.h>
#include <locale.h>
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#include "rrd_graph.h"
#include "rrd_client.h"
/* some constant definitions */
#ifndef RRD_DEFAULT_FONT
/* there is special code later to pick Cour.ttf when running on windows */
#define RRD_DEFAULT_FONT "DejaVu Sans Mono,Bitstream Vera Sans Mono,monospace,Courier"
#endif
text_prop_t text_prop[] = {
{8.0, RRD_DEFAULT_FONT,NULL}
, /* default */
{9.0, RRD_DEFAULT_FONT,NULL}
, /* title */
{7.0, RRD_DEFAULT_FONT,NULL}
, /* axis */
{8.0, RRD_DEFAULT_FONT,NULL}
, /* unit */
{8.0, RRD_DEFAULT_FONT,NULL} /* legend */
,
{5.5, RRD_DEFAULT_FONT,NULL} /* watermark */
};
xlab_t xlab[] = {
{0, 0, TMT_SECOND, 30, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{2, 0, TMT_MINUTE, 1, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{5, 0, TMT_MINUTE, 2, TMT_MINUTE, 10, TMT_MINUTE, 10, 0, "%H:%M"}
,
{10, 0, TMT_MINUTE, 5, TMT_MINUTE, 20, TMT_MINUTE, 20, 0, "%H:%M"}
,
{30, 0, TMT_MINUTE, 10, TMT_HOUR, 1, TMT_HOUR, 1, 0, "%H:%M"}
,
{60, 0, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 2, 0, "%H:%M"}
,
{60, 24 * 3600, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 6, 0, "%a %H:%M"}
,
{180, 0, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 6, 0, "%H:%M"}
,
{180, 24 * 3600, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 12, 0, "%a %H:%M"}
,
/*{300, 0, TMT_HOUR,3, TMT_HOUR,12, TMT_HOUR,12, 12*3600,"%a %p"}, this looks silly */
{600, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%a"}
,
{1200, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%d"}
,
{1800, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a %d"}
,
{2400, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a"}
,
{3600, 0, TMT_DAY, 1, TMT_WEEK, 1, TMT_WEEK, 1, 7 * 24 * 3600, "Week %V"}
,
{3 * 3600, 0, TMT_WEEK, 1, TMT_MONTH, 1, TMT_WEEK, 2, 7 * 24 * 3600, "Week %V"}
,
{6 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 1, TMT_MONTH, 1, 30 * 24 * 3600,
"%b"}
,
{48 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 3, TMT_MONTH, 3, 30 * 24 * 3600,
"%b"}
,
{315360, 0, TMT_MONTH, 3, TMT_YEAR, 1, TMT_YEAR, 1, 365 * 24 * 3600, "%Y"}
,
{10 * 24 * 3600, 0, TMT_YEAR, 1, TMT_YEAR, 1, TMT_YEAR, 1,
365 * 24 * 3600, "%y"}
,
{-1, 0, TMT_MONTH, 0, TMT_MONTH, 0, TMT_MONTH, 0, 0, ""}
};
/* sensible y label intervals ...*/
ylab_t ylab[] = {
{0.1, {1, 2, 5, 10}
}
,
{0.2, {1, 5, 10, 20}
}
,
{0.5, {1, 2, 4, 10}
}
,
{1.0, {1, 2, 5, 10}
}
,
{2.0, {1, 5, 10, 20}
}
,
{5.0, {1, 2, 4, 10}
}
,
{10.0, {1, 2, 5, 10}
}
,
{20.0, {1, 5, 10, 20}
}
,
{50.0, {1, 2, 4, 10}
}
,
{100.0, {1, 2, 5, 10}
}
,
{200.0, {1, 5, 10, 20}
}
,
{500.0, {1, 2, 4, 10}
}
,
{0.0, {0, 0, 0, 0}
}
};
gfx_color_t graph_col[] = /* default colors */
{
{1.00, 1.00, 1.00, 1.00}, /* canvas */
{0.95, 0.95, 0.95, 1.00}, /* background */
{0.81, 0.81, 0.81, 1.00}, /* shade A */
{0.62, 0.62, 0.62, 1.00}, /* shade B */
{0.56, 0.56, 0.56, 0.75}, /* grid */
{0.87, 0.31, 0.31, 0.60}, /* major grid */
{0.00, 0.00, 0.00, 1.00}, /* font */
{0.50, 0.12, 0.12, 1.00}, /* arrow */
{0.12, 0.12, 0.12, 1.00}, /* axis */
{0.00, 0.00, 0.00, 1.00} /* frame */
};
/* #define DEBUG */
#ifdef DEBUG
# define DPRINT(x) (void)(printf x, printf("\n"))
#else
# define DPRINT(x)
#endif
/* initialize with xtr(im,0); */
int xtr(
image_desc_t *im,
time_t mytime)
{
static double pixie;
if (mytime == 0) {
pixie = (double) im->xsize / (double) (im->end - im->start);
return im->xorigin;
}
return (int) ((double) im->xorigin + pixie * (mytime - im->start));
}
/* translate data values into y coordinates */
double ytr(
image_desc_t *im,
double value)
{
static double pixie;
double yval;
if (isnan(value)) {
if (!im->logarithmic)
pixie = (double) im->ysize / (im->maxval - im->minval);
else
pixie =
(double) im->ysize / (log10(im->maxval) - log10(im->minval));
yval = im->yorigin;
} else if (!im->logarithmic) {
yval = im->yorigin - pixie * (value - im->minval);
} else {
if (value < im->minval) {
yval = im->yorigin;
} else {
yval = im->yorigin - pixie * (log10(value) - log10(im->minval));
}
}
return yval;
}
/* conversion function for symbolic entry names */
#define conv_if(VV,VVV) \
if (strcmp(#VV, string) == 0) return VVV ;
enum gf_en gf_conv(
char *string)
{
conv_if(PRINT, GF_PRINT);
conv_if(GPRINT, GF_GPRINT);
conv_if(COMMENT, GF_COMMENT);
conv_if(HRULE, GF_HRULE);
conv_if(VRULE, GF_VRULE);
conv_if(LINE, GF_LINE);
conv_if(AREA, GF_AREA);
conv_if(STACK, GF_STACK);
conv_if(TICK, GF_TICK);
conv_if(TEXTALIGN, GF_TEXTALIGN);
conv_if(DEF, GF_DEF);
conv_if(CDEF, GF_CDEF);
conv_if(VDEF, GF_VDEF);
conv_if(XPORT, GF_XPORT);
conv_if(SHIFT, GF_SHIFT);
return (enum gf_en)(-1);
}
enum gfx_if_en if_conv(
char *string)
{
conv_if(PNG, IF_PNG);
conv_if(SVG, IF_SVG);
conv_if(EPS, IF_EPS);
conv_if(PDF, IF_PDF);
return (enum gfx_if_en)(-1);
}
enum tmt_en tmt_conv(
char *string)
{
conv_if(SECOND, TMT_SECOND);
conv_if(MINUTE, TMT_MINUTE);
conv_if(HOUR, TMT_HOUR);
conv_if(DAY, TMT_DAY);
conv_if(WEEK, TMT_WEEK);
conv_if(MONTH, TMT_MONTH);
conv_if(YEAR, TMT_YEAR);
return (enum tmt_en)(-1);
}
enum grc_en grc_conv(
char *string)
{
conv_if(BACK, GRC_BACK);
conv_if(CANVAS, GRC_CANVAS);
conv_if(SHADEA, GRC_SHADEA);
conv_if(SHADEB, GRC_SHADEB);
conv_if(GRID, GRC_GRID);
conv_if(MGRID, GRC_MGRID);
conv_if(FONT, GRC_FONT);
conv_if(ARROW, GRC_ARROW);
conv_if(AXIS, GRC_AXIS);
conv_if(FRAME, GRC_FRAME);
return (enum grc_en)(-1);
}
enum text_prop_en text_prop_conv(
char *string)
{
conv_if(DEFAULT, TEXT_PROP_DEFAULT);
conv_if(TITLE, TEXT_PROP_TITLE);
conv_if(AXIS, TEXT_PROP_AXIS);
conv_if(UNIT, TEXT_PROP_UNIT);
conv_if(LEGEND, TEXT_PROP_LEGEND);
conv_if(WATERMARK, TEXT_PROP_WATERMARK);
return (enum text_prop_en)(-1);
}
#undef conv_if
int im_free(
image_desc_t *im)
{
unsigned long i, ii;
cairo_status_t status = (cairo_status_t) 0;
if (im == NULL)
return 0;
if (im->daemon_addr != NULL)
free(im->daemon_addr);
if (im->gdef_map){
g_hash_table_destroy(im->gdef_map);
}
if (im->rrd_map){
g_hash_table_destroy(im->rrd_map);
}
for (i = 0; i < (unsigned) im->gdes_c; i++) {
if (im->gdes[i].data_first) {
/* careful here, because a single pointer can occur several times */
free(im->gdes[i].data);
if (im->gdes[i].ds_namv) {
for (ii = 0; ii < im->gdes[i].ds_cnt; ii++)
free(im->gdes[i].ds_namv[ii]);
free(im->gdes[i].ds_namv);
}
}
/* free allocated memory used for dashed lines */
if (im->gdes[i].p_dashes != NULL)
free(im->gdes[i].p_dashes);
free(im->gdes[i].p_data);
free(im->gdes[i].rpnp);
}
free(im->gdes);
for (i = 0; i < DIM(text_prop);i++){
pango_font_description_free(im->text_prop[i].font_desc);
im->text_prop[i].font_desc = NULL;
}
if (im->font_options)
cairo_font_options_destroy(im->font_options);
if (im->cr) {
status = cairo_status(im->cr);
cairo_destroy(im->cr);
}
if (im->rendered_image) {
free(im->rendered_image);
}
if (im->layout) {
g_object_unref (im->layout);
}
if (im->surface)
cairo_surface_destroy(im->surface);
if (status)
fprintf(stderr, "OOPS: Cairo has issues it can't even die: %s\n",
cairo_status_to_string(status));
return 0;
}
/* find SI magnitude symbol for the given number*/
void auto_scale(
image_desc_t *im, /* image description */
double *value,
char **symb_ptr,
double *magfact)
{
char *symbol[] = { "a", /* 10e-18 Atto */
"f", /* 10e-15 Femto */
"p", /* 10e-12 Pico */
"n", /* 10e-9 Nano */
"u", /* 10e-6 Micro */
"m", /* 10e-3 Milli */
" ", /* Base */
"k", /* 10e3 Kilo */
"M", /* 10e6 Mega */
"G", /* 10e9 Giga */
"T", /* 10e12 Tera */
"P", /* 10e15 Peta */
"E"
}; /* 10e18 Exa */
int symbcenter = 6;
int sindex;
if (*value == 0.0 || isnan(*value)) {
sindex = 0;
*magfact = 1.0;
} else {
sindex = floor(log(fabs(*value)) / log((double) im->base));
*magfact = pow((double) im->base, (double) sindex);
(*value) /= (*magfact);
}
if (sindex <= symbcenter && sindex >= -symbcenter) {
(*symb_ptr) = symbol[sindex + symbcenter];
} else {
(*symb_ptr) = "?";
}
}
/* power prefixes */
static char si_symbol[] = {
'y', /* 10e-24 Yocto */
'z', /* 10e-21 Zepto */
'a', /* 10e-18 Atto */
'f', /* 10e-15 Femto */
'p', /* 10e-12 Pico */
'n', /* 10e-9 Nano */
'u', /* 10e-6 Micro */
'm', /* 10e-3 Milli */
' ', /* Base */
'k', /* 10e3 Kilo */
'M', /* 10e6 Mega */
'G', /* 10e9 Giga */
'T', /* 10e12 Tera */
'P', /* 10e15 Peta */
'E', /* 10e18 Exa */
'Z', /* 10e21 Zeta */
'Y' /* 10e24 Yotta */
};
static const int si_symbcenter = 8;
/* find SI magnitude symbol for the numbers on the y-axis*/
void si_unit(
image_desc_t *im /* image description */
)
{
double digits, viewdigits = 0;
digits =
floor(log(max(fabs(im->minval), fabs(im->maxval))) /
log((double) im->base));
if (im->unitsexponent != 9999) {
/* unitsexponent = 9, 6, 3, 0, -3, -6, -9, etc */
viewdigits = floor((double)(im->unitsexponent / 3));
} else {
viewdigits = digits;
}
im->magfact = pow((double) im->base, digits);
#ifdef DEBUG
printf("digits %6.3f im->magfact %6.3f\n", digits, im->magfact);
#endif
im->viewfactor = im->magfact / pow((double) im->base, viewdigits);
if (((viewdigits + si_symbcenter) < sizeof(si_symbol)) &&
((viewdigits + si_symbcenter) >= 0))
im->symbol = si_symbol[(int) viewdigits + si_symbcenter];
else
im->symbol = '?';
}
/* move min and max values around to become sensible */
void expand_range(
image_desc_t *im)
{
double sensiblevalues[] = { 1000.0, 900.0, 800.0, 750.0, 700.0,
600.0, 500.0, 400.0, 300.0, 250.0,
200.0, 125.0, 100.0, 90.0, 80.0,
75.0, 70.0, 60.0, 50.0, 40.0, 30.0,
25.0, 20.0, 10.0, 9.0, 8.0,
7.0, 6.0, 5.0, 4.0, 3.5, 3.0,
2.5, 2.0, 1.8, 1.5, 1.2, 1.0,
0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0, -1
};
double scaled_min, scaled_max;
double adj;
int i;
#ifdef DEBUG
printf("Min: %6.2f Max: %6.2f MagFactor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTAUTOSCALE) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher then max/min vals
so we can see amplitude on the graph */
double delt, fact;
delt = im->maxval - im->minval;
adj = delt * 0.1;
fact = 2.0 * pow(10.0,
floor(log10
(max(fabs(im->minval), fabs(im->maxval)) /
im->magfact)) - 2);
if (delt < fact) {
adj = (fact - delt) * 0.55;
#ifdef DEBUG
printf
("Min: %6.2f Max: %6.2f delt: %6.2f fact: %6.2f adj: %6.2f\n",
im->minval, im->maxval, delt, fact, adj);
#endif
}
im->minval -= adj;
im->maxval += adj;
} else if (im->extra_flags & ALTAUTOSCALE_MIN) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly lower than min vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->minval -= adj;
} else if (im->extra_flags & ALTAUTOSCALE_MAX) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher than max vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->maxval += adj;
} else {
scaled_min = im->minval / im->magfact;
scaled_max = im->maxval / im->magfact;
for (i = 1; sensiblevalues[i] > 0; i++) {
if (sensiblevalues[i - 1] >= scaled_min &&
sensiblevalues[i] <= scaled_min)
im->minval = sensiblevalues[i] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_min &&
-sensiblevalues[i] >= scaled_min)
im->minval = -sensiblevalues[i - 1] * (im->magfact);
if (sensiblevalues[i - 1] >= scaled_max &&
sensiblevalues[i] <= scaled_max)
im->maxval = sensiblevalues[i - 1] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_max &&
-sensiblevalues[i] >= scaled_max)
im->maxval = -sensiblevalues[i] * (im->magfact);
}
}
} else {
/* adjust min and max to the grid definition if there is one */
im->minval = (double) im->ylabfact * im->ygridstep *
floor(im->minval / ((double) im->ylabfact * im->ygridstep));
im->maxval = (double) im->ylabfact * im->ygridstep *
ceil(im->maxval / ((double) im->ylabfact * im->ygridstep));
}
#ifdef DEBUG
fprintf(stderr, "SCALED Min: %6.2f Max: %6.2f Factor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
}
void apply_gridfit(
image_desc_t *im)
{
if (isnan(im->minval) || isnan(im->maxval))
return;
ytr(im, DNAN);
if (im->logarithmic) {
double ya, yb, ypix, ypixfrac;
double log10_range = log10(im->maxval) - log10(im->minval);
ya = pow((double) 10, floor(log10(im->minval)));
while (ya < im->minval)
ya *= 10;
if (ya > im->maxval)
return; /* don't have y=10^x gridline */
yb = ya * 10;
if (yb <= im->maxval) {
/* we have at least 2 y=10^x gridlines.
Make sure distance between them in pixels
are an integer by expanding im->maxval */
double y_pixel_delta = ytr(im, ya) - ytr(im, yb);
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_log10_range = factor * log10_range;
double new_ymax_log10 = log10(im->minval) + new_log10_range;
im->maxval = pow(10, new_ymax_log10);
ytr(im, DNAN); /* reset precalc */
log10_range = log10(im->maxval) - log10(im->minval);
}
/* make sure first y=10^x gridline is located on
integer pixel position by moving scale slightly
downwards (sub-pixel movement) */
ypix = ytr(im, ya) + im->ysize; /* add im->ysize so it always is positive */
ypixfrac = ypix - floor(ypix);
if (ypixfrac > 0 && ypixfrac < 1) {
double yfrac = ypixfrac / im->ysize;
im->minval = pow(10, log10(im->minval) - yfrac * log10_range);
im->maxval = pow(10, log10(im->maxval) - yfrac * log10_range);
ytr(im, DNAN); /* reset precalc */
}
} else {
/* Make sure we have an integer pixel distance between
each minor gridline */
double ypos1 = ytr(im, im->minval);
double ypos2 = ytr(im, im->minval + im->ygrid_scale.gridstep);
double y_pixel_delta = ypos1 - ypos2;
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_range = factor * (im->maxval - im->minval);
double gridstep = im->ygrid_scale.gridstep;
double minor_y, minor_y_px, minor_y_px_frac;
if (im->maxval > 0.0)
im->maxval = im->minval + new_range;
else
im->minval = im->maxval - new_range;
ytr(im, DNAN); /* reset precalc */
/* make sure first minor gridline is on integer pixel y coord */
minor_y = gridstep * floor(im->minval / gridstep);
while (minor_y < im->minval)
minor_y += gridstep;
minor_y_px = ytr(im, minor_y) + im->ysize; /* ensure > 0 by adding ysize */
minor_y_px_frac = minor_y_px - floor(minor_y_px);
if (minor_y_px_frac > 0 && minor_y_px_frac < 1) {
double yfrac = minor_y_px_frac / im->ysize;
double range = im->maxval - im->minval;
im->minval = im->minval - yfrac * range;
im->maxval = im->maxval - yfrac * range;
ytr(im, DNAN); /* reset precalc */
}
calc_horizontal_grid(im); /* recalc with changed im->maxval */
}
}
/* reduce data reimplementation by Alex */
void reduce_data(
enum cf_en cf, /* which consolidation function ? */
unsigned long cur_step, /* step the data currently is in */
time_t *start, /* start, end and step as requested ... */
time_t *end, /* ... by the application will be ... */
unsigned long *step, /* ... adjusted to represent reality */
unsigned long *ds_cnt, /* number of data sources in file */
rrd_value_t **data)
{ /* two dimensional array containing the data */
int i, reduce_factor = ceil((double) (*step) / (double) cur_step);
unsigned long col, dst_row, row_cnt, start_offset, end_offset, skiprows =
0;
rrd_value_t *srcptr, *dstptr;
(*step) = cur_step * reduce_factor; /* set new step size for reduced data */
dstptr = *data;
srcptr = *data;
row_cnt = ((*end) - (*start)) / cur_step;
#ifdef DEBUG
#define DEBUG_REDUCE
#endif
#ifdef DEBUG_REDUCE
printf("Reducing %lu rows with factor %i time %lu to %lu, step %lu\n",
row_cnt, reduce_factor, *start, *end, cur_step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * cur_step);
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
/* We have to combine [reduce_factor] rows of the source
** into one row for the destination. Doing this we also
** need to take care to combine the correct rows. First
** alter the start and end time so that they are multiples
** of the new step time. We cannot reduce the amount of
** time so we have to move the end towards the future and
** the start towards the past.
*/
end_offset = (*end) % (*step);
start_offset = (*start) % (*step);
/* If there is a start offset (which cannot be more than
** one destination row), skip the appropriate number of
** source rows and one destination row. The appropriate
** number is what we do know (start_offset/cur_step) of
** the new interval (*step/cur_step aka reduce_factor).
*/
#ifdef DEBUG_REDUCE
printf("start_offset: %lu end_offset: %lu\n", start_offset, end_offset);
printf("row_cnt before: %lu\n", row_cnt);
#endif
if (start_offset) {
(*start) = (*start) - start_offset;
skiprows = reduce_factor - start_offset / cur_step;
srcptr += skiprows * *ds_cnt;
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt between: %lu\n", row_cnt);
#endif
/* At the end we have some rows that are not going to be
** used, the amount is end_offset/cur_step
*/
if (end_offset) {
(*end) = (*end) - end_offset + (*step);
skiprows = end_offset / cur_step;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt after: %lu\n", row_cnt);
#endif
/* Sanity check: row_cnt should be multiple of reduce_factor */
/* if this gets triggered, something is REALLY WRONG ... we die immediately */
if (row_cnt % reduce_factor) {
printf("SANITY CHECK: %lu rows cannot be reduced by %i \n",
row_cnt, reduce_factor);
printf("BUG in reduce_data()\n");
exit(1);
}
/* Now combine reduce_factor intervals at a time
** into one interval for the destination.
*/
for (dst_row = 0; (long int) row_cnt >= reduce_factor; dst_row++) {
for (col = 0; col < (*ds_cnt); col++) {
rrd_value_t newval = DNAN;
unsigned long validval = 0;
for (i = 0; i < reduce_factor; i++) {
if (isnan(srcptr[i * (*ds_cnt) + col])) {
continue;
}
validval++;
if (isnan(newval))
newval = srcptr[i * (*ds_cnt) + col];
else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval += srcptr[i * (*ds_cnt) + col];
break;
case CF_MINIMUM:
newval = min(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_FAILURES:
/* an interval contains a failure if any subintervals contained a failure */
case CF_MAXIMUM:
newval = max(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_LAST:
newval = srcptr[i * (*ds_cnt) + col];
break;
}
}
}
if (validval == 0) {
newval = DNAN;
} else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval /= validval;
break;
case CF_MINIMUM:
case CF_FAILURES:
case CF_MAXIMUM:
case CF_LAST:
break;
}
}
*dstptr++ = newval;
}
srcptr += (*ds_cnt) * reduce_factor;
row_cnt -= reduce_factor;
}
/* If we had to alter the endtime, we didn't have enough
** source rows to fill the last row. Fill it with NaN.
*/
if (end_offset)
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
#ifdef DEBUG_REDUCE
row_cnt = ((*end) - (*start)) / *step;
srcptr = *data;
printf("Done reducing. Currently %lu rows, time %lu to %lu, step %lu\n",
row_cnt, *start, *end, *step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * (*step));
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
}
/* get the data required for the graphs from the
relevant rrds ... */
int data_fetch(
image_desc_t *im)
{
int i, ii;
/* pull the data from the rrd files ... */
for (i = 0; i < (int) im->gdes_c; i++) {
/* only GF_DEF elements fetch data */
if (im->gdes[i].gf != GF_DEF)
continue;
/* do we have it already ? */
gpointer value;
char *key = gdes_fetch_key(im->gdes[i]);
gboolean ok = g_hash_table_lookup_extended(im->rrd_map,key,NULL,&value);
free(key);
if (ok){
ii = GPOINTER_TO_INT(value);
im->gdes[i].start = im->gdes[ii].start;
im->gdes[i].end = im->gdes[ii].end;
im->gdes[i].step = im->gdes[ii].step;
im->gdes[i].ds_cnt = im->gdes[ii].ds_cnt;
im->gdes[i].ds_namv = im->gdes[ii].ds_namv;
im->gdes[i].data = im->gdes[ii].data;
im->gdes[i].data_first = 0;
} else {
unsigned long ft_step = im->gdes[i].step; /* ft_step will record what we got from fetch */
/* Flush the file if
* - a connection to the daemon has been established
* - this is the first occurrence of that RRD file
*/
if (rrdc_is_connected(im->daemon_addr))
{
int status;
status = 0;
for (ii = 0; ii < i; ii++)
{
if (strcmp (im->gdes[i].rrd, im->gdes[ii].rrd) == 0)
{
status = 1;
break;
}
}
if (status == 0)
{
status = rrdc_flush (im->gdes[i].rrd);
if (status != 0)
{
rrd_set_error ("rrdc_flush (%s) failed with status %i.",
im->gdes[i].rrd, status);
return (-1);
}
}
} /* if (rrdc_is_connected()) */
if ((rrd_fetch_fn(im->gdes[i].rrd,
im->gdes[i].cf,
&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
&im->gdes[i].ds_namv,
&im->gdes[i].data)) == -1) {
return -1;
}
im->gdes[i].data_first = 1;
/* must reduce to at least im->step
otherwhise we end up with more data than we can handle in the
chart and visibility of data will be random */
im->gdes[i].step = max(im->gdes[i].step,im->step);
if (ft_step < im->gdes[i].step) {
reduce_data(im->gdes[i].cf_reduce,
ft_step,
&im->gdes[i].start,
&im->gdes[i].end,
&im->gdes[i].step,
&im->gdes[i].ds_cnt, &im->gdes[i].data);
} else {
im->gdes[i].step = ft_step;
}
}
/* lets see if the required data source is really there */
for (ii = 0; ii < (int) im->gdes[i].ds_cnt; ii++) {
if (strcmp(im->gdes[i].ds_namv[ii], im->gdes[i].ds_nam) == 0) {
im->gdes[i].ds = ii;
}
}
if (im->gdes[i].ds == -1) {
rrd_set_error("No DS called '%s' in '%s'",
im->gdes[i].ds_nam, im->gdes[i].rrd);
return -1;
}
}
return 0;
}
/* evaluate the expressions in the CDEF functions */
/*************************************************************
* CDEF stuff
*************************************************************/
long find_var_wrapper(
void *arg1,
char *key)
{
return find_var((image_desc_t *) arg1, key);
}
/* find gdes containing var*/
long find_var(
image_desc_t *im,
char *key)
{
long match = -1;
gpointer value;
gboolean ok = g_hash_table_lookup_extended(im->gdef_map,key,NULL,&value);
if (ok){
match = GPOINTER_TO_INT(value);
}
/* printf("%s -> %ld\n",key,match); */
return match;
}
/* find the greatest common divisor for all the numbers
in the 0 terminated num array */
long lcd(
long *num)
{
long rest;
int i;
for (i = 0; num[i + 1] != 0; i++) {
do {
rest = num[i] % num[i + 1];
num[i] = num[i + 1];
num[i + 1] = rest;
} while (rest != 0);
num[i + 1] = num[i];
}
/* return i==0?num[i]:num[i-1]; */
return num[i];
}
/* run the rpn calculator on all the VDEF and CDEF arguments */
int data_calc(
image_desc_t *im)
{
int gdi;
int dataidx;
long *steparray, rpi;
int stepcnt;
time_t now;
rpnstack_t rpnstack;
rpnstack_init(&rpnstack);
for (gdi = 0; gdi < im->gdes_c; gdi++) {
/* Look for GF_VDEF and GF_CDEF in the same loop,
* so CDEFs can use VDEFs and vice versa
*/
switch (im->gdes[gdi].gf) {
case GF_XPORT:
break;
case GF_SHIFT:{
graph_desc_t *vdp = &im->gdes[im->gdes[gdi].vidx];
/* remove current shift */
vdp->start -= vdp->shift;
vdp->end -= vdp->shift;
/* vdef */
if (im->gdes[gdi].shidx >= 0)
vdp->shift = im->gdes[im->gdes[gdi].shidx].vf.val;
/* constant */
else
vdp->shift = im->gdes[gdi].shval;
/* normalize shift to multiple of consolidated step */
vdp->shift = (vdp->shift / (long) vdp->step) * (long) vdp->step;
/* apply shift */
vdp->start += vdp->shift;
vdp->end += vdp->shift;
break;
}
case GF_VDEF:
/* A VDEF has no DS. This also signals other parts
* of rrdtool that this is a VDEF value, not a CDEF.
*/
im->gdes[gdi].ds_cnt = 0;
if (vdef_calc(im, gdi)) {
rrd_set_error("Error processing VDEF '%s'",
im->gdes[gdi].vname);
rpnstack_free(&rpnstack);
return -1;
}
break;
case GF_CDEF:
im->gdes[gdi].ds_cnt = 1;
im->gdes[gdi].ds = 0;
im->gdes[gdi].data_first = 1;
im->gdes[gdi].start = 0;
im->gdes[gdi].end = 0;
steparray = NULL;
stepcnt = 0;
dataidx = -1;
/* Find the variables in the expression.
* - VDEF variables are substituted by their values
* and the opcode is changed into OP_NUMBER.
* - CDEF variables are analized for their step size,
* the lowest common denominator of all the step
* sizes of the data sources involved is calculated
* and the resulting number is the step size for the
* resulting data source.
*/
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
if (im->gdes[ptr].ds_cnt == 0) { /* this is a VDEF data source */
#if 0
printf
("DEBUG: inside CDEF '%s' processing VDEF '%s'\n",
im->gdes[gdi].vname, im->gdes[ptr].vname);
printf("DEBUG: value from vdef is %f\n",
im->gdes[ptr].vf.val);
#endif
im->gdes[gdi].rpnp[rpi].val = im->gdes[ptr].vf.val;
im->gdes[gdi].rpnp[rpi].op = OP_NUMBER;
} else { /* normal variables and PREF(variables) */
/* add one entry to the array that keeps track of the step sizes of the
* data sources going into the CDEF. */
if ((steparray =
(long*)rrd_realloc(steparray,
(++stepcnt +
1) * sizeof(*steparray))) == NULL) {
rrd_set_error("realloc steparray");
rpnstack_free(&rpnstack);
return -1;
};
steparray[stepcnt - 1] = im->gdes[ptr].step;
/* adjust start and end of cdef (gdi) so
* that it runs from the latest start point
* to the earliest endpoint of any of the
* rras involved (ptr)
*/
if (im->gdes[gdi].start < im->gdes[ptr].start)
im->gdes[gdi].start = im->gdes[ptr].start;
if (im->gdes[gdi].end == 0 ||
im->gdes[gdi].end > im->gdes[ptr].end)
im->gdes[gdi].end = im->gdes[ptr].end;
/* store pointer to the first element of
* the rra providing data for variable,
* further save step size and data source
* count of this rra
*/
im->gdes[gdi].rpnp[rpi].data =
im->gdes[ptr].data + im->gdes[ptr].ds;
im->gdes[gdi].rpnp[rpi].step = im->gdes[ptr].step;
im->gdes[gdi].rpnp[rpi].ds_cnt = im->gdes[ptr].ds_cnt;
/* backoff the *.data ptr; this is done so
* rpncalc() function doesn't have to treat
* the first case differently
*/
} /* if ds_cnt != 0 */
} /* if OP_VARIABLE */
} /* loop through all rpi */
/* move the data pointers to the correct period */
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
long diff =
im->gdes[gdi].start - im->gdes[ptr].start;
if (diff > 0)
im->gdes[gdi].rpnp[rpi].data +=
(diff / im->gdes[ptr].step) *
im->gdes[ptr].ds_cnt;
}
}
if (steparray == NULL) {
rrd_set_error("rpn expressions without DEF"
" or CDEF variables are not supported");
rpnstack_free(&rpnstack);
return -1;
}
steparray[stepcnt] = 0;
/* Now find the resulting step. All steps in all
* used RRAs have to be visited
*/
im->gdes[gdi].step = lcd(steparray);
free(steparray);
if ((im->gdes[gdi].data = (rrd_value_t*)malloc(((im->gdes[gdi].end -
im->gdes[gdi].start)
/ im->gdes[gdi].step)
* sizeof(double))) == NULL) {
rrd_set_error("malloc im->gdes[gdi].data");
rpnstack_free(&rpnstack);
return -1;
}
/* Step through the new cdef results array and
* calculate the values
*/
for (now = im->gdes[gdi].start + im->gdes[gdi].step;
now <= im->gdes[gdi].end; now += im->gdes[gdi].step) {
rpnp_t *rpnp = im->gdes[gdi].rpnp;
/* 3rd arg of rpn_calc is for OP_VARIABLE lookups;
* in this case we are advancing by timesteps;
* we use the fact that time_t is a synonym for long
*/
if (rpn_calc(rpnp, &rpnstack, (long) now,
im->gdes[gdi].data, ++dataidx) == -1) {
/* rpn_calc sets the error string */
rpnstack_free(&rpnstack);
return -1;
}
} /* enumerate over time steps within a CDEF */
break;
default:
continue;
}
} /* enumerate over CDEFs */
rpnstack_free(&rpnstack);
return 0;
}
/* from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm */
/* yes we are loosing precision by doing tos with floats instead of doubles
but it seems more stable this way. */
static int AlmostEqual2sComplement(
float A,
float B,
int maxUlps)
{
int aInt = *(int *) &A;
int bInt = *(int *) &B;
int intDiff;
/* Make sure maxUlps is non-negative and small enough that the
default NAN won't compare as equal to anything. */
/* assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024); */
/* Make aInt lexicographically ordered as a twos-complement int */
if (aInt < 0)
aInt = 0x80000000l - aInt;
/* Make bInt lexicographically ordered as a twos-complement int */
if (bInt < 0)
bInt = 0x80000000l - bInt;
intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return 1;
return 0;
}
/* massage data so, that we get one value for each x coordinate in the graph */
int data_proc(
image_desc_t *im)
{
long i, ii;
double pixstep = (double) (im->end - im->start)
/ (double) im->xsize; /* how much time
passes in one pixel */
double paintval;
double minval = DNAN, maxval = DNAN;
unsigned long gr_time;
/* memory for the processed data */
for (i = 0; i < im->gdes_c; i++) {
if ((im->gdes[i].gf == GF_LINE) ||
(im->gdes[i].gf == GF_AREA) || (im->gdes[i].gf == GF_TICK)) {
if ((im->gdes[i].p_data = (rrd_value_t*)malloc((im->xsize + 1)
* sizeof(rrd_value_t))) == NULL) {
rrd_set_error("malloc data_proc");
return -1;
}
}
}
for (i = 0; i < im->xsize; i++) { /* for each pixel */
long vidx;
gr_time = im->start + pixstep * i; /* time of the current step */
paintval = 0.0;
for (ii = 0; ii < im->gdes_c; ii++) {
double value;
switch (im->gdes[ii].gf) {
case GF_LINE:
case GF_AREA:
case GF_TICK:
if (!im->gdes[ii].stack)
paintval = 0.0;
value = im->gdes[ii].yrule;
if (isnan(value) || (im->gdes[ii].gf == GF_TICK)) {
/* The time of the data doesn't necessarily match
** the time of the graph. Beware.
*/
vidx = im->gdes[ii].vidx;
if (im->gdes[vidx].gf == GF_VDEF) {
value = im->gdes[vidx].vf.val;
} else
if (((long int) gr_time >=
(long int) im->gdes[vidx].start)
&& ((long int) gr_time <
(long int) im->gdes[vidx].end)) {
value = im->gdes[vidx].data[(unsigned long)
floor((double)
(gr_time -
im->gdes[vidx].
start)
/
im->gdes[vidx].step)
* im->gdes[vidx].ds_cnt +
im->gdes[vidx].ds];
} else {
value = DNAN;
}
};
if (!isnan(value)) {
paintval += value;
im->gdes[ii].p_data[i] = paintval;
/* GF_TICK: the data values are not
** relevant for min and max
*/
if (finite(paintval) && im->gdes[ii].gf != GF_TICK && !im->gdes[ii].skipscale) {
if ((isnan(minval) || paintval < minval) &&
!(im->logarithmic && paintval <= 0.0))
minval = paintval;
if (isnan(maxval) || paintval > maxval)
maxval = paintval;
}
} else {
im->gdes[ii].p_data[i] = DNAN;
}
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
default:
break;
}
}
}
/* if min or max have not been asigned a value this is because
there was no data in the graph ... this is not good ...
lets set these to dummy values then ... */
if (im->logarithmic) {
if (isnan(minval) || isnan(maxval) || maxval <= 0) {
minval = 0.0; /* catching this right away below */
maxval = 5.1;
}
/* in logarithm mode, where minval is smaller or equal
to 0 make the beast just way smaller than maxval */
if (minval <= 0) {
minval = maxval / 10e8;
}
} else {
if (isnan(minval) || isnan(maxval)) {
minval = 0.0;
maxval = 1.0;
}
}
/* adjust min and max values given by the user */
/* for logscale we add something on top */
if (isnan(im->minval)
|| ((!im->rigid) && im->minval > minval)
) {
if (im->logarithmic)
im->minval = minval / 2.0;
else
im->minval = minval;
}
if (isnan(im->maxval)
|| (!im->rigid && im->maxval < maxval)
) {
if (im->logarithmic)
im->maxval = maxval * 2.0;
else
im->maxval = maxval;
}
/* make sure min is smaller than max */
if (im->minval > im->maxval) {
if (im->minval > 0)
im->minval = 0.99 * im->maxval;
else
im->minval = 1.01 * im->maxval;
}
/* make sure min and max are not equal */
if (AlmostEqual2sComplement(im->minval, im->maxval, 4)) {
if (im->maxval > 0)
im->maxval *= 1.01;
else
im->maxval *= 0.99;
/* make sure min and max are not both zero */
if (AlmostEqual2sComplement(im->maxval, 0, 4)) {
im->maxval = 1.0;
}
}
return 0;
}
static int find_first_weekday(void){
static int first_weekday = -1;
if (first_weekday == -1){
#ifdef HAVE__NL_TIME_WEEK_1STDAY
/* according to http://sourceware.org/ml/libc-locales/2009-q1/msg00011.html */
/* See correct way here http://pasky.or.cz/dev/glibc/first_weekday.c */
first_weekday = nl_langinfo (_NL_TIME_FIRST_WEEKDAY)[0];
int week_1stday;
long week_1stday_l = (long) nl_langinfo (_NL_TIME_WEEK_1STDAY);
if (week_1stday_l == 19971130) week_1stday = 0; /* Sun */
else if (week_1stday_l == 19971201) week_1stday = 1; /* Mon */
else
{
first_weekday = 1;
return first_weekday; /* we go for a monday default */
}
first_weekday=(week_1stday + first_weekday - 1) % 7;
#else
first_weekday = 1;
#endif
}
return first_weekday;
}
/* identify the point where the first gridline, label ... gets placed */
time_t find_first_time(
time_t start, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
localtime_r(&start, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
switch (baseint) {
case TMT_SECOND:
tm. tm_sec -= tm.tm_sec % basestep;
break;
case TMT_MINUTE:
tm. tm_sec = 0;
tm. tm_min -= tm.tm_min % basestep;
break;
case TMT_HOUR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour -= tm.tm_hour % basestep;
break;
case TMT_DAY:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
break;
case TMT_WEEK:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday -= tm.tm_wday - find_first_weekday();
if (tm.tm_wday == 0 && find_first_weekday() > 0)
tm. tm_mday -= 7; /* we want the *previous* week */
break;
case TMT_MONTH:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon -= tm.tm_mon % basestep;
break;
case TMT_YEAR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon = 0;
tm. tm_year -= (
tm.tm_year + 1900) %basestep;
}
return mktime(&tm);
}
/* identify the point where the next gridline, label ... gets placed */
time_t find_next_time(
time_t current, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
time_t madetime;
localtime_r(¤t, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
int limit = 2;
switch (baseint) {
case TMT_SECOND: limit = 7200; break;
case TMT_MINUTE: limit = 120; break;
case TMT_HOUR: limit = 2; break;
default: limit = 2; break;
}
do {
switch (baseint) {
case TMT_SECOND:
tm. tm_sec += basestep;
break;
case TMT_MINUTE:
tm. tm_min += basestep;
break;
case TMT_HOUR:
tm. tm_hour += basestep;
break;
case TMT_DAY:
tm. tm_mday += basestep;
break;
case TMT_WEEK:
tm. tm_mday += 7 * basestep;
break;
case TMT_MONTH:
tm. tm_mon += basestep;
break;
case TMT_YEAR:
tm. tm_year += basestep;
}
madetime = mktime(&tm);
} while (madetime == -1 && limit-- >= 0); /* this is necessary to skip impossible times
like the daylight saving time skips */
return madetime;
}
/* calculate values required for PRINT and GPRINT functions */
int print_calc(
image_desc_t *im)
{
long i, ii, validsteps;
double printval;
struct tm tmvdef;
int graphelement = 0;
long vidx;
int max_ii;
double magfact = -1;
char *si_symb = "";
char *percent_s;
int prline_cnt = 0;
/* wow initializing tmvdef is quite a task :-) */
time_t now = time(NULL);
localtime_r(&now, &tmvdef);
for (i = 0; i < im->gdes_c; i++) {
vidx = im->gdes[i].vidx;
switch (im->gdes[i].gf) {
case GF_PRINT:
case GF_GPRINT:
/* PRINT and GPRINT can now print VDEF generated values.
* There's no need to do any calculations on them as these
* calculations were already made.
*/
if (im->gdes[vidx].gf == GF_VDEF) { /* simply use vals */
printval = im->gdes[vidx].vf.val;
localtime_r(&im->gdes[vidx].vf.when, &tmvdef);
} else { /* need to calculate max,min,avg etcetera */
max_ii = ((im->gdes[vidx].end - im->gdes[vidx].start)
/ im->gdes[vidx].step * im->gdes[vidx].ds_cnt);
printval = DNAN;
validsteps = 0;
for (ii = im->gdes[vidx].ds;
ii < max_ii; ii += im->gdes[vidx].ds_cnt) {
if (!finite(im->gdes[vidx].data[ii]))
continue;
if (isnan(printval)) {
printval = im->gdes[vidx].data[ii];
validsteps++;
continue;
}
switch (im->gdes[i].cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVPREDICT:
case CF_DEVSEASONAL:
case CF_SEASONAL:
case CF_AVERAGE:
validsteps++;
printval += im->gdes[vidx].data[ii];
break;
case CF_MINIMUM:
printval = min(printval, im->gdes[vidx].data[ii]);
break;
case CF_FAILURES:
case CF_MAXIMUM:
printval = max(printval, im->gdes[vidx].data[ii]);
break;
case CF_LAST:
printval = im->gdes[vidx].data[ii];
}
}
if (im->gdes[i].cf == CF_AVERAGE || im->gdes[i].cf > CF_LAST) {
if (validsteps > 1) {
printval = (printval / validsteps);
}
}
} /* prepare printval */
if (!im->gdes[i].strftm && (percent_s = strstr(im->gdes[i].format, "%S")) != NULL) {
/* Magfact is set to -1 upon entry to print_calc. If it
* is still less than 0, then we need to run auto_scale.
* Otherwise, put the value into the correct units. If
* the value is 0, then do not set the symbol or magnification
* so next the calculation will be performed again. */
if (magfact < 0.0) {
auto_scale(im, &printval, &si_symb, &magfact);
if (printval == 0.0)
magfact = -1.0;
} else {
printval /= magfact;
}
*(++percent_s) = 's';
} else if (!im->gdes[i].strftm && strstr(im->gdes[i].format, "%s") != NULL) {
auto_scale(im, &printval, &si_symb, &magfact);
}
if (im->gdes[i].gf == GF_PRINT) {
rrd_infoval_t prline;
if (im->gdes[i].strftm) {
prline.u_str = (char*)malloc((FMT_LEG_LEN + 2) * sizeof(char));
strftime(prline.u_str,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
} else if (bad_format(im->gdes[i].format)) {
rrd_set_error
("bad format for PRINT in '%s'", im->gdes[i].format);
return -1;
} else {
prline.u_str =
sprintf_alloc(im->gdes[i].format, printval, si_symb);
}
grinfo_push(im,
sprintf_alloc
("print[%ld]", prline_cnt++), RD_I_STR, prline);
free(prline.u_str);
} else {
/* GF_GPRINT */
if (im->gdes[i].strftm) {
strftime(im->gdes[i].legend,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
} else {
if (bad_format(im->gdes[i].format)) {
rrd_set_error
("bad format for GPRINT in '%s'",
im->gdes[i].format);
return -1;
}
#ifdef HAVE_SNPRINTF
snprintf(im->gdes[i].legend,
FMT_LEG_LEN - 2,
im->gdes[i].format, printval, si_symb);
#else
sprintf(im->gdes[i].legend,
im->gdes[i].format, printval, si_symb);
#endif
}
graphelement = 1;
}
break;
case GF_LINE:
case GF_AREA:
case GF_TICK:
graphelement = 1;
break;
case GF_HRULE:
if (isnan(im->gdes[i].yrule)) { /* we must set this here or the legend printer can not decide to print the legend */
im->gdes[i].yrule = im->gdes[vidx].vf.val;
};
graphelement = 1;
break;
case GF_VRULE:
if (im->gdes[i].xrule == 0) { /* again ... the legend printer needs it */
im->gdes[i].xrule = im->gdes[vidx].vf.when;
};
graphelement = 1;
break;
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_DEF:
case GF_CDEF:
case GF_VDEF:
#ifdef WITH_PIECHART
case GF_PART:
#endif
case GF_SHIFT:
case GF_XPORT:
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
}
}
return graphelement;
}
/* place legends with color spots */
int leg_place(
image_desc_t *im,
int calc_width)
{
/* graph labels */
int interleg = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int border = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int fill = 0, fill_last;
double legendwidth; // = im->ximg - 2 * border;
int leg_c = 0;
double leg_x = border;
int leg_y = 0; //im->yimg;
int leg_cc;
double glue = 0;
int i, ii, mark = 0;
char default_txtalign = TXA_JUSTIFIED; /*default line orientation */
int *legspace;
char *tab;
char saved_legend[FMT_LEG_LEN + 5];
if(calc_width){
legendwidth = 0;
}
else{
legendwidth = im->legendwidth - 2 * border;
}
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
if ((legspace = (int*)malloc(im->gdes_c * sizeof(int))) == NULL) {
rrd_set_error("malloc for legspace");
return -1;
}
for (i = 0; i < im->gdes_c; i++) {
char prt_fctn; /*special printfunctions */
if(calc_width){
strcpy(saved_legend, im->gdes[i].legend);
}
fill_last = fill;
/* hide legends for rules which are not displayed */
if (im->gdes[i].gf == GF_TEXTALIGN) {
default_txtalign = im->gdes[i].txtalign;
}
if (!(im->extra_flags & FORCE_RULES_LEGEND)) {
if (im->gdes[i].gf == GF_HRULE
&& (im->gdes[i].yrule <
im->minval || im->gdes[i].yrule > im->maxval))
im->gdes[i].legend[0] = '\0';
if (im->gdes[i].gf == GF_VRULE
&& (im->gdes[i].xrule <
im->start || im->gdes[i].xrule > im->end))
im->gdes[i].legend[0] = '\0';
}
/* turn \\t into tab */
while ((tab = strstr(im->gdes[i].legend, "\\t"))) {
memmove(tab, tab + 1, strlen(tab));
tab[0] = (char) 9;
}
leg_cc = strlen(im->gdes[i].legend);
/* is there a controle code at the end of the legend string ? */
if (leg_cc >= 2 && im->gdes[i].legend[leg_cc - 2] == '\\') {
prt_fctn = im->gdes[i].legend[leg_cc - 1];
leg_cc -= 2;
im->gdes[i].legend[leg_cc] = '\0';
} else {
prt_fctn = '\0';
}
/* only valid control codes */
if (prt_fctn != 'l' && prt_fctn != 'n' && /* a synonym for l */
prt_fctn != 'r' &&
prt_fctn != 'j' &&
prt_fctn != 'c' &&
prt_fctn != 'u' &&
prt_fctn != '.' &&
prt_fctn != 's' && prt_fctn != '\0' && prt_fctn != 'g') {
free(legspace);
rrd_set_error
("Unknown control code at the end of '%s\\%c'",
im->gdes[i].legend, prt_fctn);
return -1;
}
/* \n -> \l */
if (prt_fctn == 'n') {
prt_fctn = 'l';
}
/* \. is a null operation to allow strings ending in \x */
if (prt_fctn == '.') {
prt_fctn = '\0';
}
/* remove exess space from the end of the legend for \g */
while (prt_fctn == 'g' &&
leg_cc > 0 && im->gdes[i].legend[leg_cc - 1] == ' ') {
leg_cc--;
im->gdes[i].legend[leg_cc] = '\0';
}
if (leg_cc != 0) {
/* no interleg space if string ends in \g */
legspace[i] = (prt_fctn == 'g' ? 0 : interleg);
if (fill > 0) {
fill += legspace[i];
}
fill +=
gfx_get_text_width(im,
fill + border,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[i].legend);
leg_c++;
} else {
legspace[i] = 0;
}
/* who said there was a special tag ... ? */
if (prt_fctn == 'g') {
prt_fctn = '\0';
}
if (prt_fctn == '\0') {
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
if (i == im->gdes_c - 1 || fill > legendwidth) {
/* just one legend item is left right or center */
switch (default_txtalign) {
case TXA_RIGHT:
prt_fctn = 'r';
break;
case TXA_CENTER:
prt_fctn = 'c';
break;
case TXA_JUSTIFIED:
prt_fctn = 'j';
break;
default:
prt_fctn = 'l';
break;
}
}
/* is it time to place the legends ? */
if (fill > legendwidth) {
if (leg_c > 1) {
/* go back one */
i--;
fill = fill_last;
leg_c--;
}
}
if (leg_c == 1 && prt_fctn == 'j') {
prt_fctn = 'l';
}
}
if (prt_fctn != '\0') {
leg_x = border;
if (leg_c >= 2 && prt_fctn == 'j') {
glue = (double)(legendwidth - fill) / (double)(leg_c - 1);
} else {
glue = 0;
}
if (prt_fctn == 'c')
leg_x = border + (double)(legendwidth - fill) / 2.0;
if (prt_fctn == 'r')
leg_x = legendwidth - fill + border;
for (ii = mark; ii <= i; ii++) {
if (im->gdes[ii].legend[0] == '\0')
continue; /* skip empty legends */
im->gdes[ii].leg_x = leg_x;
im->gdes[ii].leg_y = leg_y + border;
leg_x +=
(double)gfx_get_text_width(im, leg_x,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[ii].legend)
+(double)legspace[ii]
+ glue;
}
if (leg_x > border || prt_fctn == 's')
leg_y += im->text_prop[TEXT_PROP_LEGEND].size * 1.8;
if (prt_fctn == 's')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size;
if (prt_fctn == 'u')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size *1.8;
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
fill = 0;
leg_c = 0;
mark = ii;
}
if(calc_width){
strcpy(im->gdes[i].legend, saved_legend);
}
}
if(calc_width){
im->legendwidth = legendwidth + 2 * border;
}
else{
im->legendheight = leg_y + border * 0.6;
}
free(legspace);
}
return 0;
}
/* create a grid on the graph. it determines what to do
from the values of xsize, start and end */
/* the xaxis labels are determined from the number of seconds per pixel
in the requested graph */
int calc_horizontal_grid(
image_desc_t
*im)
{
double range;
double scaledrange;
int pixel, i;
int gridind = 0;
int decimals, fractionals;
im->ygrid_scale.labfact = 2;
range = im->maxval - im->minval;
scaledrange = range / im->magfact;
/* does the scale of this graph make it impossible to put lines
on it? If so, give up. */
if (isnan(scaledrange)) {
return 0;
}
/* find grid spaceing */
pixel = 1;
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTYGRID) {
/* find the value with max number of digits. Get number of digits */
decimals =
ceil(log10
(max(fabs(im->maxval), fabs(im->minval)) *
im->viewfactor / im->magfact));
if (decimals <= 0) /* everything is small. make place for zero */
decimals = 1;
im->ygrid_scale.gridstep =
pow((double) 10,
floor(log10(range * im->viewfactor / im->magfact))) /
im->viewfactor * im->magfact;
if (im->ygrid_scale.gridstep == 0) /* range is one -> 0.1 is reasonable scale */
im->ygrid_scale.gridstep = 0.1;
/* should have at least 5 lines but no more then 15 */
if (range / im->ygrid_scale.gridstep < 5
&& im->ygrid_scale.gridstep >= 30)
im->ygrid_scale.gridstep /= 10;
if (range / im->ygrid_scale.gridstep > 15)
im->ygrid_scale.gridstep *= 10;
if (range / im->ygrid_scale.gridstep > 5) {
im->ygrid_scale.labfact = 1;
if (range / im->ygrid_scale.gridstep > 8
|| im->ygrid_scale.gridstep <
1.8 * im->text_prop[TEXT_PROP_AXIS].size)
im->ygrid_scale.labfact = 2;
} else {
im->ygrid_scale.gridstep /= 5;
im->ygrid_scale.labfact = 5;
}
fractionals =
floor(log10
(im->ygrid_scale.gridstep *
(double) im->ygrid_scale.labfact * im->viewfactor /
im->magfact));
if (fractionals < 0) { /* small amplitude. */
int len = decimals - fractionals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
sprintf(im->ygrid_scale.labfmt,
"%%%d.%df%s", len,
-fractionals, (im->symbol != ' ' ? " %c" : ""));
} else {
int len = decimals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
sprintf(im->ygrid_scale.labfmt,
"%%%d.0f%s", len, (im->symbol != ' ' ? " %c" : ""));
}
} else { /* classic rrd grid */
for (i = 0; ylab[i].grid > 0; i++) {
pixel = im->ysize / (scaledrange / ylab[i].grid);
gridind = i;
if (pixel >= 5)
break;
}
for (i = 0; i < 4; i++) {
if (pixel * ylab[gridind].lfac[i] >=
1.8 * im->text_prop[TEXT_PROP_AXIS].size) {
im->ygrid_scale.labfact = ylab[gridind].lfac[i];
break;
}
}
im->ygrid_scale.gridstep = ylab[gridind].grid * im->magfact;
}
} else {
im->ygrid_scale.gridstep = im->ygridstep;
im->ygrid_scale.labfact = im->ylabfact;
}
return 1;
}
int draw_horizontal_grid(
image_desc_t
*im)
{
int i;
double scaledstep;
char graph_label[100];
int nlabels = 0;
double X0 = im->xorigin;
double X1 = im->xorigin + im->xsize;
int sgrid = (int) (im->minval / im->ygrid_scale.gridstep - 1);
int egrid = (int) (im->maxval / im->ygrid_scale.gridstep + 1);
double MaxY;
double second_axis_magfact = 0;
char *second_axis_symb = "";
scaledstep =
im->ygrid_scale.gridstep /
(double) im->magfact * (double) im->viewfactor;
MaxY = scaledstep * (double) egrid;
for (i = sgrid; i <= egrid; i++) {
double Y0 = ytr(im,
im->ygrid_scale.gridstep * i);
double YN = ytr(im,
im->ygrid_scale.gridstep * (i + 1));
if (floor(Y0 + 0.5) >=
im->yorigin - im->ysize && floor(Y0 + 0.5) <= im->yorigin) {
/* Make sure at least 2 grid labels are shown, even if it doesn't agree
with the chosen settings. Add a label if required by settings, or if
there is only one label so far and the next grid line is out of bounds. */
if (i % im->ygrid_scale.labfact == 0
|| (nlabels == 1
&& (YN < im->yorigin - im->ysize || YN > im->yorigin))) {
if (im->symbol == ' ') {
if (im->primary_axis_format[0] == '\0'){
if (im->extra_flags & ALTYGRID) {
sprintf(graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i);
} else {
if (MaxY < 10) {
sprintf(graph_label, "%4.1f",
scaledstep * (double) i);
} else {
sprintf(graph_label, "%4.0f",
scaledstep * (double) i);
}
}
} else {
sprintf(graph_label, im->primary_axis_format,
scaledstep * (double) i);
}
} else {
char sisym = (i == 0 ? ' ' : im->symbol);
if (im->primary_axis_format[0] == '\0'){
if (im->extra_flags & ALTYGRID) {
sprintf(graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i, sisym);
} else {
if (MaxY < 10) {
sprintf(graph_label, "%4.1f %c",
scaledstep * (double) i, sisym);
} else {
sprintf(graph_label, "%4.0f %c",
scaledstep * (double) i, sisym);
}
}
} else {
sprintf(graph_label, im->primary_axis_format,
scaledstep * (double) i, sisym);
}
}
nlabels++;
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = im->ygrid_scale.gridstep*(double)i*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format[0] == '\0'){
if (!second_axis_magfact){
double dummy = im->ygrid_scale.gridstep*(double)(sgrid+egrid)/2.0*im->second_axis_scale+im->second_axis_shift;
auto_scale(im,&dummy,&second_axis_symb,&second_axis_magfact);
}
sval /= second_axis_magfact;
if(MaxY < 10) {
sprintf(graph_label_right,"%5.1f %s",sval,second_axis_symb);
} else {
sprintf(graph_label_right,"%5.0f %s",sval,second_axis_symb);
}
}
else {
sprintf(graph_label_right,im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
gfx_line(im, X0 - 2, Y0, X0, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID],
im->grid_dash_on, im->grid_dash_off);
} else if (!(im->extra_flags & NOMINOR)) {
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
}
return 1;
}
/* this is frexp for base 10 */
double frexp10(
double,
double *);
double frexp10(
double x,
double *e)
{
double mnt;
int iexp;
iexp = floor(log((double)fabs(x)) / log((double)10));
mnt = x / pow(10.0, iexp);
if (mnt >= 10.0) {
iexp++;
mnt = x / pow(10.0, iexp);
}
*e = iexp;
return mnt;
}
/* logaritmic horizontal grid */
int horizontal_log_grid(
image_desc_t
*im)
{
double yloglab[][10] = {
{
1.0, 10., 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 5.0, 10., 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 5.0, 7.0, 10., 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 4.0,
6.0, 8.0, 10.,
0.0,
0.0, 0.0, 0.0}, {
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0} /* last line */
};
int i, j, val_exp, min_exp;
double nex; /* number of decades in data */
double logscale; /* scale in logarithmic space */
int exfrac = 1; /* decade spacing */
int mid = -1; /* row in yloglab for major grid */
double mspac; /* smallest major grid spacing (pixels) */
int flab; /* first value in yloglab to use */
double value, tmp, pre_value;
double X0, X1, Y0;
char graph_label[100];
nex = log10(im->maxval / im->minval);
logscale = im->ysize / nex;
/* major spacing for data with high dynamic range */
while (logscale * exfrac < 3 * im->text_prop[TEXT_PROP_LEGEND].size) {
if (exfrac == 1)
exfrac = 3;
else
exfrac += 3;
}
/* major spacing for less dynamic data */
do {
/* search best row in yloglab */
mid++;
for (i = 0; yloglab[mid][i + 1] < 10.0; i++);
mspac = logscale * log10(10.0 / yloglab[mid][i]);
}
while (mspac >
2 * im->text_prop[TEXT_PROP_LEGEND].size && yloglab[mid][0] > 0);
if (mid)
mid--;
/* find first value in yloglab */
for (flab = 0;
yloglab[mid][flab] < 10
&& frexp10(im->minval, &tmp) > yloglab[mid][flab]; flab++);
if (yloglab[mid][flab] == 10.0) {
tmp += 1.0;
flab = 0;
}
val_exp = tmp;
if (val_exp % exfrac)
val_exp += abs(-val_exp % exfrac);
X0 = im->xorigin;
X1 = im->xorigin + im->xsize;
/* draw grid */
pre_value = DNAN;
while (1) {
value = yloglab[mid][flab] * pow(10.0, val_exp);
if (AlmostEqual2sComplement(value, pre_value, 4))
break; /* it seems we are not converging */
pre_value = value;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* major grid line */
gfx_line(im,
X0 - 2, Y0, X0, Y0, MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
/* label */
if (im->extra_flags & FORCE_UNITS_SI) {
int scale;
double pvalue;
char symbol;
scale = floor(val_exp / 3.0);
if (value >= 1.0)
pvalue = pow(10.0, val_exp % 3);
else
pvalue = pow(10.0, ((val_exp + 1) % 3) + 2);
pvalue *= yloglab[mid][flab];
if (((scale + si_symbcenter) < (int) sizeof(si_symbol))
&& ((scale + si_symbcenter) >= 0))
symbol = si_symbol[scale + si_symbcenter];
else
symbol = '?';
sprintf(graph_label, "%3.0f %c", pvalue, symbol);
} else {
sprintf(graph_label, "%3.0e", value);
}
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = value*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format[0] == '\0'){
if (im->extra_flags & FORCE_UNITS_SI) {
double mfac = 1;
char *symb = "";
auto_scale(im,&sval,&symb,&mfac);
sprintf(graph_label_right,"%4.0f %s", sval,symb);
}
else {
sprintf(graph_label_right,"%3.0e", sval);
}
}
else {
sprintf(graph_label_right,im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
/* minor grid */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line behind current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
} else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* next decade */
if (yloglab[mid][++flab] == 10.0) {
flab = 0;
val_exp += exfrac;
}
}
/* draw minor lines after highest major line */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line below current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* fancy minor gridlines */
else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
return 1;
}
void vertical_grid(
image_desc_t *im)
{
int xlab_sel; /* which sort of label and grid ? */
time_t ti, tilab, timajor;
long factor;
char graph_label[100];
double X0, Y0, Y1; /* points for filled graph and more */
struct tm tm;
/* the type of time grid is determined by finding
the number of seconds per pixel in the graph */
if (im->xlab_user.minsec == -1) {
factor = (im->end - im->start) / im->xsize;
xlab_sel = 0;
while (xlab[xlab_sel + 1].minsec !=
-1 && xlab[xlab_sel + 1].minsec <= factor) {
xlab_sel++;
} /* pick the last one */
while (xlab[xlab_sel - 1].minsec ==
xlab[xlab_sel].minsec
&& xlab[xlab_sel].length > (im->end - im->start)) {
xlab_sel--;
} /* go back to the smallest size */
im->xlab_user.gridtm = xlab[xlab_sel].gridtm;
im->xlab_user.gridst = xlab[xlab_sel].gridst;
im->xlab_user.mgridtm = xlab[xlab_sel].mgridtm;
im->xlab_user.mgridst = xlab[xlab_sel].mgridst;
im->xlab_user.labtm = xlab[xlab_sel].labtm;
im->xlab_user.labst = xlab[xlab_sel].labst;
im->xlab_user.precis = xlab[xlab_sel].precis;
im->xlab_user.stst = xlab[xlab_sel].stst;
}
/* y coords are the same for every line ... */
Y0 = im->yorigin;
Y1 = im->yorigin - im->ysize;
/* paint the minor grid */
if (!(im->extra_flags & NOMINOR)) {
for (ti = find_first_time(im->start,
im->
xlab_user.
gridtm,
im->
xlab_user.
gridst),
timajor =
find_first_time(im->start,
im->xlab_user.
mgridtm,
im->xlab_user.
mgridst);
ti < im->end && ti != -1;
ti =
find_next_time(ti, im->xlab_user.gridtm, im->xlab_user.gridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
while (timajor < ti && timajor != -1) {
timajor = find_next_time(timajor,
im->
xlab_user.
mgridtm, im->xlab_user.mgridst);
}
if (timajor == -1) break; /* fail in case of problems with time increments */
if (ti == timajor)
continue; /* skip as falls on major grid line */
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X0, Y0, X0, Y0 + 2,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0, Y0 + 1, X0,
Y1 - 1, GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* paint the major grid */
for (ti = find_first_time(im->start,
im->
xlab_user.
mgridtm,
im->
xlab_user.
mgridst);
ti < im->end && ti != -1;
ti = find_next_time(ti, im->xlab_user.mgridtm, im->xlab_user.mgridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X0, Y0, X0, Y0 + 3,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0, Y0 + 3, X0,
Y1 - 2, MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
}
/* paint the labels below the graph */
for (ti =
find_first_time(im->start -
im->xlab_user.
precis / 2,
im->xlab_user.
labtm,
im->xlab_user.
labst);
(ti <=
im->end -
im->xlab_user.precis / 2) && ti != -1;
ti = find_next_time(ti, im->xlab_user.labtm, im->xlab_user.labst)
) {
tilab = ti + im->xlab_user.precis / 2; /* correct time for the label */
/* are we inside the graph ? */
if (tilab < im->start || tilab > im->end)
continue;
#if HAVE_STRFTIME
localtime_r(&tilab, &tm);
strftime(graph_label, 99, im->xlab_user.stst, &tm);
#else
# error "your libc has no strftime I guess we'll abort the exercise here."
#endif
gfx_text(im,
xtr(im, tilab),
Y0 + 3,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_TOP, graph_label);
}
}
void axis_paint(
image_desc_t *im)
{
/* draw x and y axis */
/* gfx_line ( im->canvas, im->xorigin+im->xsize,im->yorigin,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line ( im->canvas, im->xorigin,im->yorigin-im->ysize,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]); */
gfx_line(im, im->xorigin - 4,
im->yorigin,
im->xorigin + im->xsize +
4, im->yorigin, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line(im, im->xorigin,
im->yorigin + 4,
im->xorigin,
im->yorigin - im->ysize -
4, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
/* arrow for X and Y axis direction */
gfx_new_area(im, im->xorigin + im->xsize + 2, im->yorigin - 3, im->xorigin + im->xsize + 2, im->yorigin + 3, im->xorigin + im->xsize + 7, im->yorigin, /* horyzontal */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
gfx_new_area(im, im->xorigin - 3, im->yorigin - im->ysize - 2, im->xorigin + 3, im->yorigin - im->ysize - 2, im->xorigin, im->yorigin - im->ysize - 7, /* vertical */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
if (im->second_axis_scale != 0){
gfx_line ( im, im->xorigin+im->xsize,im->yorigin+4,
im->xorigin+im->xsize,im->yorigin-im->ysize-4,
MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_new_area ( im,
im->xorigin+im->xsize-2, im->yorigin-im->ysize-2,
im->xorigin+im->xsize+3, im->yorigin-im->ysize-2,
im->xorigin+im->xsize, im->yorigin-im->ysize-7, /* LINEOFFSET */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
}
}
void grid_paint(
image_desc_t *im)
{
long i;
int res = 0;
double X0, Y0; /* points for filled graph and more */
struct gfx_color_t water_color;
if (im->draw_3d_border > 0) {
/* draw 3d border */
i = im->draw_3d_border;
gfx_new_area(im, 0, im->yimg,
i, im->yimg - i, i, i, im->graph_col[GRC_SHADEA]);
gfx_add_point(im, im->ximg - i, i);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, 0, 0);
gfx_close_path(im);
gfx_new_area(im, i, im->yimg - i,
im->ximg - i,
im->yimg - i, im->ximg - i, i, im->graph_col[GRC_SHADEB]);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, im->ximg, im->yimg);
gfx_add_point(im, 0, im->yimg);
gfx_close_path(im);
}
if (im->draw_x_grid == 1)
vertical_grid(im);
if (im->draw_y_grid == 1) {
if (im->logarithmic) {
res = horizontal_log_grid(im);
} else {
res = draw_horizontal_grid(im);
}
/* dont draw horizontal grid if there is no min and max val */
if (!res) {
char *nodata = "No Data found";
gfx_text(im, im->ximg / 2,
(2 * im->yorigin -
im->ysize) / 2,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_CENTER, nodata);
}
}
/* yaxis unit description */
if (im->ylegend[0] != '\0'){
gfx_text(im,
im->xOriginLegendY+10,
im->yOriginLegendY,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_UNIT].
font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE, GFX_H_CENTER, GFX_V_CENTER, im->ylegend);
}
if (im->second_axis_legend[0] != '\0'){
gfx_text( im,
im->xOriginLegendY2+10,
im->yOriginLegendY2,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_UNIT].font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE,
GFX_H_CENTER, GFX_V_CENTER,
im->second_axis_legend);
}
/* graph title */
gfx_text(im,
im->xOriginTitle, im->yOriginTitle+6,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_TITLE].
font_desc,
im->tabwidth, 0.0, GFX_H_CENTER, GFX_V_TOP, im->title);
/* rrdtool 'logo' */
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
double xpos = im->legendposition == EAST ? im->xOriginLegendY : im->ximg - 4;
gfx_text(im, xpos, 5,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth,
-90, GFX_H_LEFT, GFX_V_TOP, "RRDTOOL / TOBI OETIKER");
}
/* graph watermark */
if (im->watermark[0] != '\0') {
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
gfx_text(im,
im->ximg / 2, im->yimg - 6,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth, 0,
GFX_H_CENTER, GFX_V_BOTTOM, im->watermark);
}
/* graph labels */
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
for (i = 0; i < im->gdes_c; i++) {
if (im->gdes[i].legend[0] == '\0')
continue;
/* im->gdes[i].leg_y is the bottom of the legend */
X0 = im->xOriginLegend + im->gdes[i].leg_x;
Y0 = im->legenddirection == TOP_DOWN ? im->yOriginLegend + im->gdes[i].leg_y : im->yOriginLegend + im->legendheight - im->gdes[i].leg_y;
gfx_text(im, X0, Y0,
im->graph_col[GRC_FONT],
im->
text_prop
[TEXT_PROP_LEGEND].font_desc,
im->tabwidth, 0.0,
GFX_H_LEFT, GFX_V_BOTTOM, im->gdes[i].legend);
/* The legend for GRAPH items starts with "M " to have
enough space for the box */
if (im->gdes[i].gf != GF_PRINT &&
im->gdes[i].gf != GF_GPRINT && im->gdes[i].gf != GF_COMMENT) {
double boxH, boxV;
double X1, Y1;
boxH = gfx_get_text_width(im, 0,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, "o") * 1.2;
boxV = boxH;
/* shift the box up a bit */
Y0 -= boxV * 0.4;
if (im->dynamic_labels && im->gdes[i].gf == GF_HRULE) { /* [-] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0, Y0 - boxV / 2,
X0 + boxH, Y0 - boxV / 2,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_VRULE) { /* [|] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0 + boxH / 2, Y0,
X0 + boxH / 2, Y0 - boxV,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_LINE) { /* [/] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
gfx_line(im,
X0, Y0,
X0 + boxH, Y0 - boxV,
im->gdes[i].linewidth, im->gdes[i].col);
gfx_close_path(im);
} else {
/* make sure transparent colors show up the same way as in the graph */
gfx_new_area(im,
X0, Y0 - boxV,
X0, Y0, X0 + boxH, Y0, im->graph_col[GRC_BACK]);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
gfx_new_area(im, X0, Y0 - boxV, X0,
Y0, X0 + boxH, Y0, im->gdes[i].col);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
X1 = X0 + boxH;
Y1 = Y0 - boxV;
gfx_line_fit(im, &X0, &Y0);
gfx_line_fit(im, &X1, &Y1);
cairo_move_to(im->cr, X0, Y0);
cairo_line_to(im->cr, X1, Y0);
cairo_line_to(im->cr, X1, Y1);
cairo_line_to(im->cr, X0, Y1);
cairo_close_path(im->cr);
cairo_set_source_rgba(im->cr,
im->graph_col[GRC_FRAME].red,
im->graph_col[GRC_FRAME].green,
im->graph_col[GRC_FRAME].blue,
im->graph_col[GRC_FRAME].alpha);
}
if (im->gdes[i].dash) {
/* make box borders in legend dashed if the graph is dashed */
double dashes[] = {
3.0
};
cairo_set_dash(im->cr, dashes, 1, 0.0);
}
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
}
}
}
/*****************************************************
* lazy check make sure we rely need to create this graph
*****************************************************/
int lazy_check(
image_desc_t *im)
{
FILE *fd = NULL;
int size = 1;
struct stat imgstat;
if (im->lazy == 0)
return 0; /* no lazy option */
if (strlen(im->graphfile) == 0)
return 0; /* inmemory option */
if (stat(im->graphfile, &imgstat) != 0)
return 0; /* can't stat */
/* one pixel in the existing graph is more then what we would
change here ... */
if (time(NULL) - imgstat.st_mtime > (im->end - im->start) / im->xsize)
return 0;
if ((fd = fopen(im->graphfile, "rb")) == NULL)
return 0; /* the file does not exist */
switch (im->imgformat) {
case IF_PNG:
size = PngSize(fd, &(im->ximg), &(im->yimg));
break;
default:
size = 1;
}
fclose(fd);
return size;
}
int graph_size_location(
image_desc_t
*im,
int elements)
{
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area. If the option
** --full-size-mode is selected the size defines the total
** image size and the size available for the graph is
** calculated.
*/
/** +---+-----------------------------------+
** | y |...............graph title.........|
** | +---+-------------------------------+
** | a | y | |
** | x | | |
** | i | a | |
** | s | x | main graph area |
** | | i | |
** | t | s | |
** | i | | |
** | t | l | |
** | l | b +-------------------------------+
** | e | l | x axis labels |
** +---+---+-------------------------------+
** |....................legends............|
** +---------------------------------------+
** | watermark |
** +---------------------------------------+
*/
int Xvertical = 0, Xvertical2 = 0, Ytitle =
0, Xylabel = 0, Xmain = 0, Ymain =
0, Yxlabel = 0, Xspacing = 15, Yspacing = 15, Ywatermark = 4;
// no legends and no the shall be plotted it's easy
if (im->extra_flags & ONLY_GRAPH) {
im->xorigin = 0;
im->ximg = im->xsize;
im->yimg = im->ysize;
im->yorigin = im->ysize;
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
if(im->watermark[0] != '\0') {
Ywatermark = im->text_prop[TEXT_PROP_WATERMARK].size * 2;
}
// calculate the width of the left vertical legend
if (im->ylegend[0] != '\0') {
Xvertical = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
// calculate the width of the right vertical legend
if (im->second_axis_legend[0] != '\0') {
Xvertical2 = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
else{
Xvertical2 = Xspacing;
}
if (im->title[0] != '\0') {
/* The title is placed "inbetween" two text lines so it
** automatically has some vertical spacing. The horizontal
** spacing is added here, on each side.
*/
/* if necessary, reduce the font size of the title until it fits the image width */
Ytitle = im->text_prop[TEXT_PROP_TITLE].size * 2.6 + 10;
}
else{
// we have no title; get a little clearing from the top
Ytitle = Yspacing;
}
if (elements) {
if (im->draw_x_grid) {
// calculate the height of the horizontal labelling
Yxlabel = im->text_prop[TEXT_PROP_AXIS].size * 2.5;
}
if (im->draw_y_grid || im->forceleftspace) {
// calculate the width of the vertical labelling
Xylabel =
gfx_get_text_width(im, 0,
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth, "0") * im->unitslength;
}
}
// add some space to the labelling
Xylabel += Xspacing;
/* If the legend is printed besides the graph the width has to be
** calculated first. Placing the legend north or south of the
** graph requires the width calculation first, so the legend is
** skipped for the moment.
*/
im->legendheight = 0;
im->legendwidth = 0;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 1) == -1){
return -1;
}
}
}
if (im->extra_flags & FULL_SIZE_MODE) {
/* The actual size of the image to draw has been determined by the user.
** The graph area is the space remaining after accounting for the legend,
** the watermark, the axis labels, and the title.
*/
im->ximg = im->xsize;
im->yimg = im->ysize;
Xmain = im->ximg;
Ymain = im->yimg;
/* Now calculate the total size. Insert some spacing where
desired. im->xorigin and im->yorigin need to correspond
with the lower left corner of the main graph area or, if
this one is not set, the imaginary box surrounding the
pie chart area. */
/* Initial size calculation for the main graph area */
Xmain -= Xylabel;// + Xspacing;
if((im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
Xmain -= im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
Xmain -= Xylabel;
}
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
Xmain -= Xspacing;
}
Xmain -= Xvertical + Xvertical2;
/* limit the remaining space to 0 */
if(Xmain < 1){
Xmain = 1;
}
im->xsize = Xmain;
/* Putting the legend north or south, the height can now be calculated */
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
Ymain -= Yxlabel + im->legendheight;
}
else{
Ymain -= Yxlabel;
}
/* reserve space for the title *or* some padding above the graph */
Ymain -= Ytitle;
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
Ymain -= 0.5*Yspacing;
}
if (im->watermark[0] != '\0') {
Ymain -= Ywatermark;
}
/* limit the remaining height to 0 */
if(Ymain < 1){
Ymain = 1;
}
im->ysize = Ymain;
} else { /* dimension options -width and -height refer to the dimensions of the main graph area */
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area.
*/
if (elements) {
Xmain = im->xsize; // + Xspacing;
Ymain = im->ysize;
}
im->ximg = Xmain + Xylabel;
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->ximg += Xspacing;
}
if( (im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
im->ximg += im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
im->ximg += Xylabel;
}
im->ximg += Xvertical + Xvertical2;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
im->yimg = Ymain + Yxlabel;
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
im->yimg += im->legendheight;
}
/* reserve space for the title *or* some padding above the graph */
if (Ytitle) {
im->yimg += Ytitle;
} else {
im->yimg += 1.5 * Yspacing;
}
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
im->yimg += 0.5*Yspacing;
}
if (im->watermark[0] != '\0') {
im->yimg += Ywatermark;
}
}
/* In case of putting the legend in west or east position the first
** legend calculation might lead to wrong positions if some items
** are not aligned on the left hand side (e.g. centered) as the
** legendwidth wight have been increased after the item was placed.
** In this case the positions have to be recalculated.
*/
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 0) == -1){
return -1;
}
}
}
/* After calculating all dimensions
** it is now possible to calculate
** all offsets.
*/
switch(im->legendposition){
case NORTH:
im->xOriginTitle = (im->ximg / 2);
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + im->legendheight + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
break;
case WEST:
im->xOriginTitle = im->legendwidth + im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = im->legendwidth;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = im->legendwidth + Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = im->legendwidth + Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case SOUTH:
im->xOriginTitle = im->ximg / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle + Ymain + Yxlabel;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case EAST:
im->xOriginTitle = im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = Xvertical + Xylabel + Xmain + Xvertical2;
if (im->second_axis_scale != 0){
im->xOriginLegend += Xylabel;
}
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->xOriginTitle += Xspacing;
im->xOriginLegend += Xspacing;
im->xOriginLegendY += Xspacing;
im->xorigin += Xspacing;
im->xOriginLegendY2 += Xspacing;
}
break;
}
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
static cairo_status_t cairo_output(
void *closure,
const unsigned char
*data,
unsigned int length)
{
image_desc_t *im = (image_desc_t*)closure;
im->rendered_image =
(unsigned char*)realloc(im->rendered_image, im->rendered_image_size + length);
if (im->rendered_image == NULL)
return CAIRO_STATUS_WRITE_ERROR;
memcpy(im->rendered_image + im->rendered_image_size, data, length);
im->rendered_image_size += length;
return CAIRO_STATUS_SUCCESS;
}
/* draw that picture thing ... */
int graph_paint(
image_desc_t *im)
{
int i, ii;
int lazy = lazy_check(im);
double areazero = 0.0;
graph_desc_t *lastgdes = NULL;
rrd_infoval_t info;
// PangoFontMap *font_map = pango_cairo_font_map_get_default();
/* pull the data from the rrd files ... */
if (data_fetch(im) == -1)
return -1;
/* evaluate VDEF and CDEF operations ... */
if (data_calc(im) == -1)
return -1;
/* calculate and PRINT and GPRINT definitions. We have to do it at
* this point because it will affect the length of the legends
* if there are no graph elements (i==0) we stop here ...
* if we are lazy, try to quit ...
*/
i = print_calc(im);
if (i < 0)
return -1;
/* if we want and can be lazy ... quit now */
if (i == 0)
return 0;
/**************************************************************
*** Calculating sizes and locations became a bit confusing ***
*** so I moved this into a separate function. ***
**************************************************************/
if (graph_size_location(im, i) == -1)
return -1;
info.u_cnt = im->xorigin;
grinfo_push(im, sprintf_alloc("graph_left"), RD_I_CNT, info);
info.u_cnt = im->yorigin - im->ysize;
grinfo_push(im, sprintf_alloc("graph_top"), RD_I_CNT, info);
info.u_cnt = im->xsize;
grinfo_push(im, sprintf_alloc("graph_width"), RD_I_CNT, info);
info.u_cnt = im->ysize;
grinfo_push(im, sprintf_alloc("graph_height"), RD_I_CNT, info);
info.u_cnt = im->ximg;
grinfo_push(im, sprintf_alloc("image_width"), RD_I_CNT, info);
info.u_cnt = im->yimg;
grinfo_push(im, sprintf_alloc("image_height"), RD_I_CNT, info);
info.u_cnt = im->start;
grinfo_push(im, sprintf_alloc("graph_start"), RD_I_CNT, info);
info.u_cnt = im->end;
grinfo_push(im, sprintf_alloc("graph_end"), RD_I_CNT, info);
/* if we want and can be lazy ... quit now */
if (lazy)
return 0;
/* get actual drawing data and find min and max values */
if (data_proc(im) == -1)
return -1;
if (!im->logarithmic) {
si_unit(im);
}
/* identify si magnitude Kilo, Mega Giga ? */
if (!im->rigid && !im->logarithmic)
expand_range(im); /* make sure the upper and lower limit are
sensible values */
info.u_val = im->minval;
grinfo_push(im, sprintf_alloc("value_min"), RD_I_VAL, info);
info.u_val = im->maxval;
grinfo_push(im, sprintf_alloc("value_max"), RD_I_VAL, info);
if (!calc_horizontal_grid(im))
return -1;
/* reset precalc */
ytr(im, DNAN);
/* if (im->gridfit)
apply_gridfit(im); */
/* the actual graph is created by going through the individual
graph elements and then drawing them */
cairo_surface_destroy(im->surface);
switch (im->imgformat) {
case IF_PNG:
im->surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
im->ximg * im->zoom,
im->yimg * im->zoom);
break;
case IF_PDF:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
? cairo_pdf_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_pdf_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_EPS:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_ps_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_ps_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_SVG:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_svg_surface_create(im->
graphfile,
im->ximg * im->zoom, im->yimg * im->zoom)
: cairo_svg_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
cairo_svg_surface_restrict_to_version
(im->surface, CAIRO_SVG_VERSION_1_1);
break;
};
cairo_destroy(im->cr);
im->cr = cairo_create(im->surface);
cairo_set_antialias(im->cr, im->graph_antialias);
cairo_scale(im->cr, im->zoom, im->zoom);
// pango_cairo_font_map_set_resolution(PANGO_CAIRO_FONT_MAP(font_map), 100);
gfx_new_area(im, 0, 0, 0, im->yimg,
im->ximg, im->yimg, im->graph_col[GRC_BACK]);
gfx_add_point(im, im->ximg, 0);
gfx_close_path(im);
gfx_new_area(im, im->xorigin,
im->yorigin,
im->xorigin +
im->xsize, im->yorigin,
im->xorigin +
im->xsize,
im->yorigin - im->ysize, im->graph_col[GRC_CANVAS]);
gfx_add_point(im, im->xorigin, im->yorigin - im->ysize);
gfx_close_path(im);
cairo_rectangle(im->cr, im->xorigin, im->yorigin - im->ysize - 1.0,
im->xsize, im->ysize + 2.0);
cairo_clip(im->cr);
if (im->minval > 0.0)
areazero = im->minval;
if (im->maxval < 0.0)
areazero = im->maxval;
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_CDEF:
case GF_VDEF:
case GF_DEF:
case GF_PRINT:
case GF_GPRINT:
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_HRULE:
case GF_VRULE:
case GF_XPORT:
case GF_SHIFT:
break;
case GF_TICK:
for (ii = 0; ii < im->xsize; ii++) {
if (!isnan(im->gdes[i].p_data[ii])
&& im->gdes[i].p_data[ii] != 0.0) {
if (im->gdes[i].yrule > 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin + 1.0,
im->xorigin + ii,
im->yorigin -
im->gdes[i].yrule *
im->ysize, 1.0, im->gdes[i].col);
} else if (im->gdes[i].yrule < 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin - im->ysize - 1.0,
im->xorigin + ii,
im->yorigin - im->ysize -
im->gdes[i].
yrule *
im->ysize, 1.0, im->gdes[i].col);
}
}
}
break;
case GF_LINE:
case GF_AREA: {
rrd_value_t diffval = im->maxval - im->minval;
rrd_value_t maxlimit = im->maxval + 9 * diffval;
rrd_value_t minlimit = im->minval - 9 * diffval;
for (ii = 0; ii < im->xsize; ii++) {
/* fix data points at oo and -oo */
if (isinf(im->gdes[i].p_data[ii])) {
if (im->gdes[i].p_data[ii] > 0) {
im->gdes[i].p_data[ii] = im->maxval;
} else {
im->gdes[i].p_data[ii] = im->minval;
}
}
/* some versions of cairo go unstable when trying
to draw way out of the canvas ... lets not even try */
if (im->gdes[i].p_data[ii] > maxlimit) {
im->gdes[i].p_data[ii] = maxlimit;
}
if (im->gdes[i].p_data[ii] < minlimit) {
im->gdes[i].p_data[ii] = minlimit;
}
} /* for */
/* *******************************************************
a ___. (a,t)
| | ___
____| | | |
| |___|
-------|--t-1--t--------------------------------
if we know the value at time t was a then
we draw a square from t-1 to t with the value a.
********************************************************* */
if (im->gdes[i].col.alpha != 0.0) {
/* GF_LINE and friend */
if (im->gdes[i].gf == GF_LINE) {
double last_y = 0.0;
int draw_on = 0;
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
for (ii = 1; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])
|| (im->slopemode == 1
&& isnan(im->gdes[i].p_data[ii - 1]))) {
draw_on = 0;
continue;
}
if (draw_on == 0) {
last_y = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0) {
double x = ii - 1 + im->xorigin;
double y = last_y;
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
} else {
double x = ii - 1 + im->xorigin;
double y =
ytr(im, im->gdes[i].p_data[ii - 1]);
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
}
draw_on = 1;
} else {
double x1 = ii + im->xorigin;
double y1 = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0
&& !AlmostEqual2sComplement(y1, last_y, 4)) {
double x = ii - 1 + im->xorigin;
double y = y1;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
};
last_y = y1;
gfx_line_fit(im, &x1, &y1);
cairo_line_to(im->cr, x1, y1);
};
}
cairo_set_source_rgba(im->cr,
im->gdes[i].
col.red,
im->gdes[i].
col.green,
im->gdes[i].
col.blue, im->gdes[i].col.alpha);
cairo_set_line_cap(im->cr, CAIRO_LINE_CAP_ROUND);
cairo_set_line_join(im->cr, CAIRO_LINE_JOIN_ROUND);
cairo_stroke(im->cr);
cairo_restore(im->cr);
} else {
int idxI = -1;
double *foreY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *foreX =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backX =
(double *) malloc(sizeof(double) * im->xsize * 2);
int drawem = 0;
for (ii = 0; ii <= im->xsize; ii++) {
double ybase, ytop;
if (idxI > 0 && (drawem != 0 || ii == im->xsize)) {
int cntI = 1;
int lastI = 0;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI + 1], 4)) {
cntI++;
}
gfx_new_area(im,
backX[0], backY[0],
foreX[0], foreY[0],
foreX[cntI],
foreY[cntI], im->gdes[i].col);
while (cntI < idxI) {
lastI = cntI;
cntI++;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI
+ 1], 4)) {
cntI++;
}
gfx_add_point(im, foreX[cntI], foreY[cntI]);
}
gfx_add_point(im, backX[idxI], backY[idxI]);
while (idxI > 1) {
lastI = idxI;
idxI--;
while (idxI > 1
&&
AlmostEqual2sComplement(backY
[lastI],
backY[idxI], 4)
&&
AlmostEqual2sComplement(backY
[lastI],
backY
[idxI
- 1], 4)) {
idxI--;
}
gfx_add_point(im, backX[idxI], backY[idxI]);
}
idxI = -1;
drawem = 0;
gfx_close_path(im);
}
if (drawem != 0) {
drawem = 0;
idxI = -1;
}
if (ii == im->xsize)
break;
if (im->slopemode == 0 && ii == 0) {
continue;
}
if (isnan(im->gdes[i].p_data[ii])) {
drawem = 1;
continue;
}
ytop = ytr(im, im->gdes[i].p_data[ii]);
if (lastgdes && im->gdes[i].stack) {
ybase = ytr(im, lastgdes->p_data[ii]);
} else {
ybase = ytr(im, areazero);
}
if (ybase == ytop) {
drawem = 1;
continue;
}
if (ybase > ytop) {
double extra = ytop;
ytop = ybase;
ybase = extra;
}
if (im->slopemode == 0) {
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin - 1;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin - 1;
}
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin;
}
/* close up any remaining area */
free(foreY);
free(foreX);
free(backY);
free(backX);
} /* else GF_LINE */
}
/* if color != 0x0 */
/* make sure we do not run into trouble when stacking on NaN */
for (ii = 0; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])) {
if (lastgdes && (im->gdes[i].stack)) {
im->gdes[i].p_data[ii] = lastgdes->p_data[ii];
} else {
im->gdes[i].p_data[ii] = areazero;
}
}
}
lastgdes = &(im->gdes[i]);
break;
} /* GF_AREA, GF_LINE, GF_GRAD */
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
} /* switch */
}
cairo_reset_clip(im->cr);
/* grid_paint also does the text */
if (!(im->extra_flags & ONLY_GRAPH))
grid_paint(im);
if (!(im->extra_flags & ONLY_GRAPH))
axis_paint(im);
/* the RULES are the last thing to paint ... */
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_HRULE:
if (im->gdes[i].yrule >= im->minval
&& im->gdes[i].yrule <= im->maxval) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im, im->xorigin,
ytr(im, im->gdes[i].yrule),
im->xorigin + im->xsize,
ytr(im, im->gdes[i].yrule), 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
case GF_VRULE:
if (im->gdes[i].xrule >= im->start
&& im->gdes[i].xrule <= im->end) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im,
xtr(im, im->gdes[i].xrule),
im->yorigin, xtr(im,
im->
gdes[i].
xrule),
im->yorigin - im->ysize, 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
default:
break;
}
}
switch (im->imgformat) {
case IF_PNG:
{
cairo_status_t status;
status = strlen(im->graphfile) ?
cairo_surface_write_to_png(im->surface, im->graphfile)
: cairo_surface_write_to_png_stream(im->surface, &cairo_output,
im);
if (status != CAIRO_STATUS_SUCCESS) {
rrd_set_error("Could not save png to '%s'", im->graphfile);
return 1;
}
break;
}
default:
if (strlen(im->graphfile)) {
cairo_show_page(im->cr);
} else {
cairo_surface_finish(im->surface);
}
break;
}
return 0;
}
/*****************************************************
* graph stuff
*****************************************************/
int gdes_alloc(
image_desc_t *im)
{
im->gdes_c++;
if ((im->gdes = (graph_desc_t *)
rrd_realloc(im->gdes, (im->gdes_c)
* sizeof(graph_desc_t))) == NULL) {
rrd_set_error("realloc graph_descs");
return -1;
}
im->gdes[im->gdes_c - 1].step = im->step;
im->gdes[im->gdes_c - 1].step_orig = im->step;
im->gdes[im->gdes_c - 1].stack = 0;
im->gdes[im->gdes_c - 1].skipscale = 0;
im->gdes[im->gdes_c - 1].linewidth = 0;
im->gdes[im->gdes_c - 1].debug = 0;
im->gdes[im->gdes_c - 1].start = im->start;
im->gdes[im->gdes_c - 1].start_orig = im->start;
im->gdes[im->gdes_c - 1].end = im->end;
im->gdes[im->gdes_c - 1].end_orig = im->end;
im->gdes[im->gdes_c - 1].vname[0] = '\0';
im->gdes[im->gdes_c - 1].data = NULL;
im->gdes[im->gdes_c - 1].ds_namv = NULL;
im->gdes[im->gdes_c - 1].data_first = 0;
im->gdes[im->gdes_c - 1].p_data = NULL;
im->gdes[im->gdes_c - 1].rpnp = NULL;
im->gdes[im->gdes_c - 1].p_dashes = NULL;
im->gdes[im->gdes_c - 1].shift = 0.0;
im->gdes[im->gdes_c - 1].dash = 0;
im->gdes[im->gdes_c - 1].ndash = 0;
im->gdes[im->gdes_c - 1].offset = 0;
im->gdes[im->gdes_c - 1].col.red = 0.0;
im->gdes[im->gdes_c - 1].col.green = 0.0;
im->gdes[im->gdes_c - 1].col.blue = 0.0;
im->gdes[im->gdes_c - 1].col.alpha = 0.0;
im->gdes[im->gdes_c - 1].legend[0] = '\0';
im->gdes[im->gdes_c - 1].format[0] = '\0';
im->gdes[im->gdes_c - 1].strftm = 0;
im->gdes[im->gdes_c - 1].rrd[0] = '\0';
im->gdes[im->gdes_c - 1].ds = -1;
im->gdes[im->gdes_c - 1].cf_reduce = CF_AVERAGE;
im->gdes[im->gdes_c - 1].cf = CF_AVERAGE;
im->gdes[im->gdes_c - 1].yrule = DNAN;
im->gdes[im->gdes_c - 1].xrule = 0;
return 0;
}
/* copies input untill the first unescaped colon is found
or until input ends. backslashes have to be escaped as well */
int scan_for_col(
const char *const input,
int len,
char *const output)
{
int inp, outp = 0;
for (inp = 0; inp < len && input[inp] != ':' && input[inp] != '\0'; inp++) {
if (input[inp] == '\\'
&& input[inp + 1] != '\0'
&& (input[inp + 1] == '\\' || input[inp + 1] == ':')) {
output[outp++] = input[++inp];
} else {
output[outp++] = input[inp];
}
}
output[outp] = '\0';
return inp;
}
/* Now just a wrapper around rrd_graph_v */
int rrd_graph(
int argc,
char **argv,
char ***prdata,
int *xsize,
int *ysize,
FILE * stream,
double *ymin,
double *ymax)
{
int prlines = 0;
rrd_info_t *grinfo = NULL;
rrd_info_t *walker;
grinfo = rrd_graph_v(argc, argv);
if (grinfo == NULL)
return -1;
walker = grinfo;
(*prdata) = NULL;
while (walker) {
if (strcmp(walker->key, "image_info") == 0) {
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
/* imginfo goes to position 0 in the prdata array */
(*prdata)[prlines - 1] = (char*)malloc((strlen(walker->value.u_str)
+ 2) * sizeof(char));
strcpy((*prdata)[prlines - 1], walker->value.u_str);
(*prdata)[prlines] = NULL;
}
/* skip anything else */
walker = walker->next;
}
walker = grinfo;
*xsize = 0;
*ysize = 0;
*ymin = 0;
*ymax = 0;
while (walker) {
if (strcmp(walker->key, "image_width") == 0) {
*xsize = walker->value.u_cnt;
} else if (strcmp(walker->key, "image_height") == 0) {
*ysize = walker->value.u_cnt;
} else if (strcmp(walker->key, "value_min") == 0) {
*ymin = walker->value.u_val;
} else if (strcmp(walker->key, "value_max") == 0) {
*ymax = walker->value.u_val;
} else if (strncmp(walker->key, "print", 5) == 0) { /* keys are prdate[0..] */
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
(*prdata)[prlines - 1] = (char*)malloc((strlen(walker->value.u_str)
+ 2) * sizeof(char));
(*prdata)[prlines] = NULL;
strcpy((*prdata)[prlines - 1], walker->value.u_str);
} else if (strcmp(walker->key, "image") == 0) {
if ( fwrite(walker->value.u_blo.ptr, walker->value.u_blo.size, 1,
(stream ? stream : stdout)) == 0 && ferror(stream ? stream : stdout)){
rrd_set_error("writing image");
return 0;
}
}
/* skip anything else */
walker = walker->next;
}
rrd_info_free(grinfo);
return 0;
}
static int bad_format_imginfo( char *fmt);
/* Some surgery done on this function, it became ridiculously big.
** Things moved:
** - initializing now in rrd_graph_init()
** - options parsing now in rrd_graph_options()
** - script parsing now in rrd_graph_script()
*/
rrd_info_t *rrd_graph_v(
int argc,
char **argv)
{
image_desc_t im;
rrd_info_t *grinfo;
char *old_locale;
rrd_graph_init(&im);
/* a dummy surface so that we can measure text sizes for placements */
old_locale = setlocale(LC_NUMERIC, "C");
rrd_graph_options(argc, argv, &im);
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
if (optind >= argc) {
rrd_info_free(im.grinfo);
im_free(&im);
rrd_set_error("missing filename");
return NULL;
}
if (strlen(argv[optind]) >= MAXPATH) {
rrd_set_error("filename (including path) too long");
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
strncpy(im.graphfile, argv[optind], MAXPATH - 1);
im.graphfile[MAXPATH - 1] = '\0';
if (strcmp(im.graphfile, "-") == 0) {
im.graphfile[0] = '\0';
}
rrd_graph_script(argc, argv, &im, 1);
setlocale(LC_NUMERIC, old_locale); /* reenable locale for rendering the graph */
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* Everything is now read and the actual work can start */
if (graph_paint(&im) == -1) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* The image is generated and needs to be output.
** Also, if needed, print a line with information about the image.
*/
if (im.imginfo) {
rrd_infoval_t info;
char *path;
char *filename;
if (bad_format_imginfo(im.imginfo)) {
rrd_info_free(im.grinfo);
im_free(&im);
rrd_set_error("bad format for imginfo");
return NULL;
}
path = strdup(im.graphfile);
filename = basename(path);
info.u_str =
sprintf_alloc(im.imginfo,
filename,
(long) (im.zoom *
im.ximg), (long) (im.zoom * im.yimg));
grinfo_push(&im, sprintf_alloc("image_info"), RD_I_STR, info);
free(info.u_str);
free(path);
}
if (im.rendered_image) {
rrd_infoval_t img;
img.u_blo.size = im.rendered_image_size;
img.u_blo.ptr = im.rendered_image;
grinfo_push(&im, sprintf_alloc("image"), RD_I_BLO, img);
}
grinfo = im.grinfo;
im_free(&im);
return grinfo;
}
static void
rrd_set_font_desc (
image_desc_t *im,int prop,char *font, double size ){
if (font){
strncpy(im->text_prop[prop].font, font, sizeof(text_prop[prop].font) - 1);
im->text_prop[prop].font[sizeof(text_prop[prop].font) - 1] = '\0';
/* if we already got one, drop it first */
pango_font_description_free(im->text_prop[prop].font_desc);
im->text_prop[prop].font_desc = pango_font_description_from_string( font );
};
if (size > 0){
im->text_prop[prop].size = size;
};
if (im->text_prop[prop].font_desc && im->text_prop[prop].size ){
pango_font_description_set_size(im->text_prop[prop].font_desc, im->text_prop[prop].size * PANGO_SCALE);
};
}
void rrd_graph_init(
image_desc_t
*im)
{
unsigned int i;
char *deffont = getenv("RRD_DEFAULT_FONT");
static PangoFontMap *fontmap = NULL;
PangoContext *context;
#ifdef HAVE_TZSET
tzset();
#endif
im->gdef_map = g_hash_table_new_full(g_str_hash, g_str_equal,g_free,NULL);
im->rrd_map = g_hash_table_new_full(g_str_hash, g_str_equal,g_free,NULL);
im->base = 1000;
im->daemon_addr = NULL;
im->draw_x_grid = 1;
im->draw_y_grid = 1;
im->draw_3d_border = 2;
im->dynamic_labels = 0;
im->extra_flags = 0;
im->font_options = cairo_font_options_create();
im->forceleftspace = 0;
im->gdes_c = 0;
im->gdes = NULL;
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
im->grid_dash_off = 1;
im->grid_dash_on = 1;
im->gridfit = 1;
im->grinfo = (rrd_info_t *) NULL;
im->grinfo_current = (rrd_info_t *) NULL;
im->imgformat = IF_PNG;
im->imginfo = NULL;
im->lazy = 0;
im->legenddirection = TOP_DOWN;
im->legendheight = 0;
im->legendposition = SOUTH;
im->legendwidth = 0;
im->logarithmic = 0;
im->maxval = DNAN;
im->minval = 0;
im->minval = DNAN;
im->magfact = 1;
im->prt_c = 0;
im->rigid = 0;
im->rendered_image_size = 0;
im->rendered_image = NULL;
im->slopemode = 0;
im->step = 0;
im->symbol = ' ';
im->tabwidth = 40.0;
im->title[0] = '\0';
im->unitsexponent = 9999;
im->unitslength = 6;
im->viewfactor = 1.0;
im->watermark[0] = '\0';
im->with_markup = 0;
im->ximg = 0;
im->xlab_user.minsec = -1;
im->xorigin = 0;
im->xOriginLegend = 0;
im->xOriginLegendY = 0;
im->xOriginLegendY2 = 0;
im->xOriginTitle = 0;
im->xsize = 400;
im->ygridstep = DNAN;
im->yimg = 0;
im->ylegend[0] = '\0';
im->second_axis_scale = 0; /* 0 disables it */
im->second_axis_shift = 0; /* no shift by default */
im->second_axis_legend[0] = '\0';
im->second_axis_format[0] = '\0';
im->primary_axis_format[0] = '\0';
im->yorigin = 0;
im->yOriginLegend = 0;
im->yOriginLegendY = 0;
im->yOriginLegendY2 = 0;
im->yOriginTitle = 0;
im->ysize = 100;
im->zoom = 1;
im->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 10, 10);
im->cr = cairo_create(im->surface);
for (i = 0; i < DIM(text_prop); i++) {
im->text_prop[i].size = -1;
im->text_prop[i].font_desc = NULL;
rrd_set_font_desc(im,i, deffont ? deffont : text_prop[i].font,text_prop[i].size);
}
if (fontmap == NULL){
fontmap = pango_cairo_font_map_get_default();
}
context = pango_cairo_font_map_create_context((PangoCairoFontMap*)fontmap);
pango_cairo_context_set_resolution(context, 100);
pango_cairo_update_context(im->cr,context);
im->layout = pango_layout_new(context);
g_object_unref (context);
// im->layout = pango_cairo_create_layout(im->cr);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
cairo_font_options_set_hint_metrics
(im->font_options, CAIRO_HINT_METRICS_ON);
cairo_font_options_set_antialias(im->font_options, CAIRO_ANTIALIAS_GRAY);
for (i = 0; i < DIM(graph_col); i++)
im->graph_col[i] = graph_col[i];
}
void rrd_graph_options(
int argc,
char *argv[],
image_desc_t
*im)
{
int stroff;
char *parsetime_error = NULL;
char scan_gtm[12], scan_mtm[12], scan_ltm[12], col_nam[12];
time_t start_tmp = 0, end_tmp = 0;
long long_tmp;
rrd_time_value_t start_tv, end_tv;
long unsigned int color;
/* defines for long options without a short equivalent. should be bytes,
and may not collide with (the ASCII value of) short options */
#define LONGOPT_UNITS_SI 255
/* *INDENT-OFF* */
struct option long_options[] = {
{ "alt-autoscale", no_argument, 0, 'A'},
{ "imgformat", required_argument, 0, 'a'},
{ "font-smoothing-threshold", required_argument, 0, 'B'},
{ "base", required_argument, 0, 'b'},
{ "color", required_argument, 0, 'c'},
{ "full-size-mode", no_argument, 0, 'D'},
{ "daemon", required_argument, 0, 'd'},
{ "slope-mode", no_argument, 0, 'E'},
{ "end", required_argument, 0, 'e'},
{ "force-rules-legend", no_argument, 0, 'F'},
{ "imginfo", required_argument, 0, 'f'},
{ "graph-render-mode", required_argument, 0, 'G'},
{ "no-legend", no_argument, 0, 'g'},
{ "height", required_argument, 0, 'h'},
{ "no-minor", no_argument, 0, 'I'},
{ "interlaced", no_argument, 0, 'i'},
{ "alt-autoscale-min", no_argument, 0, 'J'},
{ "only-graph", no_argument, 0, 'j'},
{ "units-length", required_argument, 0, 'L'},
{ "lower-limit", required_argument, 0, 'l'},
{ "alt-autoscale-max", no_argument, 0, 'M'},
{ "zoom", required_argument, 0, 'm'},
{ "no-gridfit", no_argument, 0, 'N'},
{ "font", required_argument, 0, 'n'},
{ "logarithmic", no_argument, 0, 'o'},
{ "pango-markup", no_argument, 0, 'P'},
{ "font-render-mode", required_argument, 0, 'R'},
{ "rigid", no_argument, 0, 'r'},
{ "step", required_argument, 0, 'S'},
{ "start", required_argument, 0, 's'},
{ "tabwidth", required_argument, 0, 'T'},
{ "title", required_argument, 0, 't'},
{ "upper-limit", required_argument, 0, 'u'},
{ "vertical-label", required_argument, 0, 'v'},
{ "watermark", required_argument, 0, 'W'},
{ "width", required_argument, 0, 'w'},
{ "units-exponent", required_argument, 0, 'X'},
{ "x-grid", required_argument, 0, 'x'},
{ "alt-y-grid", no_argument, 0, 'Y'},
{ "y-grid", required_argument, 0, 'y'},
{ "lazy", no_argument, 0, 'z'},
{ "units", required_argument, 0, LONGOPT_UNITS_SI},
{ "alt-y-mrtg", no_argument, 0, 1000}, /* this has no effect it is just here to save old apps from crashing when they use it */
{ "disable-rrdtool-tag",no_argument, 0, 1001},
{ "right-axis", required_argument, 0, 1002},
{ "right-axis-label", required_argument, 0, 1003},
{ "right-axis-format", required_argument, 0, 1004},
{ "legend-position", required_argument, 0, 1005},
{ "legend-direction", required_argument, 0, 1006},
{ "border", required_argument, 0, 1007},
{ "grid-dash", required_argument, 0, 1008},
{ "dynamic-labels", no_argument, 0, 1009},
{ "left-axis-format", required_argument, 0, 1010},
{ 0, 0, 0, 0}
};
/* *INDENT-ON* */
optind = 0;
opterr = 0; /* initialize getopt */
rrd_parsetime("end-24h", &start_tv);
rrd_parsetime("now", &end_tv);
while (1) {
int option_index = 0;
int opt;
int col_start, col_end;
opt = getopt_long(argc, argv,
"Aa:B:b:c:Dd:Ee:Ff:G:gh:IiJjL:l:Mm:Nn:oPR:rS:s:T:t:u:v:W:w:X:x:Yy:z",
long_options, &option_index);
if (opt == EOF)
break;
switch (opt) {
case 'I':
im->extra_flags |= NOMINOR;
break;
case 'Y':
im->extra_flags |= ALTYGRID;
break;
case 'A':
im->extra_flags |= ALTAUTOSCALE;
break;
case 'J':
im->extra_flags |= ALTAUTOSCALE_MIN;
break;
case 'M':
im->extra_flags |= ALTAUTOSCALE_MAX;
break;
case 'j':
im->extra_flags |= ONLY_GRAPH;
break;
case 'g':
im->extra_flags |= NOLEGEND;
break;
case 1005:
if (strcmp(optarg, "north") == 0) {
im->legendposition = NORTH;
} else if (strcmp(optarg, "west") == 0) {
im->legendposition = WEST;
} else if (strcmp(optarg, "south") == 0) {
im->legendposition = SOUTH;
} else if (strcmp(optarg, "east") == 0) {
im->legendposition = EAST;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 1006:
if (strcmp(optarg, "topdown") == 0) {
im->legenddirection = TOP_DOWN;
} else if (strcmp(optarg, "bottomup") == 0) {
im->legenddirection = BOTTOM_UP;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 'F':
im->extra_flags |= FORCE_RULES_LEGEND;
break;
case 1001:
im->extra_flags |= NO_RRDTOOL_TAG;
break;
case LONGOPT_UNITS_SI:
if (im->extra_flags & FORCE_UNITS) {
rrd_set_error("--units can only be used once!");
return;
}
if (strcmp(optarg, "si") == 0)
im->extra_flags |= FORCE_UNITS_SI;
else {
rrd_set_error("invalid argument for --units: %s", optarg);
return;
}
break;
case 'X':
im->unitsexponent = atoi(optarg);
break;
case 'L':
im->unitslength = atoi(optarg);
im->forceleftspace = 1;
break;
case 'T':
im->tabwidth = atof(optarg);
break;
case 'S':
im->step = atoi(optarg);
break;
case 'N':
im->gridfit = 0;
break;
case 'P':
im->with_markup = 1;
break;
case 's':
if ((parsetime_error = rrd_parsetime(optarg, &start_tv))) {
rrd_set_error("start time: %s", parsetime_error);
return;
}
break;
case 'e':
if ((parsetime_error = rrd_parsetime(optarg, &end_tv))) {
rrd_set_error("end time: %s", parsetime_error);
return;
}
break;
case 'x':
if (strcmp(optarg, "none") == 0) {
im->draw_x_grid = 0;
break;
};
if (sscanf(optarg,
"%10[A-Z]:%ld:%10[A-Z]:%ld:%10[A-Z]:%ld:%ld:%n",
scan_gtm,
&im->xlab_user.gridst,
scan_mtm,
&im->xlab_user.mgridst,
scan_ltm,
&im->xlab_user.labst,
&im->xlab_user.precis, &stroff) == 7 && stroff != 0) {
strncpy(im->xlab_form, optarg + stroff,
sizeof(im->xlab_form) - 1);
im->xlab_form[sizeof(im->xlab_form) - 1] = '\0';
if ((int)
(im->xlab_user.gridtm = tmt_conv(scan_gtm)) == -1) {
rrd_set_error("unknown keyword %s", scan_gtm);
return;
} else if ((int)
(im->xlab_user.mgridtm = tmt_conv(scan_mtm))
== -1) {
rrd_set_error("unknown keyword %s", scan_mtm);
return;
} else if ((int)
(im->xlab_user.labtm = tmt_conv(scan_ltm)) == -1) {
rrd_set_error("unknown keyword %s", scan_ltm);
return;
}
im->xlab_user.minsec = 1;
im->xlab_user.stst = im->xlab_form;
} else {
rrd_set_error("invalid x-grid format");
return;
}
break;
case 'y':
if (strcmp(optarg, "none") == 0) {
im->draw_y_grid = 0;
break;
};
if (sscanf(optarg, "%lf:%d", &im->ygridstep, &im->ylabfact) == 2) {
if (im->ygridstep <= 0) {
rrd_set_error("grid step must be > 0");
return;
} else if (im->ylabfact < 1) {
rrd_set_error("label factor must be > 0");
return;
}
} else {
rrd_set_error("invalid y-grid format");
return;
}
break;
case 1007:
im->draw_3d_border = atoi(optarg);
break;
case 1008: /* grid-dash */
if(sscanf(optarg,
"%lf:%lf",
&im->grid_dash_on,
&im->grid_dash_off) != 2) {
rrd_set_error("expected grid-dash format float:float");
return;
}
break;
case 1009: /* enable dynamic labels */
im->dynamic_labels = 1;
break;
case 1002: /* right y axis */
if(sscanf(optarg,
"%lf:%lf",
&im->second_axis_scale,
&im->second_axis_shift) == 2) {
if(im->second_axis_scale==0){
rrd_set_error("the second_axis_scale must not be 0");
return;
}
} else {
rrd_set_error("invalid right-axis format expected scale:shift");
return;
}
break;
case 1003:
strncpy(im->second_axis_legend,optarg,150);
im->second_axis_legend[150]='\0';
break;
case 1004:
if (bad_format(optarg)){
rrd_set_error("use either %le or %lf formats");
return;
}
strncpy(im->second_axis_format,optarg,150);
im->second_axis_format[150]='\0';
break;
case 1010:
if (bad_format(optarg)){
rrd_set_error("use either %le or %lf formats");
return;
}
strncpy(im->primary_axis_format,optarg,150);
im->primary_axis_format[150]='\0';
break;
case 'v':
strncpy(im->ylegend, optarg, 150);
im->ylegend[150] = '\0';
break;
case 'u':
im->maxval = atof(optarg);
break;
case 'l':
im->minval = atof(optarg);
break;
case 'b':
im->base = atol(optarg);
if (im->base != 1024 && im->base != 1000) {
rrd_set_error
("the only sensible value for base apart from 1000 is 1024");
return;
}
break;
case 'w':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("width below 10 pixels");
return;
}
im->xsize = long_tmp;
break;
case 'h':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("height below 10 pixels");
return;
}
im->ysize = long_tmp;
break;
case 'D':
im->extra_flags |= FULL_SIZE_MODE;
break;
case 'i':
/* interlaced png not supported at the moment */
break;
case 'r':
im->rigid = 1;
break;
case 'f':
im->imginfo = optarg;
break;
case 'a':
if ((int)
(im->imgformat = if_conv(optarg)) == -1) {
rrd_set_error("unsupported graphics format '%s'", optarg);
return;
}
break;
case 'z':
im->lazy = 1;
break;
case 'E':
im->slopemode = 1;
break;
case 'o':
im->logarithmic = 1;
break;
case 'c':
if (sscanf(optarg,
"%10[A-Z]#%n%8lx%n",
col_nam, &col_start, &color, &col_end) == 2) {
int ci;
int col_len = col_end - col_start;
switch (col_len) {
case 3:
color =
(((color & 0xF00) * 0x110000) | ((color & 0x0F0) *
0x011000) |
((color & 0x00F)
* 0x001100)
| 0x000000FF);
break;
case 4:
color =
(((color & 0xF000) *
0x11000) | ((color & 0x0F00) *
0x01100) | ((color &
0x00F0) *
0x00110) |
((color & 0x000F) * 0x00011)
);
break;
case 6:
color = (color << 8) + 0xff /* shift left by 8 */ ;
break;
case 8:
break;
default:
rrd_set_error("the color format is #RRGGBB[AA]");
return;
}
if ((ci = grc_conv(col_nam)) != -1) {
im->graph_col[ci] = gfx_hex_to_col(color);
} else {
rrd_set_error("invalid color name '%s'", col_nam);
return;
}
} else {
rrd_set_error("invalid color def format");
return;
}
break;
case 'n':{
char prop[15];
double size = 1;
int end;
if (sscanf(optarg, "%10[A-Z]:%lf%n", prop, &size, &end) >= 2) {
int sindex, propidx;
if ((sindex = text_prop_conv(prop)) != -1) {
for (propidx = sindex;
propidx < TEXT_PROP_LAST; propidx++) {
if (size > 0) {
rrd_set_font_desc(im,propidx,NULL,size);
}
if ((int) strlen(optarg) > end+2) {
if (optarg[end] == ':') {
rrd_set_font_desc(im,propidx,optarg + end + 1,0);
} else {
rrd_set_error
("expected : after font size in '%s'",
optarg);
return;
}
}
/* only run the for loop for DEFAULT (0) for
all others, we break here. woodo programming */
if (propidx == sindex && sindex != 0)
break;
}
} else {
rrd_set_error("invalid fonttag '%s'", prop);
return;
}
} else {
rrd_set_error("invalid text property format");
return;
}
break;
}
case 'm':
im->zoom = atof(optarg);
if (im->zoom <= 0.0) {
rrd_set_error("zoom factor must be > 0");
return;
}
break;
case 't':
strncpy(im->title, optarg, 150);
im->title[150] = '\0';
break;
case 'R':
if (strcmp(optarg, "normal") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else if (strcmp(optarg, "light") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_SLIGHT);
} else if (strcmp(optarg, "mono") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_NONE);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else {
rrd_set_error("unknown font-render-mode '%s'", optarg);
return;
}
break;
case 'G':
if (strcmp(optarg, "normal") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
else if (strcmp(optarg, "mono") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_NONE;
else {
rrd_set_error("unknown graph-render-mode '%s'", optarg);
return;
}
break;
case 'B':
/* not supported curently */
break;
case 'W':
strncpy(im->watermark, optarg, 100);
im->watermark[99] = '\0';
break;
case 'd':
{
if (im->daemon_addr != NULL)
{
rrd_set_error ("You cannot specify --daemon "
"more than once.");
return;
}
im->daemon_addr = strdup(optarg);
if (im->daemon_addr == NULL)
{
rrd_set_error("strdup failed");
return;
}
break;
}
case '?':
if (optopt != 0)
rrd_set_error("unknown option '%c'", optopt);
else
rrd_set_error("unknown option '%s'", argv[optind - 1]);
return;
}
} /* while (1) */
{ /* try to connect to rrdcached */
int status = rrdc_connect(im->daemon_addr);
if (status != 0) return;
}
pango_cairo_context_set_font_options(pango_layout_get_context(im->layout), im->font_options);
pango_layout_context_changed(im->layout);
if (im->logarithmic && im->minval <= 0) {
rrd_set_error
("for a logarithmic yaxis you must specify a lower-limit > 0");
return;
}
if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
/* error string is set in rrd_parsetime.c */
return;
}
if (start_tmp < 3600 * 24 * 365 * 10) {
rrd_set_error
("the first entry to fetch should be after 1980 (%ld)",
start_tmp);
return;
}
if (end_tmp < start_tmp) {
rrd_set_error
("start (%ld) should be less than end (%ld)", start_tmp, end_tmp);
return;
}
im->start = start_tmp;
im->end = end_tmp;
im->step = max((long) im->step, (im->end - im->start) / im->xsize);
}
int rrd_graph_color(
image_desc_t
*im,
char *var,
char *err,
int optional)
{
char *color;
graph_desc_t *gdp = &im->gdes[im->gdes_c - 1];
color = strstr(var, "#");
if (color == NULL) {
if (optional == 0) {
rrd_set_error("Found no color in %s", err);
return 0;
}
return 0;
} else {
int n = 0;
char *rest;
long unsigned int col;
rest = strstr(color, ":");
if (rest != NULL)
n = rest - color;
else
n = strlen(color);
switch (n) {
case 7:
sscanf(color, "#%6lx%n", &col, &n);
col = (col << 8) + 0xff /* shift left by 8 */ ;
if (n != 7)
rrd_set_error("Color problem in %s", err);
break;
case 9:
sscanf(color, "#%8lx%n", &col, &n);
if (n == 9)
break;
default:
rrd_set_error("Color problem in %s", err);
}
if (rrd_test_error())
return 0;
gdp->col = gfx_hex_to_col(col);
return n;
}
}
int bad_format(
char *fmt)
{
char *ptr;
int n = 0;
ptr = fmt;
while (*ptr != '\0')
if (*ptr++ == '%') {
/* line cannot end with percent char */
if (*ptr == '\0')
return 1;
/* '%s', '%S' and '%%' are allowed */
if (*ptr == 's' || *ptr == 'S' || *ptr == '%')
ptr++;
/* %c is allowed (but use only with vdef!) */
else if (*ptr == 'c') {
ptr++;
n = 1;
}
/* or else '% 6.2lf' and such are allowed */
else {
/* optional padding character */
if (*ptr == ' ' || *ptr == '+' || *ptr == '-')
ptr++;
/* This should take care of 'm.n' with all three optional */
while (*ptr >= '0' && *ptr <= '9')
ptr++;
if (*ptr == '.')
ptr++;
while (*ptr >= '0' && *ptr <= '9')
ptr++;
/* Either 'le', 'lf' or 'lg' must follow here */
if (*ptr++ != 'l')
return 1;
if (*ptr == 'e' || *ptr == 'f' || *ptr == 'g')
ptr++;
else
return 1;
n++;
}
}
return (n != 1);
}
static int bad_format_imginfo(
char *fmt)
{
char *ptr;
int n = 0;
ptr = fmt;
while (*ptr != '\0')
if (*ptr++ == '%') {
/* line cannot end with percent char */
if (*ptr == '\0')
return 1;
/* '%%' is allowed */
if (*ptr == '%')
ptr++;
/* '%s', '%S' are allowed */
else if (*ptr == 's' || *ptr == 'S') {
n = 1;
ptr++;
}
/* or else '% 4lu' and such are allowed */
else {
/* optional padding character */
if (*ptr == ' ')
ptr++;
/* This should take care of 'm' */
while (*ptr >= '0' && *ptr <= '9')
ptr++;
/* 'lu' must follow here */
if (*ptr++ != 'l')
return 1;
if (*ptr == 'u')
ptr++;
else
return 1;
n++;
}
}
return (n != 3);
}
int vdef_parse(
struct graph_desc_t
*gdes,
const char *const str)
{
/* A VDEF currently is either "func" or "param,func"
* so the parsing is rather simple. Change if needed.
*/
double param;
char func[30];
int n;
n = 0;
sscanf(str, "%le,%29[A-Z]%n", ¶m, func, &n);
if (n == (int) strlen(str)) { /* matched */
;
} else {
n = 0;
sscanf(str, "%29[A-Z]%n", func, &n);
if (n == (int) strlen(str)) { /* matched */
param = DNAN;
} else {
rrd_set_error
("Unknown function string '%s' in VDEF '%s'",
str, gdes->vname);
return -1;
}
}
if (!strcmp("PERCENT", func))
gdes->vf.op = VDEF_PERCENT;
else if (!strcmp("PERCENTNAN", func))
gdes->vf.op = VDEF_PERCENTNAN;
else if (!strcmp("MAXIMUM", func))
gdes->vf.op = VDEF_MAXIMUM;
else if (!strcmp("AVERAGE", func))
gdes->vf.op = VDEF_AVERAGE;
else if (!strcmp("STDEV", func))
gdes->vf.op = VDEF_STDEV;
else if (!strcmp("MINIMUM", func))
gdes->vf.op = VDEF_MINIMUM;
else if (!strcmp("TOTAL", func))
gdes->vf.op = VDEF_TOTAL;
else if (!strcmp("FIRST", func))
gdes->vf.op = VDEF_FIRST;
else if (!strcmp("LAST", func))
gdes->vf.op = VDEF_LAST;
else if (!strcmp("LSLSLOPE", func))
gdes->vf.op = VDEF_LSLSLOPE;
else if (!strcmp("LSLINT", func))
gdes->vf.op = VDEF_LSLINT;
else if (!strcmp("LSLCORREL", func))
gdes->vf.op = VDEF_LSLCORREL;
else {
rrd_set_error
("Unknown function '%s' in VDEF '%s'\n", func, gdes->vname);
return -1;
};
switch (gdes->vf.op) {
case VDEF_PERCENT:
case VDEF_PERCENTNAN:
if (isnan(param)) { /* no parameter given */
rrd_set_error
("Function '%s' needs parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
if (param >= 0.0 && param <= 100.0) {
gdes->vf.param = param;
gdes->vf.val = DNAN; /* undefined */
gdes->vf.when = 0; /* undefined */
} else {
rrd_set_error
("Parameter '%f' out of range in VDEF '%s'\n",
param, gdes->vname);
return -1;
};
break;
case VDEF_MAXIMUM:
case VDEF_AVERAGE:
case VDEF_STDEV:
case VDEF_MINIMUM:
case VDEF_TOTAL:
case VDEF_FIRST:
case VDEF_LAST:
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:
if (isnan(param)) {
gdes->vf.param = DNAN;
gdes->vf.val = DNAN;
gdes->vf.when = 0;
} else {
rrd_set_error
("Function '%s' needs no parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
break;
};
return 0;
}
int vdef_calc(
image_desc_t *im,
int gdi)
{
graph_desc_t *src, *dst;
rrd_value_t *data;
long step, steps;
dst = &im->gdes[gdi];
src = &im->gdes[dst->vidx];
data = src->data + src->ds;
steps = (src->end - src->start) / src->step;
#if 0
printf
("DEBUG: start == %lu, end == %lu, %lu steps\n",
src->start, src->end, steps);
#endif
switch (dst->vf.op) {
case VDEF_PERCENT:{
rrd_value_t *array;
int field;
if ((array = (rrd_value_t*)malloc(steps * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
for (step = 0; step < steps; step++) {
array[step] = data[step * src->ds_cnt];
}
qsort(array, step, sizeof(double), vdef_percent_compar);
field = round((dst->vf.param * (double)(steps - 1)) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
free(array);
#if 0
for (step = 0; step < steps; step++)
printf("DEBUG: %3li:%10.2f %c\n",
step, array[step], step == field ? '*' : ' ');
#endif
}
break;
case VDEF_PERCENTNAN:{
rrd_value_t *array;
int field;
/* count number of "valid" values */
int nancount=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) { nancount++; }
}
/* and allocate it */
if ((array = (rrd_value_t*)malloc(nancount * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
/* and fill it in */
field=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) {
array[field] = data[step * src->ds_cnt];
field++;
}
}
qsort(array, nancount, sizeof(double), vdef_percent_compar);
field = round( dst->vf.param * (double)(nancount - 1) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
free(array);
}
break;
case VDEF_MAXIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] > dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
}
step++;
}
break;
case VDEF_TOTAL:
case VDEF_STDEV:
case VDEF_AVERAGE:{
int cnt = 0;
double sum = 0.0;
double average = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += data[step * src->ds_cnt];
cnt++;
};
}
if (cnt) {
if (dst->vf.op == VDEF_TOTAL) {
dst->vf.val = sum * src->step;
dst->vf.when = 0; /* no time component */
} else if (dst->vf.op == VDEF_AVERAGE) {
dst->vf.val = sum / cnt;
dst->vf.when = 0; /* no time component */
} else {
average = sum / cnt;
sum = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += pow((data[step * src->ds_cnt] - average), 2.0);
};
}
dst->vf.val = pow(sum / cnt, 0.5);
dst->vf.when = 0; /* no time component */
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
}
}
break;
case VDEF_MINIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] < dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
}
step++;
}
break;
case VDEF_FIRST:
/* The time value returned here is one step before the
* actual time value. This is the start of the first
* non-NaN interval.
*/
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + step * src->step;
}
break;
case VDEF_LAST:
/* The time value returned here is the
* actual time value. This is the end of the last
* non-NaN interval.
*/
step = steps - 1;
while (step >= 0 && isnan(data[step * src->ds_cnt]))
step--;
if (step < 0) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
break;
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:{
/* Bestfit line by linear least squares method */
int cnt = 0;
double SUMx, SUMy, SUMxy, SUMxx, SUMyy, slope, y_intercept, correl;
SUMx = 0;
SUMy = 0;
SUMxy = 0;
SUMxx = 0;
SUMyy = 0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
cnt++;
SUMx += step;
SUMxx += step * step;
SUMxy += step * data[step * src->ds_cnt];
SUMy += data[step * src->ds_cnt];
SUMyy += data[step * src->ds_cnt] * data[step * src->ds_cnt];
};
}
slope = (SUMx * SUMy - cnt * SUMxy) / (SUMx * SUMx - cnt * SUMxx);
y_intercept = (SUMy - slope * SUMx) / cnt;
correl =
(SUMxy -
(SUMx * SUMy) / cnt) /
sqrt((SUMxx -
(SUMx * SUMx) / cnt) * (SUMyy - (SUMy * SUMy) / cnt));
if (cnt) {
if (dst->vf.op == VDEF_LSLSLOPE) {
dst->vf.val = slope;
dst->vf.when = 0;
} else if (dst->vf.op == VDEF_LSLINT) {
dst->vf.val = y_intercept;
dst->vf.when = 0;
} else if (dst->vf.op == VDEF_LSLCORREL) {
dst->vf.val = correl;
dst->vf.when = 0;
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
}
}
break;
}
return 0;
}
/* NaN < -INF < finite_values < INF */
int vdef_percent_compar(
const void
*a,
const void
*b)
{
/* Equality is not returned; this doesn't hurt except
* (maybe) for a little performance.
*/
/* First catch NaN values. They are smallest */
if (isnan(*(double *) a))
return -1;
if (isnan(*(double *) b))
return 1;
/* NaN doesn't reach this part so INF and -INF are extremes.
* The sign from isinf() is compatible with the sign we return
*/
if (isinf(*(double *) a))
return isinf(*(double *) a);
if (isinf(*(double *) b))
return isinf(*(double *) b);
/* If we reach this, both values must be finite */
if (*(double *) a < *(double *) b)
return -1;
else
return 1;
}
void grinfo_push(
image_desc_t *im,
char *key,
rrd_info_type_t type,
rrd_infoval_t value)
{
im->grinfo_current = rrd_info_push(im->grinfo_current, key, type, value);
if (im->grinfo == NULL) {
im->grinfo = im->grinfo_current;
}
}
| ./CrossVul/dataset_final_sorted/CWE-134/c/bad_2266_0 |
crossvul-cpp_data_good_3455_0 | /* vi:set et ai sw=2 sts=2 ts=2: */
/*-
* Copyright (c) 2005-2007 Benedikt Meurer <benny@xfce.org>
* Copyright (c) 2009-2011 Jannis Pohlmann <jannis@xfce.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <gio/gio.h>
#include <thunar/thunar-application.h>
#include <thunar/thunar-gio-extensions.h>
#include <thunar/thunar-io-scan-directory.h>
#include <thunar/thunar-io-jobs-util.h>
#include <thunar/thunar-job.h>
#include <thunar/thunar-private.h>
#include <thunar/thunar-thumbnail-cache.h>
#include <thunar/thunar-transfer-job.h>
typedef struct _ThunarTransferNode ThunarTransferNode;
static void thunar_transfer_job_finalize (GObject *object);
static gboolean thunar_transfer_job_execute (ExoJob *job,
GError **error);
static void thunar_transfer_node_free (ThunarTransferNode *node);
struct _ThunarTransferJobClass
{
ThunarJobClass __parent__;
};
struct _ThunarTransferJob
{
ThunarJob __parent__;
ThunarTransferJobType type;
GList *source_node_list;
GList *target_file_list;
guint64 total_size;
guint64 total_progress;
guint64 file_progress;
gdouble previous_percentage;
};
struct _ThunarTransferNode
{
ThunarTransferNode *next;
ThunarTransferNode *children;
GFile *source_file;
};
G_DEFINE_TYPE (ThunarTransferJob, thunar_transfer_job, THUNAR_TYPE_JOB)
static void
thunar_transfer_job_class_init (ThunarTransferJobClass *klass)
{
GObjectClass *gobject_class;
ExoJobClass *exojob_class;
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = thunar_transfer_job_finalize;
exojob_class = EXO_JOB_CLASS (klass);
exojob_class->execute = thunar_transfer_job_execute;
}
static void
thunar_transfer_job_init (ThunarTransferJob *job)
{
job->type = 0;
job->source_node_list = NULL;
job->target_file_list = NULL;
job->total_size = 0;
job->total_progress = 0;
job->file_progress = 0;
job->previous_percentage = 0.0;
}
static void
thunar_transfer_job_finalize (GObject *object)
{
ThunarTransferJob *job = THUNAR_TRANSFER_JOB (object);
g_list_foreach (job->source_node_list, (GFunc) thunar_transfer_node_free, NULL);
g_list_free (job->source_node_list);
thunar_g_file_list_free (job->target_file_list);
(*G_OBJECT_CLASS (thunar_transfer_job_parent_class)->finalize) (object);
}
static void
thunar_transfer_job_progress (goffset current_num_bytes,
goffset total_num_bytes,
gpointer user_data)
{
guint64 new_percentage;
ThunarTransferJob *job = user_data;
_thunar_return_if_fail (THUNAR_IS_TRANSFER_JOB (job));
if (G_LIKELY (job->total_size > 0))
{
/* update total progress */
job->total_progress += (current_num_bytes - job->file_progress);
/* update file progress */
job->file_progress = current_num_bytes;
/* compute the new percentage after the progress we've made */
new_percentage = (job->total_progress * 100.0) / job->total_size;
/* notify callers about the progress only if we have advanced by
* at least 0.01 percent since the last signal emission */
if (new_percentage >= (job->previous_percentage + 0.01))
{
/* emit the percent signal */
exo_job_percent (EXO_JOB (job), new_percentage);
/* remember the percentage */
job->previous_percentage = new_percentage;
}
}
}
static gboolean
thunar_transfer_job_collect_node (ThunarTransferJob *job,
ThunarTransferNode *node,
GError **error)
{
ThunarTransferNode *child_node;
GFileInfo *info;
GError *err = NULL;
GList *file_list;
GList *lp;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), FALSE);
_thunar_return_val_if_fail (node != NULL && G_IS_FILE (node->source_file), FALSE);
_thunar_return_val_if_fail (error == NULL || *error == NULL, FALSE);
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
info = g_file_query_info (node->source_file,
G_FILE_ATTRIBUTE_STANDARD_SIZE ","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
if (G_UNLIKELY (info == NULL))
return FALSE;
job->total_size += g_file_info_get_size (info);
/* check if we have a directory here */
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
/* scan the directory for immediate children */
file_list = thunar_io_scan_directory (THUNAR_JOB (job), node->source_file,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
FALSE, FALSE, &err);
/* add children to the transfer node */
for (lp = file_list; err == NULL && lp != NULL; lp = lp->next)
{
/* allocate a new transfer node for the child */
child_node = g_slice_new0 (ThunarTransferNode);
child_node->source_file = g_object_ref (lp->data);
/* hook the child node into the child list */
child_node->next = node->children;
node->children = child_node;
/* collect the child node */
thunar_transfer_job_collect_node (job, child_node, &err);
}
/* release the child files */
thunar_g_file_list_free (file_list);
}
/* release file info */
g_object_unref (info);
if (G_UNLIKELY (err != NULL))
{
g_propagate_error (error, err);
return FALSE;
}
return TRUE;
}
static gboolean
ttj_copy_file (ThunarTransferJob *job,
GFile *source_file,
GFile *target_file,
GFileCopyFlags copy_flags,
gboolean merge_directories,
GError **error)
{
GFileType source_type;
GFileType target_type;
gboolean target_exists;
GError *err = NULL;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), FALSE);
_thunar_return_val_if_fail (G_IS_FILE (source_file), FALSE);
_thunar_return_val_if_fail (G_IS_FILE (target_file), FALSE);
_thunar_return_val_if_fail (error == NULL || *error == NULL, FALSE);
/* reset the file progress */
job->file_progress = 0;
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
source_type = g_file_query_file_type (source_file, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)));
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
target_type = g_file_query_file_type (target_file, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)));
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
/* check if the target is a symlink and we are in overwrite mode */
if (target_type == G_FILE_TYPE_SYMBOLIC_LINK && (copy_flags & G_FILE_COPY_OVERWRITE) != 0)
{
/* try to delete the symlink */
if (!g_file_delete (target_file, exo_job_get_cancellable (EXO_JOB (job)), &err))
{
g_propagate_error (error, err);
return FALSE;
}
}
/* try to copy the file */
g_file_copy (source_file, target_file, copy_flags,
exo_job_get_cancellable (EXO_JOB (job)),
thunar_transfer_job_progress, job, &err);
/* check if there were errors */
if (G_UNLIKELY (err != NULL && err->domain == G_IO_ERROR))
{
if (err->code == G_IO_ERROR_WOULD_MERGE
|| (err->code == G_IO_ERROR_EXISTS
&& source_type == G_FILE_TYPE_DIRECTORY
&& target_type == G_FILE_TYPE_DIRECTORY))
{
/* we tried to overwrite a directory with a directory. this normally results
* in a merge. ignore the error if we actually *want* to merge */
if (merge_directories)
g_clear_error (&err);
}
else if (err->code == G_IO_ERROR_WOULD_RECURSE)
{
g_clear_error (&err);
/* we tried to copy a directory and either
*
* - the target did not exist which means we simple have to
* create the target directory
*
* or
*
* - the target is not a directory and we tried to overwrite it in
* which case we have to delete it first and then create the target
* directory
*/
/* check if the target file exists */
target_exists = g_file_query_exists (target_file,
exo_job_get_cancellable (EXO_JOB (job)));
/* abort on cancellation, continue otherwise */
if (!exo_job_set_error_if_cancelled (EXO_JOB (job), &err))
{
if (target_exists)
{
/* the target still exists and thus is not a directory. try to remove it */
g_file_delete (target_file,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
}
/* abort on error or cancellation, continue otherwise */
if (err == NULL)
{
/* now try to create the directory */
g_file_make_directory (target_file,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
}
}
}
}
if (G_UNLIKELY (err != NULL))
{
g_propagate_error (error, err);
return FALSE;
}
else
{
return TRUE;
}
}
/**
* thunar_transfer_job_copy_file:
* @job : a #ThunarTransferJob.
* @source_file : the source #GFile to copy.
* @target_file : the destination #GFile to copy to.
* @error : return location for errors or %NULL.
*
* Tries to copy @source_file to @target_file. The real destination is the
* return value and may differ from @target_file (e.g. if you try to copy
* the file "/foo/bar" into the same directory you'll end up with something
* like "/foo/copy of bar" instead of "/foo/bar".
*
* The return value is guaranteed to be %NULL on errors and @error will
* always be set in those cases. If the file is skipped, the return value
* will be @source_file.
*
* Return value: the destination #GFile to which @source_file was copied
* or linked. The caller is reposible to release it with
* g_object_unref() if no longer needed. It points to
* @source_file if the file was skipped and will be %NULL
* on error or cancellation.
**/
static GFile *
thunar_transfer_job_copy_file (ThunarTransferJob *job,
GFile *source_file,
GFile *target_file,
GError **error)
{
ThunarJobResponse response;
GFileCopyFlags copy_flags = G_FILE_COPY_NOFOLLOW_SYMLINKS;
GError *err = NULL;
gint n;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), NULL);
_thunar_return_val_if_fail (G_IS_FILE (source_file), NULL);
_thunar_return_val_if_fail (G_IS_FILE (target_file), NULL);
_thunar_return_val_if_fail (error == NULL || *error == NULL, NULL);
/* abort on cancellation */
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return NULL;
/* various attempts to copy the file */
while (err == NULL)
{
if (G_LIKELY (!g_file_equal (source_file, target_file)))
{
/* try to copy the file from source_file to the target_file */
if (ttj_copy_file (job, source_file, target_file, copy_flags, TRUE, &err))
{
/* return the real target file */
return g_object_ref (target_file);
}
}
else
{
for (n = 1; err == NULL; ++n)
{
GFile *duplicate_file = thunar_io_jobs_util_next_duplicate_file (THUNAR_JOB (job),
source_file,
TRUE, n,
&err);
if (err == NULL)
{
/* try to copy the file from source file to the duplicate file */
if (ttj_copy_file (job, source_file, duplicate_file, copy_flags, TRUE, &err))
{
/* return the real target file */
return duplicate_file;
}
g_object_unref (duplicate_file);
}
if (err != NULL && err->domain == G_IO_ERROR && err->code == G_IO_ERROR_EXISTS)
{
/* this duplicate already exists => clear the error to try the next alternative */
g_clear_error (&err);
}
}
}
/* check if we can recover from this error */
if (err->domain == G_IO_ERROR && err->code == G_IO_ERROR_EXISTS)
{
/* reset the error */
g_clear_error (&err);
/* ask the user whether to replace the target file */
response = thunar_job_ask_replace (THUNAR_JOB (job), source_file,
target_file, &err);
if (err != NULL)
break;
/* check if we should retry */
if (response == THUNAR_JOB_RESPONSE_RETRY)
continue;
/* add overwrite flag and retry if we should overwrite */
if (response == THUNAR_JOB_RESPONSE_YES)
{
copy_flags |= G_FILE_COPY_OVERWRITE;
continue;
}
/* tell the caller we skipped the file if the user
* doesn't want to retry/overwrite */
if (response == THUNAR_JOB_RESPONSE_NO)
return g_object_ref (source_file);
}
}
_thunar_assert (err != NULL);
g_propagate_error (error, err);
return NULL;
}
static void
thunar_transfer_job_copy_node (ThunarTransferJob *job,
ThunarTransferNode *node,
GFile *target_file,
GFile *target_parent_file,
GList **target_file_list_return,
GError **error)
{
ThunarThumbnailCache *thumbnail_cache;
ThunarApplication *application;
ThunarJobResponse response;
GFileInfo *info;
GError *err = NULL;
GFile *real_target_file = NULL;
gchar *base_name;
_thunar_return_if_fail (THUNAR_IS_TRANSFER_JOB (job));
_thunar_return_if_fail (node != NULL && G_IS_FILE (node->source_file));
_thunar_return_if_fail (target_file == NULL || node->next == NULL);
_thunar_return_if_fail ((target_file == NULL && target_parent_file != NULL) || (target_file != NULL && target_parent_file == NULL));
_thunar_return_if_fail (error == NULL || *error == NULL);
/* The caller can either provide a target_file or a target_parent_file, but not both. The toplevel
* transfer_nodes (for which next is NULL) should be called with target_file, to get proper behavior
* wrt restoring files from the trash. Other transfer_nodes will be called with target_parent_file.
*/
/* take a reference on the thumbnail cache */
application = thunar_application_get ();
thumbnail_cache = thunar_application_get_thumbnail_cache (application);
g_object_unref (application);
for (; err == NULL && node != NULL; node = node->next)
{
/* guess the target file for this node (unless already provided) */
if (G_LIKELY (target_file == NULL))
{
base_name = g_file_get_basename (node->source_file);
target_file = g_file_get_child (target_parent_file, base_name);
g_free (base_name);
}
else
target_file = g_object_ref (target_file);
/* query file info */
info = g_file_query_info (node->source_file,
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
/* abort on error or cancellation */
if (info == NULL)
{
g_object_unref (target_file);
break;
}
/* update progress information */
exo_job_info_message (EXO_JOB (job), "%s", g_file_info_get_display_name (info));
retry_copy:
/* copy the item specified by this node (not recursively) */
real_target_file = thunar_transfer_job_copy_file (job, node->source_file,
target_file, &err);
if (G_LIKELY (real_target_file != NULL))
{
/* node->source_file == real_target_file means to skip the file */
if (G_LIKELY (node->source_file != real_target_file))
{
/* notify the thumbnail cache of the copy operation */
thunar_thumbnail_cache_copy_file (thumbnail_cache,
node->source_file,
real_target_file);
/* check if we have children to copy */
if (node->children != NULL)
{
/* copy all children of this node */
thunar_transfer_job_copy_node (job, node->children, NULL, real_target_file, NULL, &err);
/* free resources allocted for the children */
thunar_transfer_node_free (node->children);
node->children = NULL;
}
/* check if the child copy failed */
if (G_UNLIKELY (err != NULL))
{
/* outa here, freeing the target paths */
g_object_unref (real_target_file);
g_object_unref (target_file);
break;
}
/* add the real target file to the return list */
if (G_LIKELY (target_file_list_return != NULL))
{
*target_file_list_return =
thunar_g_file_list_prepend (*target_file_list_return,
real_target_file);
}
retry_remove:
/* try to remove the source directory if we are on copy+remove fallback for move */
if (job->type == THUNAR_TRANSFER_JOB_MOVE)
{
if (g_file_delete (node->source_file,
exo_job_get_cancellable (EXO_JOB (job)),
&err))
{
/* notify the thumbnail cache of the delete operation */
thunar_thumbnail_cache_delete_file (thumbnail_cache,
node->source_file);
}
else
{
/* ask the user to retry */
response = thunar_job_ask_skip (THUNAR_JOB (job), "%s",
err->message);
/* reset the error */
g_clear_error (&err);
/* check whether to retry */
if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY))
goto retry_remove;
}
}
}
g_object_unref (real_target_file);
}
else if (err != NULL)
{
/* we can only skip if there is space left on the device */
if (err->domain != G_IO_ERROR || err->code != G_IO_ERROR_NO_SPACE)
{
/* ask the user to skip this node and all subnodes */
response = thunar_job_ask_skip (THUNAR_JOB (job), "%s", err->message);
/* reset the error */
g_clear_error (&err);
/* check whether to retry */
if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY))
goto retry_copy;
}
}
/* release the guessed target file */
g_object_unref (target_file);
target_file = NULL;
/* release file info */
g_object_unref (info);
}
/* release the thumbnail cache */
g_object_unref (thumbnail_cache);
/* propagate error if we failed or the job was cancelled */
if (G_UNLIKELY (err != NULL))
g_propagate_error (error, err);
}
static gboolean
thunar_transfer_job_execute (ExoJob *job,
GError **error)
{
ThunarThumbnailCache *thumbnail_cache;
ThunarTransferNode *node;
ThunarApplication *application;
ThunarJobResponse response;
ThunarTransferJob *transfer_job = THUNAR_TRANSFER_JOB (job);
GFileInfo *info;
gboolean parent_exists;
GError *err = NULL;
GList *new_files_list = NULL;
GList *snext;
GList *sp;
GList *tnext;
GList *tp;
GFile *target_parent;
gchar *base_name;
gchar *parent_display_name;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), FALSE);
_thunar_return_val_if_fail (error == NULL || *error == NULL, FALSE);
if (exo_job_set_error_if_cancelled (job, error))
return FALSE;
exo_job_info_message (job, _("Collecting files..."));
/* take a reference on the thumbnail cache */
application = thunar_application_get ();
thumbnail_cache = thunar_application_get_thumbnail_cache (application);
g_object_unref (application);
for (sp = transfer_job->source_node_list, tp = transfer_job->target_file_list;
sp != NULL && tp != NULL && err == NULL;
sp = snext, tp = tnext)
{
/* determine the next list items */
snext = sp->next;
tnext = tp->next;
/* determine the current source transfer node */
node = sp->data;
info = g_file_query_info (node->source_file,
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (job),
&err);
if (G_UNLIKELY (info == NULL))
break;
/* check if we are moving a file out of the trash */
if (transfer_job->type == THUNAR_TRANSFER_JOB_MOVE
&& thunar_g_file_is_trashed (node->source_file))
{
/* update progress information */
exo_job_info_message (job, _("Trying to restore \"%s\""),
g_file_info_get_display_name (info));
/* determine the parent file */
target_parent = g_file_get_parent (tp->data);
/* check if the parent exists */
if (target_parent != NULL)
parent_exists = g_file_query_exists (target_parent, exo_job_get_cancellable (job));
/* abort on cancellation */
if (exo_job_set_error_if_cancelled (job, &err))
{
g_object_unref (target_parent);
break;
}
if (target_parent != NULL && !parent_exists)
{
/* determine the display name of the parent */
base_name = g_file_get_basename (target_parent);
parent_display_name = g_filename_display_name (base_name);
g_free (base_name);
/* ask the user whether he wants to create the parent folder because its gone */
response = thunar_job_ask_create (THUNAR_JOB (job),
_("The folder \"%s\" does not exist anymore but is "
"required to restore the file \"%s\" from the "
"trash"),
parent_display_name,
g_file_info_get_display_name (info));
/* abort if cancelled */
if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_CANCEL))
{
g_object_unref (target_parent);
g_free (parent_display_name);
break;
}
/* try to create the parent directory */
if (!g_file_make_directory_with_parents (target_parent,
exo_job_get_cancellable (job),
&err))
{
if (!exo_job_is_cancelled (job))
{
g_clear_error (&err);
/* overwrite the internal GIO error with something more user-friendly */
g_set_error (&err, G_IO_ERROR, G_IO_ERROR_FAILED,
_("Failed to restore the folder \"%s\""),
parent_display_name);
}
g_object_unref (target_parent);
g_free (parent_display_name);
break;
}
/* clean up */
g_free (parent_display_name);
}
if (target_parent != NULL)
g_object_unref (target_parent);
}
if (transfer_job->type == THUNAR_TRANSFER_JOB_MOVE)
{
/* update progress information */
exo_job_info_message (job, _("Trying to move \"%s\""),
g_file_info_get_display_name (info));
if (g_file_move (node->source_file, tp->data,
G_FILE_COPY_NOFOLLOW_SYMLINKS
| G_FILE_COPY_NO_FALLBACK_FOR_MOVE,
exo_job_get_cancellable (job),
NULL, NULL, &err))
{
/* notify the thumbnail cache of the move operation */
thunar_thumbnail_cache_move_file (thumbnail_cache,
node->source_file,
tp->data);
/* add the target file to the new files list */
new_files_list = thunar_g_file_list_prepend (new_files_list, tp->data);
/* release source and target files */
thunar_transfer_node_free (node);
g_object_unref (tp->data);
/* drop the matching list items */
transfer_job->source_node_list = g_list_delete_link (transfer_job->source_node_list, sp);
transfer_job->target_file_list = g_list_delete_link (transfer_job->target_file_list, tp);
}
else if (!exo_job_is_cancelled (job))
{
g_clear_error (&err);
/* update progress information */
exo_job_info_message (job, _("Could not move \"%s\" directly. "
"Collecting files for copying..."),
g_file_info_get_display_name (info));
if (!thunar_transfer_job_collect_node (transfer_job, node, &err))
{
/* failed to collect, cannot continue */
g_object_unref (info);
break;
}
}
}
else if (transfer_job->type == THUNAR_TRANSFER_JOB_COPY)
{
if (!thunar_transfer_job_collect_node (THUNAR_TRANSFER_JOB (job), node, &err))
break;
}
g_object_unref (info);
}
/* release the thumbnail cache */
g_object_unref (thumbnail_cache);
/* continue if there were no errors yet */
if (G_LIKELY (err == NULL))
{
/* perform the copy recursively for all source transfer nodes */
for (sp = transfer_job->source_node_list, tp = transfer_job->target_file_list;
sp != NULL && tp != NULL && err == NULL;
sp = sp->next, tp = tp->next)
{
thunar_transfer_job_copy_node (transfer_job, sp->data, tp->data, NULL,
&new_files_list, &err);
}
}
/* check if we failed */
if (G_UNLIKELY (err != NULL))
{
g_propagate_error (error, err);
return FALSE;
}
else
{
thunar_job_new_files (THUNAR_JOB (job), new_files_list);
thunar_g_file_list_free (new_files_list);
return TRUE;
}
}
static void
thunar_transfer_node_free (ThunarTransferNode *node)
{
ThunarTransferNode *next;
/* free all nodes in a row */
while (node != NULL)
{
/* free all children of this node */
thunar_transfer_node_free (node->children);
/* determine the next node */
next = node->next;
/* drop the source file of this node */
g_object_unref (node->source_file);
/* release the resources of this node */
g_slice_free (ThunarTransferNode, node);
/* continue with the next node */
node = next;
}
}
ThunarJob *
thunar_transfer_job_new (GList *source_node_list,
GList *target_file_list,
ThunarTransferJobType type)
{
ThunarTransferNode *node;
ThunarTransferJob *job;
GList *sp;
GList *tp;
_thunar_return_val_if_fail (source_node_list != NULL, NULL);
_thunar_return_val_if_fail (target_file_list != NULL, NULL);
_thunar_return_val_if_fail (g_list_length (source_node_list) == g_list_length (target_file_list), NULL);
job = g_object_new (THUNAR_TYPE_TRANSFER_JOB, NULL);
job->type = type;
/* add a transfer node for each source path and a matching target parent path */
for (sp = source_node_list, tp = target_file_list;
sp != NULL;
sp = sp->next, tp = tp->next)
{
/* make sure we don't transfer root directories. this should be prevented in the GUI */
if (G_UNLIKELY (thunar_g_file_is_root (sp->data) || thunar_g_file_is_root (tp->data)))
continue;
/* only process non-equal pairs unless we're copying */
if (G_LIKELY (type != THUNAR_TRANSFER_JOB_MOVE || !g_file_equal (sp->data, tp->data)))
{
/* append transfer node for this source file */
node = g_slice_new0 (ThunarTransferNode);
node->source_file = g_object_ref (sp->data);
job->source_node_list = g_list_append (job->source_node_list, node);
/* append target file */
job->target_file_list = thunar_g_file_list_append (job->target_file_list, tp->data);
}
}
/* make sure we didn't mess things up */
_thunar_assert (g_list_length (job->source_node_list) == g_list_length (job->target_file_list));
return THUNAR_JOB (job);
}
| ./CrossVul/dataset_final_sorted/CWE-134/c/good_3455_0 |
crossvul-cpp_data_good_2610_1 | /* omzmq3.c
* Copyright 2012 Talksum, Inc
* Using the czmq interface to zeromq, we output
* to a zmq socket.
* Copyright (C) 2014 Rainer Gerhards
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* Author: David Kelly
* <davidk@talksum.com>
*/
#include "config.h"
#include "rsyslog.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include "conf.h"
#include "syslogd-types.h"
#include "srUtils.h"
#include "template.h"
#include "module-template.h"
#include "errmsg.h"
#include "cfsysline.h"
#include <czmq.h>
MODULE_TYPE_OUTPUT
MODULE_TYPE_NOKEEP
MODULE_CNFNAME("omzmq3")
DEF_OMOD_STATIC_DATA
DEFobjCurrIf(errmsg)
static pthread_mutex_t mutDoAct = PTHREAD_MUTEX_INITIALIZER;
/* convienent symbols to denote a socket we want to bind
vs one we want to just connect to
*/
#define ACTION_CONNECT 1
#define ACTION_BIND 2
/* ----------------------------------------------------------------------------
* structs to describe sockets
*/
struct socket_type {
char* name;
int type;
};
/* more overkill, but seems nice to be consistent. */
struct socket_action {
char* name;
int action;
};
typedef struct _instanceData {
void* socket;
uchar* description;
int type;
int action;
int sndHWM;
int rcvHWM;
uchar* identity;
int sndBuf;
int rcvBuf;
int linger;
int backlog;
int sndTimeout;
int rcvTimeout;
int maxMsgSize;
int rate;
int recoveryIVL;
int multicastHops;
int reconnectIVL;
int reconnectIVLMax;
int ipv4Only;
int affinity;
uchar* tplName;
} instanceData;
typedef struct wrkrInstanceData {
instanceData *pData;
} wrkrInstanceData_t;
/* ----------------------------------------------------------------------------
* Static definitions/initializations
*/
/* only 1 zctx for all the sockets, with an adjustable number of
worker threads which may be useful if we use affinity in particular
sockets
*/
static zctx_t* s_context = NULL;
static int s_workerThreads = -1;
static struct socket_type types[] = {
{"PUB", ZMQ_PUB },
{"PUSH", ZMQ_PUSH },
{"DEALER", ZMQ_DEALER },
{"XPUB", ZMQ_XPUB }
};
static struct socket_action actions[] = {
{"BIND", ACTION_BIND},
{"CONNECT", ACTION_CONNECT},
};
static struct cnfparamdescr actpdescr[] = {
{ "description", eCmdHdlrGetWord, 0 },
{ "sockType", eCmdHdlrGetWord, 0 },
{ "action", eCmdHdlrGetWord, 0 },
{ "sndHWM", eCmdHdlrInt, 0 },
{ "rcvHWM", eCmdHdlrInt, 0 },
{ "identity", eCmdHdlrGetWord, 0 },
{ "sndBuf", eCmdHdlrInt, 0 },
{ "rcvBuf", eCmdHdlrInt, 0 },
{ "linger", eCmdHdlrInt, 0 },
{ "backlog", eCmdHdlrInt, 0 },
{ "sndTimeout", eCmdHdlrInt, 0 },
{ "rcvTimeout", eCmdHdlrInt, 0 },
{ "maxMsgSize", eCmdHdlrInt, 0 },
{ "rate", eCmdHdlrInt, 0 },
{ "recoveryIVL", eCmdHdlrInt, 0 },
{ "multicastHops", eCmdHdlrInt, 0 },
{ "reconnectIVL", eCmdHdlrInt, 0 },
{ "reconnectIVLMax", eCmdHdlrInt, 0 },
{ "ipv4Only", eCmdHdlrInt, 0 },
{ "affinity", eCmdHdlrInt, 0 },
{ "globalWorkerThreads", eCmdHdlrInt, 0 },
{ "template", eCmdHdlrGetWord, 1 }
};
static struct cnfparamblk actpblk = {
CNFPARAMBLK_VERSION,
sizeof(actpdescr)/sizeof(struct cnfparamdescr),
actpdescr
};
/* ----------------------------------------------------------------------------
* Helper Functions
*/
/* get the name of a socket type, return the ZMQ_XXX type
or -1 if not a supported type (see above)
*/
int getSocketType(char* name) {
int type = -1;
uint i;
for(i=0; i<sizeof(types)/sizeof(struct socket_type); ++i) {
if( !strcmp(types[i].name, name) ) {
type = types[i].type;
break;
}
}
return type;
}
static int getSocketAction(char* name) {
int action = -1;
uint i;
for(i=0; i < sizeof(actions)/sizeof(struct socket_action); ++i) {
if(!strcmp(actions[i].name, name)) {
action = actions[i].action;
break;
}
}
return action;
}
/* closeZMQ will destroy the context and
* associated socket
*/
static void closeZMQ(instanceData* pData) {
errmsg.LogError(0, NO_ERRCODE, "closeZMQ called");
if(s_context && pData->socket) {
if(pData->socket != NULL) {
zsocket_destroy(s_context, pData->socket);
}
}
}
static rsRetVal initZMQ(instanceData* pData) {
DEFiRet;
/* create the context if necessary. */
if (NULL == s_context) {
zsys_handler_set(NULL);
s_context = zctx_new();
if (s_workerThreads > 0) zctx_set_iothreads(s_context, s_workerThreads);
}
pData->socket = zsocket_new(s_context, pData->type);
if (NULL == pData->socket) {
errmsg.LogError(0, RS_RET_NO_ERRCODE,
"omzmq3: zsocket_new failed for %s: %s",
pData->description, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
/* use czmq defaults for these, unless set to non-default values */
if(pData->identity) zsocket_set_identity(pData->socket, (char*)pData->identity);
if(pData->sndBuf > -1) zsocket_set_sndbuf(pData->socket, pData->sndBuf);
if(pData->rcvBuf > -1) zsocket_set_sndbuf(pData->socket, pData->rcvBuf);
if(pData->linger > -1) zsocket_set_linger(pData->socket, pData->linger);
if(pData->backlog > -1) zsocket_set_backlog(pData->socket, pData->backlog);
if(pData->sndTimeout > -1) zsocket_set_sndtimeo(pData->socket, pData->sndTimeout);
if(pData->rcvTimeout > -1) zsocket_set_rcvtimeo(pData->socket, pData->rcvTimeout);
if(pData->maxMsgSize > -1) zsocket_set_maxmsgsize(pData->socket, pData->maxMsgSize);
if(pData->rate > -1) zsocket_set_rate(pData->socket, pData->rate);
if(pData->recoveryIVL > -1) zsocket_set_recovery_ivl(pData->socket, pData->recoveryIVL);
if(pData->multicastHops > -1) zsocket_set_multicast_hops(pData->socket, pData->multicastHops);
if(pData->reconnectIVL > -1) zsocket_set_reconnect_ivl(pData->socket, pData->reconnectIVL);
if(pData->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(pData->socket, pData->reconnectIVLMax);
if(pData->ipv4Only > -1) zsocket_set_ipv4only(pData->socket, pData->ipv4Only);
if(pData->affinity != 1) zsocket_set_affinity(pData->socket, pData->affinity);
if(pData->rcvHWM > -1) zsocket_set_rcvhwm(pData->socket, pData->rcvHWM);
if(pData->sndHWM > -1) zsocket_set_sndhwm(pData->socket, pData->sndHWM);
/* bind or connect to it */
if (pData->action == ACTION_BIND) {
/* bind asserts, so no need to test return val here
which isn't the greatest api -- oh well */
if(-1 == zsocket_bind(pData->socket, "%s", (char*)pData->description)) {
errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: bind failed for %s: %s",
pData->description, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
DBGPRINTF("omzmq3: bind to %s successful\n",pData->description);
} else {
if(-1 == zsocket_connect(pData->socket, "%s", (char*)pData->description)) {
errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: connect failed for %s: %s",
pData->description, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
DBGPRINTF("omzmq3: connect to %s successful", pData->description);
}
finalize_it:
RETiRet;
}
rsRetVal writeZMQ(uchar* msg, instanceData* pData) {
DEFiRet;
/* initialize if necessary */
if(NULL == pData->socket)
CHKiRet(initZMQ(pData));
/* send it */
int result = zstr_send(pData->socket, (char*)msg);
/* whine if things went wrong */
if (result == -1) {
errmsg.LogError(0, NO_ERRCODE, "omzmq3: send of %s failed: %s", msg, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_ERR);
}
finalize_it:
RETiRet;
}
static void
setInstParamDefaults(instanceData* pData) {
pData->description = NULL;
pData->socket = NULL;
pData->tplName = NULL;
pData->type = ZMQ_PUB;
pData->action = ACTION_BIND;
pData->sndHWM = -1;
pData->rcvHWM = -1;
pData->identity = NULL;
pData->sndBuf = -1;
pData->rcvBuf = -1;
pData->linger = -1;
pData->backlog = -1;
pData->sndTimeout = -1;
pData->rcvTimeout = -1;
pData->maxMsgSize = -1;
pData->rate = -1;
pData->recoveryIVL = -1;
pData->multicastHops = -1;
pData->reconnectIVL = -1;
pData->reconnectIVLMax = -1;
pData->ipv4Only = -1;
pData->affinity = 1;
}
/* ----------------------------------------------------------------------------
* Output Module Functions
*/
BEGINcreateInstance
CODESTARTcreateInstance
ENDcreateInstance
BEGINcreateWrkrInstance
CODESTARTcreateWrkrInstance
ENDcreateWrkrInstance
BEGINisCompatibleWithFeature
CODESTARTisCompatibleWithFeature
if(eFeat == sFEATURERepeatedMsgReduction)
iRet = RS_RET_OK;
ENDisCompatibleWithFeature
BEGINdbgPrintInstInfo
CODESTARTdbgPrintInstInfo
ENDdbgPrintInstInfo
BEGINfreeInstance
CODESTARTfreeInstance
closeZMQ(pData);
free(pData->description);
free(pData->tplName);
free(pData->identity);
ENDfreeInstance
BEGINfreeWrkrInstance
CODESTARTfreeWrkrInstance
ENDfreeWrkrInstance
BEGINtryResume
CODESTARTtryResume
pthread_mutex_lock(&mutDoAct);
if(NULL == pWrkrData->pData->socket)
iRet = initZMQ(pWrkrData->pData);
pthread_mutex_unlock(&mutDoAct);
ENDtryResume
BEGINdoAction
instanceData *pData = pWrkrData->pData;
CODESTARTdoAction
pthread_mutex_lock(&mutDoAct);
iRet = writeZMQ(ppString[0], pData);
pthread_mutex_unlock(&mutDoAct);
ENDdoAction
BEGINnewActInst
struct cnfparamvals *pvals;
int i;
CODESTARTnewActInst
if ((pvals = nvlstGetParams(lst, &actpblk, NULL)) == NULL) {
ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
}
CHKiRet(createInstance(&pData));
setInstParamDefaults(pData);
CODE_STD_STRING_REQUESTnewActInst(1)
for (i = 0; i < actpblk.nParams; ++i) {
if (!pvals[i].bUsed)
continue;
if (!strcmp(actpblk.descr[i].name, "description")) {
pData->description = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if (!strcmp(actpblk.descr[i].name, "template")) {
pData->tplName = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if (!strcmp(actpblk.descr[i].name, "sockType")){
pData->type = getSocketType(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if (!strcmp(actpblk.descr[i].name, "action")){
pData->action = getSocketAction(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if (!strcmp(actpblk.descr[i].name, "sndHWM")) {
pData->sndHWM = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rcvHWM")) {
pData->rcvHWM = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "identity")){
pData->identity = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if (!strcmp(actpblk.descr[i].name, "sndBuf")) {
pData->sndBuf = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rcvBuf")) {
pData->rcvBuf = (int) pvals[i].val.d.n;
} else if(!strcmp(actpblk.descr[i].name, "linger")) {
pData->linger = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "backlog")) {
pData->backlog = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "sndTimeout")) {
pData->sndTimeout = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rcvTimeout")) {
pData->rcvTimeout = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "maxMsgSize")) {
pData->maxMsgSize = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rate")) {
pData->rate = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "recoveryIVL")) {
pData->recoveryIVL = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "multicastHops")) {
pData->multicastHops = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "reconnectIVL")) {
pData->reconnectIVL = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "reconnectIVLMax")) {
pData->reconnectIVLMax = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "ipv4Only")) {
pData->ipv4Only = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "affinity")) {
pData->affinity = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "globalWorkerThreads")) {
s_workerThreads = (int) pvals[i].val.d.n;
} else {
errmsg.LogError(0, NO_ERRCODE, "omzmq3: program error, non-handled "
"param '%s'\n", actpblk.descr[i].name);
}
}
if (pData->tplName == NULL) {
CHKiRet(OMSRsetEntry(*ppOMSR, 0, (uchar*)strdup("RSYSLOG_ForwardFormat"), OMSR_NO_RQD_TPL_OPTS));
} else {
CHKiRet(OMSRsetEntry(*ppOMSR, 0, (uchar*)pData->tplName, OMSR_NO_RQD_TPL_OPTS));
}
if (NULL == pData->description) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR, "omzmq3: you didn't enter a description");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
if (pData->type == -1) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR, "omzmq3: unknown socket type.");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
if (pData->action == -1) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR, "omzmq3: unknown socket action");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
CODE_STD_FINALIZERnewActInst
cnfparamvalsDestruct(pvals, &actpblk);
ENDnewActInst
BEGINparseSelectorAct
CODESTARTparseSelectorAct
/* tell the engine we only want one template string */
CODE_STD_STRING_REQUESTparseSelectorAct(1)
if(!strncmp((char*) p, ":omzmq3:", sizeof(":omzmq3:") - 1))
errmsg.LogError(0, RS_RET_LEGA_ACT_NOT_SUPPORTED,
"omzmq3 supports only v6 config format, use: "
"action(type=\"omzmq3\" serverport=...)");
ABORT_FINALIZE(RS_RET_CONFLINE_UNPROCESSED);
CODE_STD_FINALIZERparseSelectorAct
ENDparseSelectorAct
BEGINinitConfVars /* (re)set config variables to defaults */
CODESTARTinitConfVars
s_workerThreads = -1;
ENDinitConfVars
BEGINmodExit
CODESTARTmodExit
if (NULL != s_context) {
zctx_destroy(&s_context);
s_context=NULL;
}
ENDmodExit
BEGINqueryEtryPt
CODESTARTqueryEtryPt
CODEqueryEtryPt_STD_OMOD_QUERIES
CODEqueryEtryPt_STD_CONF2_OMOD_QUERIES
CODEqueryEtryPt_STD_OMOD8_QUERIES
ENDqueryEtryPt
BEGINmodInit()
CODESTARTmodInit
*ipIFVersProvided = CURR_MOD_IF_VERSION; /* only supports rsyslog 6 configs */
CODEmodInit_QueryRegCFSLineHdlr
CHKiRet(objUse(errmsg, CORE_COMPONENT));
INITChkCoreFeature(bCoreSupportsBatching, CORE_FEATURE_BATCHING);
DBGPRINTF("omzmq3: module compiled with rsyslog version %s.\n", VERSION);
INITLegCnfVars
CHKiRet(omsdRegCFSLineHdlr((uchar *)"omzmq3workerthreads", 0, eCmdHdlrInt, NULL, &s_workerThreads,
STD_LOADABLE_MODULE_ID));
ENDmodInit
| ./CrossVul/dataset_final_sorted/CWE-134/c/good_2610_1 |
crossvul-cpp_data_bad_1792_0 | /*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) 1998-2015 Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@zend.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
| Dmitry Stogov <dmitry@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include <signal.h>
#include "zend.h"
#include "zend_compile.h"
#include "zend_execute.h"
#include "zend_API.h"
#include "zend_stack.h"
#include "zend_constants.h"
#include "zend_extensions.h"
#include "zend_exceptions.h"
#include "zend_closures.h"
#include "zend_generators.h"
#include "zend_vm.h"
#include "zend_float.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
ZEND_API void (*zend_execute_ex)(zend_execute_data *execute_data);
ZEND_API void (*zend_execute_internal)(zend_execute_data *execute_data, zval *return_value);
/* true globals */
ZEND_API const zend_fcall_info empty_fcall_info = { 0, NULL, {{0}, {{0}}, {0}}, NULL, NULL, NULL, NULL, 0, 0 };
ZEND_API const zend_fcall_info_cache empty_fcall_info_cache = { 0, NULL, NULL, NULL, NULL };
#ifdef ZEND_WIN32
ZEND_TLS HANDLE tq_timer = NULL;
#endif
#if 0&&ZEND_DEBUG
static void (*original_sigsegv_handler)(int);
static void zend_handle_sigsegv(int dummy) /* {{{ */
{
fflush(stdout);
fflush(stderr);
if (original_sigsegv_handler == zend_handle_sigsegv) {
signal(SIGSEGV, original_sigsegv_handler);
} else {
signal(SIGSEGV, SIG_DFL);
}
{
fprintf(stderr, "SIGSEGV caught on opcode %d on opline %d of %s() at %s:%d\n\n",
active_opline->opcode,
active_opline-EG(active_op_array)->opcodes,
get_active_function_name(),
zend_get_executed_filename(),
zend_get_executed_lineno());
/* See http://support.microsoft.com/kb/190351 */
#ifdef ZEND_WIN32
fflush(stderr);
#endif
}
if (original_sigsegv_handler!=zend_handle_sigsegv) {
original_sigsegv_handler(dummy);
}
}
/* }}} */
#endif
static void zend_extension_activator(zend_extension *extension) /* {{{ */
{
if (extension->activate) {
extension->activate();
}
}
/* }}} */
static void zend_extension_deactivator(zend_extension *extension) /* {{{ */
{
if (extension->deactivate) {
extension->deactivate();
}
}
/* }}} */
static int clean_non_persistent_function(zval *zv) /* {{{ */
{
zend_function *function = Z_PTR_P(zv);
return (function->type == ZEND_INTERNAL_FUNCTION) ? ZEND_HASH_APPLY_STOP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
ZEND_API int clean_non_persistent_function_full(zval *zv) /* {{{ */
{
zend_function *function = Z_PTR_P(zv);
return (function->type == ZEND_INTERNAL_FUNCTION) ? ZEND_HASH_APPLY_KEEP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
static int clean_non_persistent_class(zval *zv) /* {{{ */
{
zend_class_entry *ce = Z_PTR_P(zv);
return (ce->type == ZEND_INTERNAL_CLASS) ? ZEND_HASH_APPLY_STOP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
ZEND_API int clean_non_persistent_class_full(zval *zv) /* {{{ */
{
zend_class_entry *ce = Z_PTR_P(zv);
return (ce->type == ZEND_INTERNAL_CLASS) ? ZEND_HASH_APPLY_KEEP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
void init_executor(void) /* {{{ */
{
zend_init_fpu();
ZVAL_NULL(&EG(uninitialized_zval));
ZVAL_NULL(&EG(error_zval));
/* destroys stack frame, therefore makes core dumps worthless */
#if 0&&ZEND_DEBUG
original_sigsegv_handler = signal(SIGSEGV, zend_handle_sigsegv);
#endif
EG(symtable_cache_ptr) = EG(symtable_cache) - 1;
EG(symtable_cache_limit) = EG(symtable_cache) + SYMTABLE_CACHE_SIZE - 1;
EG(no_extensions) = 0;
EG(function_table) = CG(function_table);
EG(class_table) = CG(class_table);
EG(in_autoload) = NULL;
EG(autoload_func) = NULL;
EG(error_handling) = EH_NORMAL;
zend_vm_stack_init();
zend_hash_init(&EG(symbol_table), 64, NULL, ZVAL_PTR_DTOR, 0);
EG(valid_symbol_table) = 1;
zend_llist_apply(&zend_extensions, (llist_apply_func_t) zend_extension_activator);
zend_hash_init(&EG(included_files), 8, NULL, NULL, 0);
EG(ticks_count) = 0;
ZVAL_UNDEF(&EG(user_error_handler));
EG(current_execute_data) = NULL;
zend_stack_init(&EG(user_error_handlers_error_reporting), sizeof(int));
zend_stack_init(&EG(user_error_handlers), sizeof(zval));
zend_stack_init(&EG(user_exception_handlers), sizeof(zval));
zend_objects_store_init(&EG(objects_store), 1024);
EG(full_tables_cleanup) = 0;
#ifdef ZEND_WIN32
EG(timed_out) = 0;
#endif
EG(exception) = NULL;
EG(prev_exception) = NULL;
EG(scope) = NULL;
EG(ht_iterators_count) = sizeof(EG(ht_iterators_slots)) / sizeof(HashTableIterator);
EG(ht_iterators_used) = 0;
EG(ht_iterators) = EG(ht_iterators_slots);
memset(EG(ht_iterators), 0, sizeof(EG(ht_iterators_slots)));
EG(active) = 1;
}
/* }}} */
static int zval_call_destructor(zval *zv) /* {{{ */
{
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zv = Z_INDIRECT_P(zv);
}
if (Z_TYPE_P(zv) == IS_OBJECT && Z_REFCOUNT_P(zv) == 1) {
return ZEND_HASH_APPLY_REMOVE;
} else {
return ZEND_HASH_APPLY_KEEP;
}
}
/* }}} */
static void zend_unclean_zval_ptr_dtor(zval *zv) /* {{{ */
{
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zv = Z_INDIRECT_P(zv);
}
i_zval_ptr_dtor(zv ZEND_FILE_LINE_CC);
}
/* }}} */
static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */
{
va_list va;
char *message = NULL;
va_start(va, format);
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
zend_throw_error(exception_ce, message);
} else {
zend_error(E_ERROR, "%s", message);
}
efree(message);
va_end(va);
}
/* }}} */
void shutdown_destructors(void) /* {{{ */
{
if (CG(unclean_shutdown)) {
EG(symbol_table).pDestructor = zend_unclean_zval_ptr_dtor;
}
zend_try {
uint32_t symbols;
do {
symbols = zend_hash_num_elements(&EG(symbol_table));
zend_hash_reverse_apply(&EG(symbol_table), (apply_func_t) zval_call_destructor);
} while (symbols != zend_hash_num_elements(&EG(symbol_table)));
zend_objects_store_call_destructors(&EG(objects_store));
} zend_catch {
/* if we couldn't destruct cleanly, mark all objects as destructed anyway */
zend_objects_store_mark_destructed(&EG(objects_store));
} zend_end_try();
}
/* }}} */
void shutdown_executor(void) /* {{{ */
{
zend_function *func;
zend_class_entry *ce;
zend_try {
/* Removed because this can not be safely done, e.g. in this situation:
Object 1 creates object 2
Object 3 holds reference to object 2.
Now when 1 and 2 are destroyed, 3 can still access 2 in its destructor, with
very problematic results */
/* zend_objects_store_call_destructors(&EG(objects_store)); */
/* Moved after symbol table cleaners, because some of the cleaners can call
destructors, which would use EG(symtable_cache_ptr) and thus leave leaks */
/* while (EG(symtable_cache_ptr)>=EG(symtable_cache)) {
zend_hash_destroy(*EG(symtable_cache_ptr));
efree(*EG(symtable_cache_ptr));
EG(symtable_cache_ptr)--;
}
*/
zend_llist_apply(&zend_extensions, (llist_apply_func_t) zend_extension_deactivator);
if (CG(unclean_shutdown)) {
EG(symbol_table).pDestructor = zend_unclean_zval_ptr_dtor;
}
zend_hash_graceful_reverse_destroy(&EG(symbol_table));
} zend_end_try();
EG(valid_symbol_table) = 0;
zend_try {
zval *zeh;
/* remove error handlers before destroying classes and functions,
* so that if handler used some class, crash would not happen */
if (Z_TYPE(EG(user_error_handler)) != IS_UNDEF) {
zeh = &EG(user_error_handler);
zval_ptr_dtor(zeh);
ZVAL_UNDEF(&EG(user_error_handler));
}
if (Z_TYPE(EG(user_exception_handler)) != IS_UNDEF) {
zeh = &EG(user_exception_handler);
zval_ptr_dtor(zeh);
ZVAL_UNDEF(&EG(user_exception_handler));
}
zend_stack_clean(&EG(user_error_handlers_error_reporting), NULL, 1);
zend_stack_clean(&EG(user_error_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1);
zend_stack_clean(&EG(user_exception_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1);
} zend_end_try();
zend_try {
/* Cleanup static data for functions and arrays.
* We need a separate cleanup stage because of the following problem:
* Suppose we destroy class X, which destroys the class's function table,
* and in the function table we have function foo() that has static $bar.
* Now if an object of class X is assigned to $bar, its destructor will be
* called and will fail since X's function table is in mid-destruction.
* So we want first of all to clean up all data and then move to tables destruction.
* Note that only run-time accessed data need to be cleaned up, pre-defined data can
* not contain objects and thus are not probelmatic */
if (EG(full_tables_cleanup)) {
ZEND_HASH_FOREACH_PTR(EG(function_table), func) {
if (func->type == ZEND_USER_FUNCTION) {
zend_cleanup_op_array_data((zend_op_array *) func);
}
} ZEND_HASH_FOREACH_END();
ZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) {
if (ce->type == ZEND_USER_CLASS) {
zend_cleanup_user_class_data(ce);
} else {
zend_cleanup_internal_class_data(ce);
}
} ZEND_HASH_FOREACH_END();
} else {
ZEND_HASH_REVERSE_FOREACH_PTR(EG(function_table), func) {
if (func->type != ZEND_USER_FUNCTION) {
break;
}
zend_cleanup_op_array_data((zend_op_array *) func);
} ZEND_HASH_FOREACH_END();
ZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) {
if (ce->type != ZEND_USER_CLASS) {
break;
}
zend_cleanup_user_class_data(ce);
} ZEND_HASH_FOREACH_END();
zend_cleanup_internal_classes();
}
} zend_end_try();
zend_try {
zend_llist_destroy(&CG(open_files));
} zend_end_try();
zend_try {
zend_close_rsrc_list(&EG(regular_list));
} zend_end_try();
#if ZEND_DEBUG
if (GC_G(gc_enabled) && !CG(unclean_shutdown)) {
gc_collect_cycles();
}
#endif
zend_try {
zend_objects_store_free_object_storage(&EG(objects_store));
zend_vm_stack_destroy();
/* Destroy all op arrays */
if (EG(full_tables_cleanup)) {
zend_hash_reverse_apply(EG(function_table), clean_non_persistent_function_full);
zend_hash_reverse_apply(EG(class_table), clean_non_persistent_class_full);
} else {
zend_hash_reverse_apply(EG(function_table), clean_non_persistent_function);
zend_hash_reverse_apply(EG(class_table), clean_non_persistent_class);
}
while (EG(symtable_cache_ptr)>=EG(symtable_cache)) {
zend_hash_destroy(*EG(symtable_cache_ptr));
FREE_HASHTABLE(*EG(symtable_cache_ptr));
EG(symtable_cache_ptr)--;
}
} zend_end_try();
zend_try {
clean_non_persistent_constants();
} zend_end_try();
zend_try {
#if 0&&ZEND_DEBUG
signal(SIGSEGV, original_sigsegv_handler);
#endif
zend_hash_destroy(&EG(included_files));
zend_stack_destroy(&EG(user_error_handlers_error_reporting));
zend_stack_destroy(&EG(user_error_handlers));
zend_stack_destroy(&EG(user_exception_handlers));
zend_objects_store_destroy(&EG(objects_store));
if (EG(in_autoload)) {
zend_hash_destroy(EG(in_autoload));
FREE_HASHTABLE(EG(in_autoload));
}
} zend_end_try();
zend_shutdown_fpu();
EG(ht_iterators_used) = 0;
if (EG(ht_iterators) != EG(ht_iterators_slots)) {
efree(EG(ht_iterators));
}
EG(active) = 0;
}
/* }}} */
/* return class name and "::" or "". */
ZEND_API const char *get_active_class_name(const char **space) /* {{{ */
{
zend_function *func;
if (!zend_is_executing()) {
if (space) {
*space = "";
}
return "";
}
func = EG(current_execute_data)->func;
switch (func->type) {
case ZEND_USER_FUNCTION:
case ZEND_INTERNAL_FUNCTION:
{
zend_class_entry *ce = func->common.scope;
if (space) {
*space = ce ? "::" : "";
}
return ce ? ZSTR_VAL(ce->name) : "";
}
default:
if (space) {
*space = "";
}
return "";
}
}
/* }}} */
ZEND_API const char *get_active_function_name(void) /* {{{ */
{
zend_function *func;
if (!zend_is_executing()) {
return NULL;
}
func = EG(current_execute_data)->func;
switch (func->type) {
case ZEND_USER_FUNCTION: {
zend_string *function_name = func->common.function_name;
if (function_name) {
return ZSTR_VAL(function_name);
} else {
return "main";
}
}
break;
case ZEND_INTERNAL_FUNCTION:
return ZSTR_VAL(func->common.function_name);
break;
default:
return NULL;
}
}
/* }}} */
ZEND_API const char *zend_get_executed_filename(void) /* {{{ */
{
zend_execute_data *ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
ex = ex->prev_execute_data;
}
if (ex) {
return ZSTR_VAL(ex->func->op_array.filename);
} else {
return "[no active file]";
}
}
/* }}} */
ZEND_API zend_string *zend_get_executed_filename_ex(void) /* {{{ */
{
zend_execute_data *ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
ex = ex->prev_execute_data;
}
if (ex) {
return ex->func->op_array.filename;
} else {
return NULL;
}
}
/* }}} */
ZEND_API uint zend_get_executed_lineno(void) /* {{{ */
{
zend_execute_data *ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
ex = ex->prev_execute_data;
}
if (ex) {
if (EG(exception) && ex->opline->opcode == ZEND_HANDLE_EXCEPTION &&
ex->opline->lineno == 0 && EG(opline_before_exception)) {
return EG(opline_before_exception)->lineno;
}
return ex->opline->lineno;
} else {
return 0;
}
}
/* }}} */
ZEND_API zend_bool zend_is_executing(void) /* {{{ */
{
return EG(current_execute_data) != 0;
}
/* }}} */
ZEND_API void _zval_ptr_dtor(zval *zval_ptr ZEND_FILE_LINE_DC) /* {{{ */
{
i_zval_ptr_dtor(zval_ptr ZEND_FILE_LINE_RELAY_CC);
}
/* }}} */
ZEND_API void _zval_internal_ptr_dtor(zval *zval_ptr ZEND_FILE_LINE_DC) /* {{{ */
{
if (Z_REFCOUNTED_P(zval_ptr)) {
Z_DELREF_P(zval_ptr);
if (Z_REFCOUNT_P(zval_ptr) == 0) {
_zval_internal_dtor_for_ptr(zval_ptr ZEND_FILE_LINE_CC);
}
}
}
/* }}} */
#define IS_VISITED_CONSTANT 0x80
#define IS_CONSTANT_VISITED(p) (Z_TYPE_P(p) & IS_VISITED_CONSTANT)
#define MARK_CONSTANT_VISITED(p) Z_TYPE_INFO_P(p) |= IS_VISITED_CONSTANT
#define RESET_CONSTANT_VISITED(p) Z_TYPE_INFO_P(p) &= ~IS_VISITED_CONSTANT
ZEND_API int zval_update_constant_ex(zval *p, zend_bool inline_change, zend_class_entry *scope) /* {{{ */
{
zval *const_value;
char *colon;
if (IS_CONSTANT_VISITED(p)) {
zend_throw_error(NULL, "Cannot declare self-referencing constant '%s'", Z_STRVAL_P(p));
return FAILURE;
} else if (Z_TYPE_P(p) == IS_CONSTANT) {
SEPARATE_ZVAL_NOREF(p);
MARK_CONSTANT_VISITED(p);
if (Z_CONST_FLAGS_P(p) & IS_CONSTANT_CLASS) {
ZEND_ASSERT(EG(current_execute_data));
if (inline_change) {
zend_string_release(Z_STR_P(p));
}
if (EG(scope) && EG(scope)->name) {
ZVAL_STR_COPY(p, EG(scope)->name);
} else {
ZVAL_EMPTY_STRING(p);
}
} else if (UNEXPECTED((const_value = zend_get_constant_ex(Z_STR_P(p), scope, Z_CONST_FLAGS_P(p))) == NULL)) {
char *actual = Z_STRVAL_P(p);
if (UNEXPECTED(EG(exception))) {
RESET_CONSTANT_VISITED(p);
return FAILURE;
} else if ((colon = (char*)zend_memrchr(Z_STRVAL_P(p), ':', Z_STRLEN_P(p)))) {
zend_throw_error(NULL, "Undefined class constant '%s'", Z_STRVAL_P(p));
RESET_CONSTANT_VISITED(p);
return FAILURE;
} else {
zend_string *save = Z_STR_P(p);
char *slash;
size_t actual_len = Z_STRLEN_P(p);
if ((Z_CONST_FLAGS_P(p) & IS_CONSTANT_UNQUALIFIED) && (slash = (char *)zend_memrchr(actual, '\\', actual_len))) {
actual = slash + 1;
actual_len -= (actual - Z_STRVAL_P(p));
if (inline_change) {
zend_string *s = zend_string_init(actual, actual_len, 0);
Z_STR_P(p) = s;
Z_TYPE_FLAGS_P(p) = IS_TYPE_REFCOUNTED | IS_TYPE_COPYABLE;
}
}
if (actual[0] == '\\') {
if (inline_change) {
memmove(Z_STRVAL_P(p), Z_STRVAL_P(p)+1, Z_STRLEN_P(p));
--Z_STRLEN_P(p);
} else {
++actual;
}
--actual_len;
}
if ((Z_CONST_FLAGS_P(p) & IS_CONSTANT_UNQUALIFIED) == 0) {
if (ZSTR_VAL(save)[0] == '\\') {
zend_throw_error(NULL, "Undefined constant '%s'", ZSTR_VAL(save) + 1);
} else {
zend_throw_error(NULL, "Undefined constant '%s'", ZSTR_VAL(save));
}
if (inline_change) {
zend_string_release(save);
}
RESET_CONSTANT_VISITED(p);
return FAILURE;
} else {
zend_error(E_NOTICE, "Use of undefined constant %s - assumed '%s'", actual, actual);
if (!inline_change) {
ZVAL_STRINGL(p, actual, actual_len);
} else {
Z_TYPE_INFO_P(p) = Z_REFCOUNTED_P(p) ?
IS_STRING_EX : IS_INTERNED_STRING_EX;
if (save && ZSTR_VAL(save) != actual) {
zend_string_release(save);
}
}
}
}
} else {
if (inline_change) {
zend_string_release(Z_STR_P(p));
}
ZVAL_COPY_VALUE(p, const_value);
if (Z_OPT_CONSTANT_P(p)) {
if (UNEXPECTED(zval_update_constant_ex(p, 1, NULL) != SUCCESS)) {
RESET_CONSTANT_VISITED(p);
return FAILURE;
}
}
zval_opt_copy_ctor(p);
}
} else if (Z_TYPE_P(p) == IS_CONSTANT_AST) {
zval tmp;
if (UNEXPECTED(zend_ast_evaluate(&tmp, Z_ASTVAL_P(p), scope) != SUCCESS)) {
return FAILURE;
}
if (inline_change) {
zval_ptr_dtor(p);
}
ZVAL_COPY_VALUE(p, &tmp);
}
return SUCCESS;
}
/* }}} */
ZEND_API int zval_update_constant(zval *pp, zend_bool inline_change) /* {{{ */
{
return zval_update_constant_ex(pp, inline_change, NULL);
}
/* }}} */
int call_user_function(HashTable *function_table, zval *object, zval *function_name, zval *retval_ptr, uint32_t param_count, zval params[]) /* {{{ */
{
return call_user_function_ex(function_table, object, function_name, retval_ptr, param_count, params, 1, NULL);
}
/* }}} */
int call_user_function_ex(HashTable *function_table, zval *object, zval *function_name, zval *retval_ptr, uint32_t param_count, zval params[], int no_separation, zend_array *symbol_table) /* {{{ */
{
zend_fcall_info fci;
fci.size = sizeof(fci);
fci.function_table = function_table;
fci.object = object ? Z_OBJ_P(object) : NULL;
ZVAL_COPY_VALUE(&fci.function_name, function_name);
fci.retval = retval_ptr;
fci.param_count = param_count;
fci.params = params;
fci.no_separation = (zend_bool) no_separation;
fci.symbol_table = symbol_table;
return zend_call_function(&fci, NULL);
}
/* }}} */
int zend_call_function(zend_fcall_info *fci, zend_fcall_info_cache *fci_cache) /* {{{ */
{
uint32_t i;
zend_class_entry *calling_scope = NULL;
zend_execute_data *call, dummy_execute_data;
zend_fcall_info_cache fci_cache_local;
zend_function *func;
zend_class_entry *orig_scope;
ZVAL_UNDEF(fci->retval);
if (!EG(active)) {
return FAILURE; /* executor is already inactive */
}
if (EG(exception)) {
return FAILURE; /* we would result in an instable executor otherwise */
}
switch (fci->size) {
case sizeof(zend_fcall_info):
break; /* nothing to do currently */
default:
zend_error_noreturn(E_CORE_ERROR, "Corrupted fcall_info provided to zend_call_function()");
break;
}
orig_scope = EG(scope);
/* Initialize execute_data */
if (!EG(current_execute_data)) {
/* This only happens when we're called outside any execute()'s
* It shouldn't be strictly necessary to NULL execute_data out,
* but it may make bugs easier to spot
*/
memset(&dummy_execute_data, 0, sizeof(zend_execute_data));
EG(current_execute_data) = &dummy_execute_data;
} else if (EG(current_execute_data)->func &&
ZEND_USER_CODE(EG(current_execute_data)->func->common.type) &&
EG(current_execute_data)->opline->opcode != ZEND_DO_FCALL &&
EG(current_execute_data)->opline->opcode != ZEND_DO_ICALL &&
EG(current_execute_data)->opline->opcode != ZEND_DO_UCALL &&
EG(current_execute_data)->opline->opcode != ZEND_DO_FCALL_BY_NAME) {
/* Insert fake frame in case of include or magic calls */
dummy_execute_data = *EG(current_execute_data);
dummy_execute_data.prev_execute_data = EG(current_execute_data);
dummy_execute_data.call = NULL;
dummy_execute_data.opline = NULL;
dummy_execute_data.func = NULL;
EG(current_execute_data) = &dummy_execute_data;
}
if (!fci_cache || !fci_cache->initialized) {
zend_string *callable_name;
char *error = NULL;
if (!fci_cache) {
fci_cache = &fci_cache_local;
}
if (!zend_is_callable_ex(&fci->function_name, fci->object, IS_CALLABLE_CHECK_SILENT, &callable_name, fci_cache, &error)) {
if (error) {
zend_error(E_WARNING, "Invalid callback %s, %s", ZSTR_VAL(callable_name), error);
efree(error);
}
if (callable_name) {
zend_string_release(callable_name);
}
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
return FAILURE;
} else if (error) {
/* Capitalize the first latter of the error message */
if (error[0] >= 'a' && error[0] <= 'z') {
error[0] += ('A' - 'a');
}
zend_error(E_DEPRECATED, "%s", error);
efree(error);
}
zend_string_release(callable_name);
}
func = fci_cache->function_handler;
call = zend_vm_stack_push_call_frame(ZEND_CALL_TOP_FUNCTION,
func, fci->param_count, fci_cache->called_scope, fci_cache->object);
calling_scope = fci_cache->calling_scope;
fci->object = fci_cache->object;
if (fci->object &&
(!EG(objects_store).object_buckets ||
!IS_OBJ_VALID(EG(objects_store).object_buckets[fci->object->handle]))) {
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
return FAILURE;
}
if (func->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_DEPRECATED)) {
if (func->common.fn_flags & ZEND_ACC_ABSTRACT) {
zend_throw_error(NULL, "Cannot call abstract method %s::%s()", ZSTR_VAL(func->common.scope->name), ZSTR_VAL(func->common.function_name));
return FAILURE;
}
if (func->common.fn_flags & ZEND_ACC_DEPRECATED) {
zend_error(E_DEPRECATED, "Function %s%s%s() is deprecated",
func->common.scope ? ZSTR_VAL(func->common.scope->name) : "",
func->common.scope ? "::" : "",
ZSTR_VAL(func->common.function_name));
}
}
for (i=0; i<fci->param_count; i++) {
zval *param;
zval *arg = &fci->params[i];
if (ARG_SHOULD_BE_SENT_BY_REF(func, i + 1)) {
if (UNEXPECTED(!Z_ISREF_P(arg))) {
if (fci->no_separation &&
!ARG_MAY_BE_SENT_BY_REF(func, i + 1)) {
if (i) {
/* hack to clean up the stack */
ZEND_CALL_NUM_ARGS(call) = i;
zend_vm_stack_free_args(call);
}
zend_vm_stack_free_call_frame(call);
zend_error(E_WARNING, "Parameter %d to %s%s%s() expected to be a reference, value given",
i+1,
func->common.scope ? ZSTR_VAL(func->common.scope->name) : "",
func->common.scope ? "::" : "",
ZSTR_VAL(func->common.function_name));
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
return FAILURE;
}
ZVAL_NEW_REF(arg, arg);
}
Z_ADDREF_P(arg);
} else {
if (Z_ISREF_P(arg) &&
!(func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) {
/* don't separate references for __call */
arg = Z_REFVAL_P(arg);
}
if (Z_OPT_REFCOUNTED_P(arg)) {
Z_ADDREF_P(arg);
}
}
param = ZEND_CALL_ARG(call, i+1);
ZVAL_COPY_VALUE(param, arg);
}
EG(scope) = calling_scope;
if (func->common.fn_flags & ZEND_ACC_STATIC) {
fci->object = NULL;
}
Z_OBJ(call->This) = fci->object;
if (UNEXPECTED(func->op_array.fn_flags & ZEND_ACC_CLOSURE)) {
ZEND_ASSERT(GC_TYPE((zend_object*)func->op_array.prototype) == IS_OBJECT);
GC_REFCOUNT((zend_object*)func->op_array.prototype)++;
ZEND_ADD_CALL_FLAG(call, ZEND_CALL_CLOSURE);
}
if (func->type == ZEND_USER_FUNCTION) {
int call_via_handler = (func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) != 0;
EG(scope) = func->common.scope;
call->symbol_table = fci->symbol_table;
if (EXPECTED((func->op_array.fn_flags & ZEND_ACC_GENERATOR) == 0)) {
zend_init_execute_data(call, &func->op_array, fci->retval);
zend_execute_ex(call);
} else {
zend_generator_create_zval(call, &func->op_array, fci->retval);
}
if (call_via_handler) {
/* We must re-initialize function again */
fci_cache->initialized = 0;
}
} else if (func->type == ZEND_INTERNAL_FUNCTION) {
int call_via_handler = (func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) != 0;
ZVAL_NULL(fci->retval);
if (func->common.scope) {
EG(scope) = func->common.scope;
}
call->prev_execute_data = EG(current_execute_data);
call->return_value = NULL; /* this is not a constructor call */
EG(current_execute_data) = call;
if (EXPECTED(zend_execute_internal == NULL)) {
/* saves one function call if zend_execute_internal is not used */
func->internal_function.handler(call, fci->retval);
} else {
zend_execute_internal(call, fci->retval);
}
EG(current_execute_data) = call->prev_execute_data;
zend_vm_stack_free_args(call);
/* We shouldn't fix bad extensions here,
because it can break proper ones (Bug #34045)
if (!EX(function_state).function->common.return_reference)
{
INIT_PZVAL(f->retval);
}*/
if (EG(exception)) {
zval_ptr_dtor(fci->retval);
ZVAL_UNDEF(fci->retval);
}
if (call_via_handler) {
/* We must re-initialize function again */
fci_cache->initialized = 0;
}
} else { /* ZEND_OVERLOADED_FUNCTION */
ZVAL_NULL(fci->retval);
/* Not sure what should be done here if it's a static method */
if (fci->object) {
call->prev_execute_data = EG(current_execute_data);
EG(current_execute_data) = call;
fci->object->handlers->call_method(func->common.function_name, fci->object, call, fci->retval);
EG(current_execute_data) = call->prev_execute_data;
} else {
zend_throw_error(NULL, "Cannot call overloaded function for non-object");
}
zend_vm_stack_free_args(call);
if (func->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY) {
zend_string_release(func->common.function_name);
}
efree(func);
if (EG(exception)) {
zval_ptr_dtor(fci->retval);
ZVAL_UNDEF(fci->retval);
}
}
EG(scope) = orig_scope;
zend_vm_stack_free_call_frame(call);
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
if (EG(exception)) {
zend_throw_exception_internal(NULL);
}
return SUCCESS;
}
/* }}} */
ZEND_API zend_class_entry *zend_lookup_class_ex(zend_string *name, const zval *key, int use_autoload) /* {{{ */
{
zend_class_entry *ce = NULL;
zval args[1];
zval local_retval;
int retval;
zend_string *lc_name;
zend_fcall_info fcall_info;
zend_fcall_info_cache fcall_cache;
if (key) {
lc_name = Z_STR_P(key);
} else {
if (name == NULL || !ZSTR_LEN(name)) {
return NULL;
}
if (ZSTR_VAL(name)[0] == '\\') {
lc_name = zend_string_alloc(ZSTR_LEN(name) - 1, 0);
zend_str_tolower_copy(ZSTR_VAL(lc_name), ZSTR_VAL(name) + 1, ZSTR_LEN(name) - 1);
} else {
lc_name = zend_string_tolower(name);
}
}
ce = zend_hash_find_ptr(EG(class_table), lc_name);
if (ce) {
if (!key) {
zend_string_release(lc_name);
}
return ce;
}
/* The compiler is not-reentrant. Make sure we __autoload() only during run-time
* (doesn't impact functionality of __autoload()
*/
if (!use_autoload || zend_is_compiling()) {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
if (!EG(autoload_func)) {
zend_function *func = zend_hash_str_find_ptr(EG(function_table), ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1);
if (func) {
EG(autoload_func) = func;
} else {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
}
/* Verify class name before passing it to __autoload() */
if (strspn(ZSTR_VAL(name), "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\") != ZSTR_LEN(name)) {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
if (EG(in_autoload) == NULL) {
ALLOC_HASHTABLE(EG(in_autoload));
zend_hash_init(EG(in_autoload), 8, NULL, NULL, 0);
}
if (zend_hash_add_empty_element(EG(in_autoload), lc_name) == NULL) {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
ZVAL_UNDEF(&local_retval);
if (ZSTR_VAL(name)[0] == '\\') {
ZVAL_STRINGL(&args[0], ZSTR_VAL(name) + 1, ZSTR_LEN(name) - 1);
} else {
ZVAL_STR_COPY(&args[0], name);
}
fcall_info.size = sizeof(fcall_info);
fcall_info.function_table = EG(function_table);
ZVAL_STR_COPY(&fcall_info.function_name, EG(autoload_func)->common.function_name);
fcall_info.symbol_table = NULL;
fcall_info.retval = &local_retval;
fcall_info.param_count = 1;
fcall_info.params = args;
fcall_info.object = NULL;
fcall_info.no_separation = 1;
fcall_cache.initialized = 1;
fcall_cache.function_handler = EG(autoload_func);
fcall_cache.calling_scope = NULL;
fcall_cache.called_scope = NULL;
fcall_cache.object = NULL;
zend_exception_save();
retval = zend_call_function(&fcall_info, &fcall_cache);
zend_exception_restore();
zval_ptr_dtor(&args[0]);
zval_dtor(&fcall_info.function_name);
zend_hash_del(EG(in_autoload), lc_name);
zval_ptr_dtor(&local_retval);
if (retval == SUCCESS) {
ce = zend_hash_find_ptr(EG(class_table), lc_name);
}
if (!key) {
zend_string_release(lc_name);
}
return ce;
}
/* }}} */
ZEND_API zend_class_entry *zend_lookup_class(zend_string *name) /* {{{ */
{
return zend_lookup_class_ex(name, NULL, 1);
}
/* }}} */
ZEND_API zend_class_entry *zend_get_called_scope(zend_execute_data *ex) /* {{{ */
{
while (ex) {
if (ex->called_scope) {
return ex->called_scope;
} else if (ex->func) {
if (ex->func->type != ZEND_INTERNAL_FUNCTION || ex->func->common.scope) {
return ex->called_scope;
}
}
ex = ex->prev_execute_data;
}
return NULL;
}
/* }}} */
ZEND_API zend_object *zend_get_this_object(zend_execute_data *ex) /* {{{ */
{
while (ex) {
if (Z_OBJ(ex->This)) {
return Z_OBJ(ex->This);
} else if (ex->func) {
if (ex->func->type != ZEND_INTERNAL_FUNCTION || ex->func->common.scope) {
return Z_OBJ(ex->This);
}
}
ex = ex->prev_execute_data;
}
return NULL;
}
/* }}} */
ZEND_API int zend_eval_stringl(char *str, size_t str_len, zval *retval_ptr, char *string_name) /* {{{ */
{
zval pv;
zend_op_array *new_op_array;
uint32_t original_compiler_options;
int retval;
if (retval_ptr) {
ZVAL_NEW_STR(&pv, zend_string_alloc(str_len + sizeof("return ;")-1, 1));
memcpy(Z_STRVAL(pv), "return ", sizeof("return ") - 1);
memcpy(Z_STRVAL(pv) + sizeof("return ") - 1, str, str_len);
Z_STRVAL(pv)[Z_STRLEN(pv) - 1] = ';';
Z_STRVAL(pv)[Z_STRLEN(pv)] = '\0';
} else {
ZVAL_STRINGL(&pv, str, str_len);
}
/*printf("Evaluating '%s'\n", pv.value.str.val);*/
original_compiler_options = CG(compiler_options);
CG(compiler_options) = ZEND_COMPILE_DEFAULT_FOR_EVAL;
new_op_array = zend_compile_string(&pv, string_name);
CG(compiler_options) = original_compiler_options;
if (new_op_array) {
zval local_retval;
EG(no_extensions)=1;
zend_try {
ZVAL_UNDEF(&local_retval);
zend_execute(new_op_array, &local_retval);
} zend_catch {
destroy_op_array(new_op_array);
efree_size(new_op_array, sizeof(zend_op_array));
zend_bailout();
} zend_end_try();
if (Z_TYPE(local_retval) != IS_UNDEF) {
if (retval_ptr) {
ZVAL_COPY_VALUE(retval_ptr, &local_retval);
} else {
zval_ptr_dtor(&local_retval);
}
} else {
if (retval_ptr) {
ZVAL_NULL(retval_ptr);
}
}
EG(no_extensions)=0;
destroy_op_array(new_op_array);
efree_size(new_op_array, sizeof(zend_op_array));
retval = SUCCESS;
} else {
retval = FAILURE;
}
zval_dtor(&pv);
return retval;
}
/* }}} */
ZEND_API int zend_eval_string(char *str, zval *retval_ptr, char *string_name) /* {{{ */
{
return zend_eval_stringl(str, strlen(str), retval_ptr, string_name);
}
/* }}} */
ZEND_API int zend_eval_stringl_ex(char *str, size_t str_len, zval *retval_ptr, char *string_name, int handle_exceptions) /* {{{ */
{
int result;
result = zend_eval_stringl(str, str_len, retval_ptr, string_name);
if (handle_exceptions && EG(exception)) {
zend_exception_error(EG(exception), E_ERROR);
result = FAILURE;
}
return result;
}
/* }}} */
ZEND_API int zend_eval_string_ex(char *str, zval *retval_ptr, char *string_name, int handle_exceptions) /* {{{ */
{
return zend_eval_stringl_ex(str, strlen(str), retval_ptr, string_name, handle_exceptions);
}
/* }}} */
ZEND_API void zend_timeout(int dummy) /* {{{ */
{
if (zend_on_timeout) {
#ifdef ZEND_SIGNALS
/*
We got here because we got a timeout signal, so we are in a signal handler
at this point. However, we want to be able to timeout any user-supplied
shutdown functions, so pretend we are not in a signal handler while we are
calling these
*/
SIGG(running) = 0;
#endif
zend_on_timeout(EG(timeout_seconds));
}
zend_error_noreturn(E_ERROR, "Maximum execution time of %pd second%s exceeded", EG(timeout_seconds), EG(timeout_seconds) == 1 ? "" : "s");
}
/* }}} */
#ifdef ZEND_WIN32
VOID CALLBACK tq_timer_cb(PVOID arg, BOOLEAN timed_out)
{
zend_bool *php_timed_out;
/* The doc states it'll be always true, however it theoretically
could be FALSE when the thread was signaled. */
if (!timed_out) {
return;
}
php_timed_out = (zend_bool *)arg;
*php_timed_out = 1;
}
#endif
/* This one doesn't exists on QNX */
#ifndef SIGPROF
#define SIGPROF 27
#endif
void zend_set_timeout(zend_long seconds, int reset_signals) /* {{{ */
{
EG(timeout_seconds) = seconds;
#ifdef ZEND_WIN32
if(!seconds) {
return;
}
/* Don't use ChangeTimerQueueTimer() as it will not restart an expired
timer, so we could end up with just an ignored timeout. Instead
delete and recreate. */
if (NULL != tq_timer) {
if (!DeleteTimerQueueTimer(NULL, tq_timer, NULL)) {
EG(timed_out) = 0;
tq_timer = NULL;
zend_error_noreturn(E_ERROR, "Could not delete queued timer");
return;
}
tq_timer = NULL;
}
/* XXX passing NULL means the default timer queue provided by the system is used */
if (!CreateTimerQueueTimer(&tq_timer, NULL, (WAITORTIMERCALLBACK)tq_timer_cb, (VOID*)&EG(timed_out), seconds*1000, 0, WT_EXECUTEONLYONCE)) {
EG(timed_out) = 0;
tq_timer = NULL;
zend_error_noreturn(E_ERROR, "Could not queue new timer");
return;
}
EG(timed_out) = 0;
#else
# ifdef HAVE_SETITIMER
{
struct itimerval t_r; /* timeout requested */
int signo;
if(seconds) {
t_r.it_value.tv_sec = seconds;
t_r.it_value.tv_usec = t_r.it_interval.tv_sec = t_r.it_interval.tv_usec = 0;
# ifdef __CYGWIN__
setitimer(ITIMER_REAL, &t_r, NULL);
}
signo = SIGALRM;
# else
setitimer(ITIMER_PROF, &t_r, NULL);
}
signo = SIGPROF;
# endif
if (reset_signals) {
# ifdef ZEND_SIGNALS
zend_signal(signo, zend_timeout);
# else
sigset_t sigset;
signal(signo, zend_timeout);
sigemptyset(&sigset);
sigaddset(&sigset, signo);
sigprocmask(SIG_UNBLOCK, &sigset, NULL);
# endif
}
}
# endif /* HAVE_SETITIMER */
#endif
}
/* }}} */
void zend_unset_timeout(void) /* {{{ */
{
#ifdef ZEND_WIN32
if (NULL != tq_timer) {
if (!DeleteTimerQueueTimer(NULL, tq_timer, NULL)) {
EG(timed_out) = 0;
tq_timer = NULL;
zend_error_noreturn(E_ERROR, "Could not delete queued timer");
return;
}
tq_timer = NULL;
}
EG(timed_out) = 0;
#else
# ifdef HAVE_SETITIMER
if (EG(timeout_seconds)) {
struct itimerval no_timeout;
no_timeout.it_value.tv_sec = no_timeout.it_value.tv_usec = no_timeout.it_interval.tv_sec = no_timeout.it_interval.tv_usec = 0;
#ifdef __CYGWIN__
setitimer(ITIMER_REAL, &no_timeout, NULL);
#else
setitimer(ITIMER_PROF, &no_timeout, NULL);
#endif
}
# endif
#endif
}
/* }}} */
zend_class_entry *zend_fetch_class(zend_string *class_name, int fetch_type) /* {{{ */
{
zend_class_entry *ce;
int fetch_sub_type = fetch_type & ZEND_FETCH_CLASS_MASK;
check_fetch_type:
switch (fetch_sub_type) {
case ZEND_FETCH_CLASS_SELF:
if (UNEXPECTED(!EG(scope))) {
zend_throw_or_error(fetch_type, NULL, "Cannot access self:: when no class scope is active");
}
return EG(scope);
case ZEND_FETCH_CLASS_PARENT:
if (UNEXPECTED(!EG(scope))) {
zend_throw_or_error(fetch_type, NULL, "Cannot access parent:: when no class scope is active");
return NULL;
}
if (UNEXPECTED(!EG(scope)->parent)) {
zend_throw_or_error(fetch_type, NULL, "Cannot access parent:: when current class scope has no parent");
}
return EG(scope)->parent;
case ZEND_FETCH_CLASS_STATIC:
ce = zend_get_called_scope(EG(current_execute_data));
if (UNEXPECTED(!ce)) {
zend_throw_or_error(fetch_type, NULL, "Cannot access static:: when no class scope is active");
return NULL;
}
return ce;
case ZEND_FETCH_CLASS_AUTO: {
fetch_sub_type = zend_get_class_fetch_type(class_name);
if (UNEXPECTED(fetch_sub_type != ZEND_FETCH_CLASS_DEFAULT)) {
goto check_fetch_type;
}
}
break;
}
if (fetch_type & ZEND_FETCH_CLASS_NO_AUTOLOAD) {
return zend_lookup_class_ex(class_name, NULL, 0);
} else if ((ce = zend_lookup_class_ex(class_name, NULL, 1)) == NULL) {
if (!(fetch_type & ZEND_FETCH_CLASS_SILENT) && !EG(exception)) {
if (fetch_sub_type == ZEND_FETCH_CLASS_INTERFACE) {
zend_throw_or_error(fetch_type, NULL, "Interface '%s' not found", ZSTR_VAL(class_name));
} else if (fetch_sub_type == ZEND_FETCH_CLASS_TRAIT) {
zend_throw_or_error(fetch_type, NULL, "Trait '%s' not found", ZSTR_VAL(class_name));
} else {
zend_throw_or_error(fetch_type, NULL, "Class '%s' not found", ZSTR_VAL(class_name));
}
}
return NULL;
}
return ce;
}
/* }}} */
zend_class_entry *zend_fetch_class_by_name(zend_string *class_name, const zval *key, int fetch_type) /* {{{ */
{
zend_class_entry *ce;
if (fetch_type & ZEND_FETCH_CLASS_NO_AUTOLOAD) {
return zend_lookup_class_ex(class_name, key, 0);
} else if ((ce = zend_lookup_class_ex(class_name, key, 1)) == NULL) {
if ((fetch_type & ZEND_FETCH_CLASS_SILENT) == 0 && !EG(exception)) {
if ((fetch_type & ZEND_FETCH_CLASS_MASK) == ZEND_FETCH_CLASS_INTERFACE) {
zend_throw_or_error(fetch_type, NULL, "Interface '%s' not found", ZSTR_VAL(class_name));
} else if ((fetch_type & ZEND_FETCH_CLASS_MASK) == ZEND_FETCH_CLASS_TRAIT) {
zend_throw_or_error(fetch_type, NULL, "Trait '%s' not found", ZSTR_VAL(class_name));
} else {
zend_throw_or_error(fetch_type, NULL, "Class '%s' not found", ZSTR_VAL(class_name));
}
}
return NULL;
}
return ce;
}
/* }}} */
#define MAX_ABSTRACT_INFO_CNT 3
#define MAX_ABSTRACT_INFO_FMT "%s%s%s%s"
#define DISPLAY_ABSTRACT_FN(idx) \
ai.afn[idx] ? ZEND_FN_SCOPE_NAME(ai.afn[idx]) : "", \
ai.afn[idx] ? "::" : "", \
ai.afn[idx] ? ZSTR_VAL(ai.afn[idx]->common.function_name) : "", \
ai.afn[idx] && ai.afn[idx + 1] ? ", " : (ai.afn[idx] && ai.cnt > MAX_ABSTRACT_INFO_CNT ? ", ..." : "")
typedef struct _zend_abstract_info {
zend_function *afn[MAX_ABSTRACT_INFO_CNT + 1];
int cnt;
int ctor;
} zend_abstract_info;
static void zend_verify_abstract_class_function(zend_function *fn, zend_abstract_info *ai) /* {{{ */
{
if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) {
if (ai->cnt < MAX_ABSTRACT_INFO_CNT) {
ai->afn[ai->cnt] = fn;
}
if (fn->common.fn_flags & ZEND_ACC_CTOR) {
if (!ai->ctor) {
ai->cnt++;
ai->ctor = 1;
} else {
ai->afn[ai->cnt] = NULL;
}
} else {
ai->cnt++;
}
}
}
/* }}} */
void zend_verify_abstract_class(zend_class_entry *ce) /* {{{ */
{
zend_function *func;
zend_abstract_info ai;
if ((ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) && !(ce->ce_flags & (ZEND_ACC_TRAIT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) {
memset(&ai, 0, sizeof(ai));
ZEND_HASH_FOREACH_PTR(&ce->function_table, func) {
zend_verify_abstract_class_function(func, &ai);
} ZEND_HASH_FOREACH_END();
if (ai.cnt) {
zend_error_noreturn(E_ERROR, "Class %s contains %d abstract method%s and must therefore be declared abstract or implement the remaining methods (" MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT ")",
ZSTR_VAL(ce->name), ai.cnt,
ai.cnt > 1 ? "s" : "",
DISPLAY_ABSTRACT_FN(0),
DISPLAY_ABSTRACT_FN(1),
DISPLAY_ABSTRACT_FN(2)
);
}
}
}
/* }}} */
ZEND_API int zend_delete_global_variable(zend_string *name) /* {{{ */
{
return zend_hash_del_ind(&EG(symbol_table), name);
}
/* }}} */
ZEND_API zend_array *zend_rebuild_symbol_table(void) /* {{{ */
{
zend_execute_data *ex;
zend_array *symbol_table;
/* Search for last called user function */
ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->common.type))) {
ex = ex->prev_execute_data;
}
if (!ex) {
return NULL;
}
if (ex->symbol_table) {
return ex->symbol_table;
}
if (EG(symtable_cache_ptr) >= EG(symtable_cache)) {
/*printf("Cache hit! Reusing %x\n", symtable_cache[symtable_cache_ptr]);*/
symbol_table = ex->symbol_table = *(EG(symtable_cache_ptr)--);
if (!ex->func->op_array.last_var) {
return symbol_table;
}
zend_hash_extend(symbol_table, ex->func->op_array.last_var, 0);
} else {
symbol_table = ex->symbol_table = emalloc(sizeof(zend_array));
zend_hash_init(symbol_table, ex->func->op_array.last_var, NULL, ZVAL_PTR_DTOR, 0);
if (!ex->func->op_array.last_var) {
return symbol_table;
}
zend_hash_real_init(symbol_table, 0);
/*printf("Cache miss! Initialized %x\n", EG(active_symbol_table));*/
}
if (EXPECTED(ex->func->op_array.last_var)) {
zend_string **str = ex->func->op_array.vars;
zend_string **end = str + ex->func->op_array.last_var;
zval *var = ZEND_CALL_VAR_NUM(ex, 0);
do {
_zend_hash_append_ind(symbol_table, *str, var);
str++;
var++;
} while (str != end);
}
return symbol_table;
}
/* }}} */
ZEND_API void zend_attach_symbol_table(zend_execute_data *execute_data) /* {{{ */
{
zend_op_array *op_array = &execute_data->func->op_array;
HashTable *ht = execute_data->symbol_table;
/* copy real values from symbol table into CV slots and create
INDIRECT references to CV in symbol table */
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
zval *var = EX_VAR_NUM(0);
do {
zval *zv = zend_hash_find(ht, *str);
if (zv) {
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zval *val = Z_INDIRECT_P(zv);
ZVAL_COPY_VALUE(var, val);
} else {
ZVAL_COPY_VALUE(var, zv);
}
} else {
ZVAL_UNDEF(var);
zv = zend_hash_add_new(ht, *str, var);
}
ZVAL_INDIRECT(zv, var);
str++;
var++;
} while (str != end);
}
}
/* }}} */
ZEND_API void zend_detach_symbol_table(zend_execute_data *execute_data) /* {{{ */
{
zend_op_array *op_array = &execute_data->func->op_array;
HashTable *ht = execute_data->symbol_table;
/* copy real values from CV slots into symbol table */
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
zval *var = EX_VAR_NUM(0);
do {
if (Z_TYPE_P(var) == IS_UNDEF) {
zend_hash_del(ht, *str);
} else {
zend_hash_update(ht, *str, var);
ZVAL_UNDEF(var);
}
str++;
var++;
} while (str != end);
}
}
/* }}} */
ZEND_API int zend_set_local_var(zend_string *name, zval *value, int force) /* {{{ */
{
zend_execute_data *execute_data = EG(current_execute_data);
while (execute_data && (!execute_data->func || !ZEND_USER_CODE(execute_data->func->common.type))) {
execute_data = execute_data->prev_execute_data;
}
if (execute_data) {
if (!execute_data->symbol_table) {
zend_ulong h = zend_string_hash_val(name);
zend_op_array *op_array = &execute_data->func->op_array;
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
do {
if (ZSTR_H(*str) == h &&
ZSTR_LEN(*str) == ZSTR_LEN(name) &&
memcmp(ZSTR_VAL(*str), ZSTR_VAL(name), ZSTR_LEN(name)) == 0) {
zval *var = EX_VAR_NUM(str - op_array->vars);
ZVAL_COPY_VALUE(var, value);
return SUCCESS;
}
str++;
} while (str != end);
}
if (force) {
zend_array *symbol_table = zend_rebuild_symbol_table();
if (symbol_table) {
return zend_hash_update(symbol_table, name, value) ? SUCCESS : FAILURE;;
}
}
} else {
return (zend_hash_update_ind(execute_data->symbol_table, name, value) != NULL) ? SUCCESS : FAILURE;
}
}
return FAILURE;
}
/* }}} */
ZEND_API int zend_set_local_var_str(const char *name, size_t len, zval *value, int force) /* {{{ */
{
zend_execute_data *execute_data = EG(current_execute_data);
while (execute_data && (!execute_data->func || !ZEND_USER_CODE(execute_data->func->common.type))) {
execute_data = execute_data->prev_execute_data;
}
if (execute_data) {
if (!execute_data->symbol_table) {
zend_ulong h = zend_hash_func(name, len);
zend_op_array *op_array = &execute_data->func->op_array;
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
do {
if (ZSTR_H(*str) == h &&
ZSTR_LEN(*str) == len &&
memcmp(ZSTR_VAL(*str), name, len) == 0) {
zval *var = EX_VAR_NUM(str - op_array->vars);
zval_ptr_dtor(var);
ZVAL_COPY_VALUE(var, value);
return SUCCESS;
}
str++;
} while (str != end);
}
if (force) {
zend_array *symbol_table = zend_rebuild_symbol_table();
if (symbol_table) {
return zend_hash_str_update(symbol_table, name, len, value) ? SUCCESS : FAILURE;;
}
}
} else {
return (zend_hash_str_update_ind(execute_data->symbol_table, name, len, value) != NULL) ? SUCCESS : FAILURE;
}
}
return FAILURE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: t
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-134/c/bad_1792_0 |
crossvul-cpp_data_good_2610_0 | /* imzmq3.c
*
* This input plugin enables rsyslog to read messages from a ZeroMQ
* queue.
*
* Copyright 2012 Talksum, Inc.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* Authors:
* David Kelly <davidk@talksum.com>
* Hongfei Cheng <hongfeic@talksum.com>
*/
#include "config.h"
#include "rsyslog.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "cfsysline.h"
#include "dirty.h"
#include "errmsg.h"
#include "glbl.h"
#include "module-template.h"
#include "msg.h"
#include "net.h"
#include "parser.h"
#include "prop.h"
#include "ruleset.h"
#include "srUtils.h"
#include "unicode-helper.h"
#include <czmq.h>
MODULE_TYPE_INPUT
MODULE_TYPE_NOKEEP
MODULE_CNFNAME("imzmq3");
/* convienent symbols to denote a socket we want to bind
* vs one we want to just connect to
*/
#define ACTION_CONNECT 1
#define ACTION_BIND 2
/* Module static data */
DEF_IMOD_STATIC_DATA
DEFobjCurrIf(errmsg)
DEFobjCurrIf(glbl)
DEFobjCurrIf(prop)
DEFobjCurrIf(ruleset)
/* ----------------------------------------------------------------------------
* structs to describe sockets
*/
typedef struct _socket_type {
char* name;
int type;
} socket_type;
/* more overkill, but seems nice to be consistent.*/
typedef struct _socket_action {
char* name;
int action;
} socket_action;
typedef struct _poller_data {
ruleset_t* ruleset;
thrdInfo_t* thread;
} poller_data;
/* a linked-list of subscription topics */
typedef struct sublist_t {
char* subscribe;
struct sublist_t* next;
} sublist;
struct instanceConf_s {
int type;
int action;
char* description;
int sndHWM; /* if you want more than 2^32 messages, */
int rcvHWM; /* then pass in 0 (the default). */
char* identity;
sublist* subscriptions;
int sndBuf;
int rcvBuf;
int linger;
int backlog;
int sndTimeout;
int rcvTimeout;
int maxMsgSize;
int rate;
int recoveryIVL;
int multicastHops;
int reconnectIVL;
int reconnectIVLMax;
int ipv4Only;
int affinity;
uchar* pszBindRuleset;
ruleset_t* pBindRuleset;
struct instanceConf_s* next;
};
struct modConfData_s {
rsconf_t* pConf;
instanceConf_t* root;
instanceConf_t* tail;
int io_threads;
};
struct lstn_s {
struct lstn_s* next;
void* sock;
ruleset_t* pRuleset;
};
/* ----------------------------------------------------------------------------
* Static definitions/initializations.
*/
static modConfData_t* runModConf = NULL;
static struct lstn_s* lcnfRoot = NULL;
static struct lstn_s* lcnfLast = NULL;
static prop_t* s_namep = NULL;
static zloop_t* s_zloop = NULL;
static zctx_t* s_context = NULL;
static socket_type socketTypes[] = {
{"SUB", ZMQ_SUB },
{"PULL", ZMQ_PULL },
{"ROUTER", ZMQ_ROUTER },
{"XSUB", ZMQ_XSUB }
};
static socket_action socketActions[] = {
{"BIND", ACTION_BIND},
{"CONNECT", ACTION_CONNECT},
};
static struct cnfparamdescr modpdescr[] = {
{ "ioThreads", eCmdHdlrInt, 0 },
};
static struct cnfparamblk modpblk = {
CNFPARAMBLK_VERSION,
sizeof(modpdescr)/sizeof(struct cnfparamdescr),
modpdescr
};
static struct cnfparamdescr inppdescr[] = {
{ "description", eCmdHdlrGetWord, 0 },
{ "sockType", eCmdHdlrGetWord, 0 },
{ "subscribe", eCmdHdlrGetWord, 0 },
{ "ruleset", eCmdHdlrGetWord, 0 },
{ "action", eCmdHdlrGetWord, 0 },
{ "sndHWM", eCmdHdlrInt, 0 },
{ "rcvHWM", eCmdHdlrInt, 0 },
{ "identity", eCmdHdlrGetWord, 0 },
{ "sndBuf", eCmdHdlrInt, 0 },
{ "rcvBuf", eCmdHdlrInt, 0 },
{ "linger", eCmdHdlrInt, 0 },
{ "backlog", eCmdHdlrInt, 0 },
{ "sndTimeout", eCmdHdlrInt, 0 },
{ "rcvTimeout", eCmdHdlrInt, 0 },
{ "maxMsgSize", eCmdHdlrInt, 0 },
{ "rate", eCmdHdlrInt, 0 },
{ "recoveryIVL", eCmdHdlrInt, 0 },
{ "multicastHops", eCmdHdlrInt, 0 },
{ "reconnectIVL", eCmdHdlrInt, 0 },
{ "reconnectIVLMax", eCmdHdlrInt, 0 },
{ "ipv4Only", eCmdHdlrInt, 0 },
{ "affinity", eCmdHdlrInt, 0 }
};
static struct cnfparamblk inppblk = {
CNFPARAMBLK_VERSION,
sizeof(inppdescr)/sizeof(struct cnfparamdescr),
inppdescr
};
#include "im-helper.h" /* must be included AFTER the type definitions! */
/* ----------------------------------------------------------------------------
* Helper functions
*/
/* get the name of a socket type, return the ZMQ_XXX type
or -1 if not a supported type (see above)
*/
static int getSocketType(char* name) {
int type = -1;
uint i;
/* match name with known socket type */
for(i=0; i<sizeof(socketTypes)/sizeof(socket_type); ++i) {
if( !strcmp(socketTypes[i].name, name) ) {
type = socketTypes[i].type;
break;
}
}
/* whine if no match was found. */
if (type == -1)
errmsg.LogError(0, NO_ERRCODE, "unknown type %s",name);
return type;
}
static int getSocketAction(char* name) {
int action = -1;
uint i;
/* match name with known socket action */
for(i=0; i < sizeof(socketActions)/sizeof(socket_action); ++i) {
if(!strcmp(socketActions[i].name, name)) {
action = socketActions[i].action;
break;
}
}
/* whine if no matching action was found */
if (action == -1)
errmsg.LogError(0, NO_ERRCODE, "unknown action %s",name);
return action;
}
static void setDefaults(instanceConf_t* info) {
info->type = -1;
info->action = -1;
info->description = NULL;
info->sndHWM = -1;
info->rcvHWM = -1;
info->identity = NULL;
info->subscriptions = NULL;
info->pszBindRuleset = NULL;
info->pBindRuleset = NULL;
info->sndBuf = -1;
info->rcvBuf = -1;
info->linger = -1;
info->backlog = -1;
info->sndTimeout = -1;
info->rcvTimeout = -1;
info->maxMsgSize = -1;
info->rate = -1;
info->recoveryIVL = -1;
info->multicastHops = -1;
info->reconnectIVL = -1;
info->reconnectIVLMax = -1;
info->ipv4Only = -1;
info->affinity = -1;
info->next = NULL;
};
/* given a comma separated list of subscriptions, create a char* array of them
* to set later
*/
static rsRetVal parseSubscriptions(char* subscribes, sublist** subList){
char* tok = strtok(subscribes, ",");
sublist* currentSub;
sublist* head;
DEFiRet;
/* create empty list */
CHKmalloc(*subList = (sublist*)MALLOC(sizeof(sublist)));
head = *subList;
head->next = NULL;
head->subscribe=NULL;
currentSub=head;
if(tok) {
head->subscribe=strdup(tok);
for(tok=strtok(NULL, ","); tok!=NULL;tok=strtok(NULL, ",")) {
CHKmalloc(currentSub->next = (sublist*)MALLOC(sizeof(sublist)));
currentSub=currentSub->next;
currentSub->subscribe=strdup(tok);
currentSub->next=NULL;
}
} else {
/* make empty subscription ie subscribe="" */
head->subscribe=strdup("");
}
/* TODO: temporary logging */
currentSub = head;
DBGPRINTF("imzmq3: Subscriptions:");
for(currentSub = head; currentSub != NULL; currentSub=currentSub->next) {
DBGPRINTF("'%s'", currentSub->subscribe);
}
DBGPRINTF("\n");
finalize_it:
RETiRet;
}
static rsRetVal validateConfig(instanceConf_t* info) {
if (info->type == -1) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"you entered an invalid type");
return RS_RET_INVALID_PARAMS;
}
if (info->action == -1) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"you entered an invalid action");
return RS_RET_INVALID_PARAMS;
}
if (info->description == NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"you didn't enter a description");
return RS_RET_INVALID_PARAMS;
}
if(info->type == ZMQ_SUB && info->subscriptions == NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"SUB sockets need a subscription");
return RS_RET_INVALID_PARAMS;
}
if(info->type != ZMQ_SUB && info->subscriptions != NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"only SUB sockets can have subscriptions");
return RS_RET_INVALID_PARAMS;
}
return RS_RET_OK;
}
static rsRetVal createContext() {
if (s_context == NULL) {
DBGPRINTF("imzmq3: creating zctx...");
zsys_handler_set(NULL);
s_context = zctx_new();
if (s_context == NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"zctx_new failed: %s",
zmq_strerror(errno));
/* DK: really should do better than invalid params...*/
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("success!\n");
if (runModConf->io_threads > 1) {
DBGPRINTF("setting io worker threads to %d\n", runModConf->io_threads);
zctx_set_iothreads(s_context, runModConf->io_threads);
}
}
return RS_RET_OK;
}
static rsRetVal createSocket(instanceConf_t* info, void** sock) {
int rv;
sublist* sub;
*sock = zsocket_new(s_context, info->type);
if (!sock) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zsocket_new failed: %s, for type %d",
zmq_strerror(errno),info->type);
/* DK: invalid params seems right here */
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: socket of type %d created successfully\n", info->type)
/* Set options *before* the connect/bind. */
if (info->identity) zsocket_set_identity(*sock, info->identity);
if (info->sndBuf > -1) zsocket_set_sndbuf(*sock, info->sndBuf);
if (info->rcvBuf > -1) zsocket_set_rcvbuf(*sock, info->rcvBuf);
if (info->linger > -1) zsocket_set_linger(*sock, info->linger);
if (info->backlog > -1) zsocket_set_backlog(*sock, info->backlog);
if (info->sndTimeout > -1) zsocket_set_sndtimeo(*sock, info->sndTimeout);
if (info->rcvTimeout > -1) zsocket_set_rcvtimeo(*sock, info->rcvTimeout);
if (info->maxMsgSize > -1) zsocket_set_maxmsgsize(*sock, info->maxMsgSize);
if (info->rate > -1) zsocket_set_rate(*sock, info->rate);
if (info->recoveryIVL > -1) zsocket_set_recovery_ivl(*sock, info->recoveryIVL);
if (info->multicastHops > -1) zsocket_set_multicast_hops(*sock, info->multicastHops);
if (info->reconnectIVL > -1) zsocket_set_reconnect_ivl(*sock, info->reconnectIVL);
if (info->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(*sock, info->reconnectIVLMax);
if (info->ipv4Only > -1) zsocket_set_ipv4only(*sock, info->ipv4Only);
if (info->affinity > -1) zsocket_set_affinity(*sock, info->affinity);
if (info->sndHWM > -1 ) zsocket_set_sndhwm(*sock, info->sndHWM);
if (info->rcvHWM > -1 ) zsocket_set_rcvhwm(*sock, info->rcvHWM);
/* Set subscriptions.*/
if (info->type == ZMQ_SUB) {
for(sub = info->subscriptions; sub!=NULL; sub=sub->next) {
zsocket_set_subscribe(*sock, sub->subscribe);
}
}
/* Do the bind/connect... */
if (info->action==ACTION_CONNECT) {
rv = zsocket_connect(*sock, "%s", info->description);
if (rv == -1) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zmq_connect using %s failed: %s",
info->description, zmq_strerror(errno));
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: connect for %s successful\n",info->description);
} else {
rv = zsocket_bind(*sock, "%s", info->description);
if (rv == -1) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zmq_bind using %s failed: %s",
info->description, zmq_strerror(errno));
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: bind for %s successful\n",info->description);
}
return RS_RET_OK;
}
/* ----------------------------------------------------------------------------
* Module endpoints
*/
/* add an actual endpoint
*/
static rsRetVal createInstance(instanceConf_t** pinst) {
DEFiRet;
instanceConf_t* inst;
CHKmalloc(inst = MALLOC(sizeof(instanceConf_t)));
/* set defaults into new instance config struct */
setDefaults(inst);
/* add this to the config */
if (runModConf->root == NULL || runModConf->tail == NULL) {
runModConf->tail = runModConf->root = inst;
} else {
runModConf->tail->next = inst;
runModConf->tail = inst;
}
*pinst = inst;
finalize_it:
RETiRet;
}
static rsRetVal createListener(struct cnfparamvals* pvals) {
instanceConf_t* inst;
int i;
DEFiRet;
CHKiRet(createInstance(&inst));
for(i = 0 ; i < inppblk.nParams ; ++i) {
if(!pvals[i].bUsed)
continue;
if(!strcmp(inppblk.descr[i].name, "ruleset")) {
inst->pszBindRuleset = (uchar *)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(inppblk.descr[i].name, "description")) {
inst->description = es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(inppblk.descr[i].name, "sockType")){
inst->type = getSocketType(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if(!strcmp(inppblk.descr[i].name, "action")){
inst->action = getSocketAction(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if(!strcmp(inppblk.descr[i].name, "sndHWM")) {
inst->sndHWM = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rcvHWM")) {
inst->rcvHWM = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "subscribe")) {
char *subscribes = es_str2cstr(pvals[i].val.d.estr, NULL);
rsRetVal ret = parseSubscriptions(subscribes, &inst->subscriptions);
free(subscribes);
CHKiRet(ret);
} else if(!strcmp(inppblk.descr[i].name, "identity")){
inst->identity = es_str2cstr(pvals[i].val.d.estr, NULL);
} else if(!strcmp(inppblk.descr[i].name, "sndBuf")) {
inst->sndBuf = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rcvBuf")) {
inst->rcvBuf = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "linger")) {
inst->linger = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "backlog")) {
inst->backlog = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "sndTimeout")) {
inst->sndTimeout = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rcvTimeout")) {
inst->rcvTimeout = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "maxMsgSize")) {
inst->maxMsgSize = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "rate")) {
inst->rate = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "recoveryIVL")) {
inst->recoveryIVL = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "multicastHops")) {
inst->multicastHops = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "reconnectIVL")) {
inst->reconnectIVL = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "reconnectIVLMax")) {
inst->reconnectIVLMax = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "ipv4Only")) {
inst->ipv4Only = (int) pvals[i].val.d.n;
} else if(!strcmp(inppblk.descr[i].name, "affinity")) {
inst->affinity = (int) pvals[i].val.d.n;
} else {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: program error, non-handled "
"param '%s'\n", inppblk.descr[i].name);
}
}
finalize_it:
RETiRet;
}
static rsRetVal addListener(instanceConf_t* inst){
/* create the socket */
void* sock;
struct lstn_s* newcnfinfo;
DEFiRet;
CHKiRet(createSocket(inst, &sock));
/* now create new lstn_s struct */
CHKmalloc(newcnfinfo=(struct lstn_s*)MALLOC(sizeof(struct lstn_s)));
newcnfinfo->next = NULL;
newcnfinfo->sock = sock;
newcnfinfo->pRuleset = inst->pBindRuleset;
/* add this struct to the global */
if(lcnfRoot == NULL) {
lcnfRoot = newcnfinfo;
}
if(lcnfLast == NULL) {
lcnfLast = newcnfinfo;
} else {
lcnfLast->next = newcnfinfo;
lcnfLast = newcnfinfo;
}
finalize_it:
RETiRet;
}
static int handlePoll(zloop_t __attribute__((unused)) * loop, zmq_pollitem_t *poller, void* pd) {
smsg_t* pMsg;
poller_data* pollerData = (poller_data*)pd;
char* buf = zstr_recv(poller->socket);
if (msgConstruct(&pMsg) == RS_RET_OK) {
MsgSetRawMsg(pMsg, buf, strlen(buf));
MsgSetInputName(pMsg, s_namep);
MsgSetHOSTNAME(pMsg, glbl.GetLocalHostName(), ustrlen(glbl.GetLocalHostName()));
MsgSetRcvFrom(pMsg, glbl.GetLocalHostNameProp());
MsgSetRcvFromIP(pMsg, glbl.GetLocalHostIP());
MsgSetMSGoffs(pMsg, 0);
MsgSetFlowControlType(pMsg, eFLOWCTL_NO_DELAY);
MsgSetRuleset(pMsg, pollerData->ruleset);
pMsg->msgFlags = NEEDS_PARSING | PARSE_HOSTNAME;
submitMsg2(pMsg);
}
/* gotta free the string returned from zstr_recv() */
free(buf);
if( pollerData->thread->bShallStop == TRUE) {
/* a handler that returns -1 will terminate the
czmq reactor loop
*/
return -1;
}
return 0;
}
/* called when runInput is called by rsyslog
*/
static rsRetVal rcv_loop(thrdInfo_t* pThrd){
size_t n_items = 0;
size_t i;
int rv;
zmq_pollitem_t* items = NULL;
poller_data* pollerData = NULL;
struct lstn_s* current;
instanceConf_t* inst;
DEFiRet;
/* now add listeners. This actually creates the sockets, etc... */
for (inst = runModConf->root; inst != NULL; inst=inst->next) {
addListener(inst);
}
if (lcnfRoot == NULL) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: no listeners were "
"started, input not activated.\n");
ABORT_FINALIZE(RS_RET_NO_RUN);
}
/* count the # of items first */
for(current=lcnfRoot;current!=NULL;current=current->next)
n_items++;
/* make arrays of pollitems, pollerdata so they are easy to delete later */
/* create the poll items*/
CHKmalloc(items = (zmq_pollitem_t*)MALLOC(sizeof(zmq_pollitem_t)*n_items));
/* create poller data (stuff to pass into the zmq closure called when we get a message)*/
CHKmalloc(pollerData = (poller_data*)MALLOC(sizeof(poller_data)*n_items));
/* loop through and initialize the poll items and poller_data arrays...*/
for(i=0, current = lcnfRoot; current != NULL; current = current->next, i++) {
/* create the socket, update items.*/
items[i].socket=current->sock;
items[i].events = ZMQ_POLLIN;
/* now update the poller_data for this item */
pollerData[i].thread = pThrd;
pollerData[i].ruleset = current->pRuleset;
}
s_zloop = zloop_new();
for(i=0; i<n_items; ++i) {
rv = zloop_poller(s_zloop, &items[i], handlePoll, &pollerData[i]);
if (rv) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: zloop_poller failed for item %zu: %s", i, zmq_strerror(errno));
}
}
DBGPRINTF("imzmq3: zloop_poller starting...");
zloop_start(s_zloop);
zloop_destroy(&s_zloop);
DBGPRINTF("imzmq3: zloop_poller stopped.");
finalize_it:
zctx_destroy(&s_context);
free(items);
free(pollerData);
RETiRet;
}
/* ----------------------------------------------------------------------------
* input module functions
*/
BEGINrunInput
CODESTARTrunInput
CHKiRet(rcv_loop(pThrd));
finalize_it:
RETiRet;
ENDrunInput
/* initialize and return if will run or not */
BEGINwillRun
CODESTARTwillRun
/* we need to create the inputName property (only once during our
lifetime) */
CHKiRet(prop.Construct(&s_namep));
CHKiRet(prop.SetString(s_namep,
UCHAR_CONSTANT("imzmq3"),
sizeof("imzmq3") - 1));
CHKiRet(prop.ConstructFinalize(s_namep));
finalize_it:
ENDwillRun
BEGINafterRun
CODESTARTafterRun
/* do cleanup here */
if (s_namep != NULL)
prop.Destruct(&s_namep);
ENDafterRun
BEGINmodExit
CODESTARTmodExit
/* release what we no longer need */
objRelease(errmsg, CORE_COMPONENT);
objRelease(glbl, CORE_COMPONENT);
objRelease(prop, CORE_COMPONENT);
objRelease(ruleset, CORE_COMPONENT);
ENDmodExit
BEGINisCompatibleWithFeature
CODESTARTisCompatibleWithFeature
if (eFeat == sFEATURENonCancelInputTermination)
iRet = RS_RET_OK;
ENDisCompatibleWithFeature
BEGINbeginCnfLoad
CODESTARTbeginCnfLoad
/* After endCnfLoad() (BEGINendCnfLoad...ENDendCnfLoad) is called,
* the pModConf pointer must not be used to change the in-memory
* config object. It's safe to use the same pointer for accessing
* the config object until freeCnf() (BEGINfreeCnf...ENDfreeCnf). */
runModConf = pModConf;
runModConf->pConf = pConf;
/* init module config */
runModConf->io_threads = 0; /* 0 means don't set it */
ENDbeginCnfLoad
BEGINsetModCnf
struct cnfparamvals* pvals = NULL;
int i;
CODESTARTsetModCnf
pvals = nvlstGetParams(lst, &modpblk, NULL);
if (NULL == pvals) {
errmsg.LogError(0, RS_RET_MISSING_CNFPARAMS, "imzmq3: error processing module "
" config parameters ['module(...)']");
ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
}
for (i=0; i < modpblk.nParams; ++i) {
if (!pvals[i].bUsed)
continue;
if (!strcmp(modpblk.descr[i].name, "ioThreads")) {
runModConf->io_threads = (int)pvals[i].val.d.n;
} else {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"imzmq3: config error, unknown "
"param %s in setModCnf\n",
modpblk.descr[i].name);
}
}
finalize_it:
if (pvals != NULL)
cnfparamvalsDestruct(pvals, &modpblk);
ENDsetModCnf
BEGINendCnfLoad
CODESTARTendCnfLoad
/* Last chance to make changes to the in-memory config object for this
* input module. After this call, the config object must no longer be
* changed. */
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
assert(pModConf == runModConf);
ENDendCnfLoad
/* function to generate error message if framework does not find requested ruleset */
static inline void
std_checkRuleset_genErrMsg(__attribute__((unused)) modConfData_t *modConf, instanceConf_t *inst)
{
errmsg.LogError(0, NO_ERRCODE, "imzmq3: ruleset '%s' for socket %s not found - "
"using default ruleset instead", inst->pszBindRuleset,
inst->description);
}
BEGINcheckCnf
instanceConf_t* inst;
CODESTARTcheckCnf
for(inst = pModConf->root; inst!=NULL; inst=inst->next) {
std_checkRuleset(pModConf, inst);
/* now, validate the instanceConf */
CHKiRet(validateConfig(inst));
}
finalize_it:
RETiRet;
ENDcheckCnf
BEGINactivateCnfPrePrivDrop
CODESTARTactivateCnfPrePrivDrop
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
assert(pModConf == runModConf);
/* first create the context */
createContext();
/* could setup context here, and set the global worker threads
and so on... */
ENDactivateCnfPrePrivDrop
BEGINactivateCnf
CODESTARTactivateCnf
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
assert(pModConf == runModConf);
ENDactivateCnf
BEGINfreeCnf
struct lstn_s *lstn, *lstn_r;
instanceConf_t *inst, *inst_r;
sublist *sub, *sub_r;
CODESTARTfreeCnf
DBGPRINTF("imzmq3: BEGINfreeCnf ...\n");
if (pModConf != runModConf) {
errmsg.LogError(0, NO_ERRCODE, "imzmq3: pointer of in-memory config object has "
"changed - pModConf=%p, runModConf=%p", pModConf, runModConf);
}
for (lstn = lcnfRoot; lstn != NULL; ) {
lstn_r = lstn;
lstn = lstn_r->next;
free(lstn_r);
}
for (inst = pModConf->root ; inst != NULL ; ) {
for (sub = inst->subscriptions; sub != NULL; ) {
free(sub->subscribe);
sub_r = sub;
sub = sub_r->next;
free(sub_r);
}
free(inst->pszBindRuleset);
inst_r = inst;
inst = inst->next;
free(inst_r);
}
ENDfreeCnf
BEGINnewInpInst
struct cnfparamvals* pvals;
CODESTARTnewInpInst
DBGPRINTF("newInpInst (imzmq3)\n");
pvals = nvlstGetParams(lst, &inppblk, NULL);
if(NULL==pvals) {
errmsg.LogError(0, RS_RET_MISSING_CNFPARAMS,
"imzmq3: required parameters are missing\n");
ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
}
DBGPRINTF("imzmq3: input param blk:\n");
cnfparamsPrint(&inppblk, pvals);
/* now, parse the config params and so on... */
CHKiRet(createListener(pvals));
finalize_it:
CODE_STD_FINALIZERnewInpInst
cnfparamvalsDestruct(pvals, &inppblk);
ENDnewInpInst
BEGINqueryEtryPt
CODESTARTqueryEtryPt
CODEqueryEtryPt_STD_IMOD_QUERIES
CODEqueryEtryPt_STD_CONF2_QUERIES
CODEqueryEtryPt_STD_CONF2_setModCnf_QUERIES
CODEqueryEtryPt_STD_CONF2_PREPRIVDROP_QUERIES
CODEqueryEtryPt_STD_CONF2_IMOD_QUERIES
CODEqueryEtryPt_IsCompatibleWithFeature_IF_OMOD_QUERIES
ENDqueryEtryPt
BEGINmodInit()
CODESTARTmodInit
/* we only support the current interface specification */
*ipIFVersProvided = CURR_MOD_IF_VERSION;
CODEmodInit_QueryRegCFSLineHdlr
CHKiRet(objUse(errmsg, CORE_COMPONENT));
CHKiRet(objUse(glbl, CORE_COMPONENT));
CHKiRet(objUse(prop, CORE_COMPONENT));
CHKiRet(objUse(ruleset, CORE_COMPONENT));
ENDmodInit
| ./CrossVul/dataset_final_sorted/CWE-134/c/good_2610_0 |
crossvul-cpp_data_bad_3455_0 | /* vi:set et ai sw=2 sts=2 ts=2: */
/*-
* Copyright (c) 2005-2007 Benedikt Meurer <benny@xfce.org>
* Copyright (c) 2009-2011 Jannis Pohlmann <jannis@xfce.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <gio/gio.h>
#include <thunar/thunar-application.h>
#include <thunar/thunar-gio-extensions.h>
#include <thunar/thunar-io-scan-directory.h>
#include <thunar/thunar-io-jobs-util.h>
#include <thunar/thunar-job.h>
#include <thunar/thunar-private.h>
#include <thunar/thunar-thumbnail-cache.h>
#include <thunar/thunar-transfer-job.h>
typedef struct _ThunarTransferNode ThunarTransferNode;
static void thunar_transfer_job_finalize (GObject *object);
static gboolean thunar_transfer_job_execute (ExoJob *job,
GError **error);
static void thunar_transfer_node_free (ThunarTransferNode *node);
struct _ThunarTransferJobClass
{
ThunarJobClass __parent__;
};
struct _ThunarTransferJob
{
ThunarJob __parent__;
ThunarTransferJobType type;
GList *source_node_list;
GList *target_file_list;
guint64 total_size;
guint64 total_progress;
guint64 file_progress;
gdouble previous_percentage;
};
struct _ThunarTransferNode
{
ThunarTransferNode *next;
ThunarTransferNode *children;
GFile *source_file;
};
G_DEFINE_TYPE (ThunarTransferJob, thunar_transfer_job, THUNAR_TYPE_JOB)
static void
thunar_transfer_job_class_init (ThunarTransferJobClass *klass)
{
GObjectClass *gobject_class;
ExoJobClass *exojob_class;
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = thunar_transfer_job_finalize;
exojob_class = EXO_JOB_CLASS (klass);
exojob_class->execute = thunar_transfer_job_execute;
}
static void
thunar_transfer_job_init (ThunarTransferJob *job)
{
job->type = 0;
job->source_node_list = NULL;
job->target_file_list = NULL;
job->total_size = 0;
job->total_progress = 0;
job->file_progress = 0;
job->previous_percentage = 0.0;
}
static void
thunar_transfer_job_finalize (GObject *object)
{
ThunarTransferJob *job = THUNAR_TRANSFER_JOB (object);
g_list_foreach (job->source_node_list, (GFunc) thunar_transfer_node_free, NULL);
g_list_free (job->source_node_list);
thunar_g_file_list_free (job->target_file_list);
(*G_OBJECT_CLASS (thunar_transfer_job_parent_class)->finalize) (object);
}
static void
thunar_transfer_job_progress (goffset current_num_bytes,
goffset total_num_bytes,
gpointer user_data)
{
guint64 new_percentage;
ThunarTransferJob *job = user_data;
_thunar_return_if_fail (THUNAR_IS_TRANSFER_JOB (job));
if (G_LIKELY (job->total_size > 0))
{
/* update total progress */
job->total_progress += (current_num_bytes - job->file_progress);
/* update file progress */
job->file_progress = current_num_bytes;
/* compute the new percentage after the progress we've made */
new_percentage = (job->total_progress * 100.0) / job->total_size;
/* notify callers about the progress only if we have advanced by
* at least 0.01 percent since the last signal emission */
if (new_percentage >= (job->previous_percentage + 0.01))
{
/* emit the percent signal */
exo_job_percent (EXO_JOB (job), new_percentage);
/* remember the percentage */
job->previous_percentage = new_percentage;
}
}
}
static gboolean
thunar_transfer_job_collect_node (ThunarTransferJob *job,
ThunarTransferNode *node,
GError **error)
{
ThunarTransferNode *child_node;
GFileInfo *info;
GError *err = NULL;
GList *file_list;
GList *lp;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), FALSE);
_thunar_return_val_if_fail (node != NULL && G_IS_FILE (node->source_file), FALSE);
_thunar_return_val_if_fail (error == NULL || *error == NULL, FALSE);
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
info = g_file_query_info (node->source_file,
G_FILE_ATTRIBUTE_STANDARD_SIZE ","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
if (G_UNLIKELY (info == NULL))
return FALSE;
job->total_size += g_file_info_get_size (info);
/* check if we have a directory here */
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
/* scan the directory for immediate children */
file_list = thunar_io_scan_directory (THUNAR_JOB (job), node->source_file,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
FALSE, FALSE, &err);
/* add children to the transfer node */
for (lp = file_list; err == NULL && lp != NULL; lp = lp->next)
{
/* allocate a new transfer node for the child */
child_node = g_slice_new0 (ThunarTransferNode);
child_node->source_file = g_object_ref (lp->data);
/* hook the child node into the child list */
child_node->next = node->children;
node->children = child_node;
/* collect the child node */
thunar_transfer_job_collect_node (job, child_node, &err);
}
/* release the child files */
thunar_g_file_list_free (file_list);
}
/* release file info */
g_object_unref (info);
if (G_UNLIKELY (err != NULL))
{
g_propagate_error (error, err);
return FALSE;
}
return TRUE;
}
static gboolean
ttj_copy_file (ThunarTransferJob *job,
GFile *source_file,
GFile *target_file,
GFileCopyFlags copy_flags,
gboolean merge_directories,
GError **error)
{
GFileType source_type;
GFileType target_type;
gboolean target_exists;
GError *err = NULL;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), FALSE);
_thunar_return_val_if_fail (G_IS_FILE (source_file), FALSE);
_thunar_return_val_if_fail (G_IS_FILE (target_file), FALSE);
_thunar_return_val_if_fail (error == NULL || *error == NULL, FALSE);
/* reset the file progress */
job->file_progress = 0;
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
source_type = g_file_query_file_type (source_file, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)));
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
target_type = g_file_query_file_type (target_file, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)));
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return FALSE;
/* check if the target is a symlink and we are in overwrite mode */
if (target_type == G_FILE_TYPE_SYMBOLIC_LINK && (copy_flags & G_FILE_COPY_OVERWRITE) != 0)
{
/* try to delete the symlink */
if (!g_file_delete (target_file, exo_job_get_cancellable (EXO_JOB (job)), &err))
{
g_propagate_error (error, err);
return FALSE;
}
}
/* try to copy the file */
g_file_copy (source_file, target_file, copy_flags,
exo_job_get_cancellable (EXO_JOB (job)),
thunar_transfer_job_progress, job, &err);
/* check if there were errors */
if (G_UNLIKELY (err != NULL && err->domain == G_IO_ERROR))
{
if (err->code == G_IO_ERROR_WOULD_MERGE
|| (err->code == G_IO_ERROR_EXISTS
&& source_type == G_FILE_TYPE_DIRECTORY
&& target_type == G_FILE_TYPE_DIRECTORY))
{
/* we tried to overwrite a directory with a directory. this normally results
* in a merge. ignore the error if we actually *want* to merge */
if (merge_directories)
g_clear_error (&err);
}
else if (err->code == G_IO_ERROR_WOULD_RECURSE)
{
g_clear_error (&err);
/* we tried to copy a directory and either
*
* - the target did not exist which means we simple have to
* create the target directory
*
* or
*
* - the target is not a directory and we tried to overwrite it in
* which case we have to delete it first and then create the target
* directory
*/
/* check if the target file exists */
target_exists = g_file_query_exists (target_file,
exo_job_get_cancellable (EXO_JOB (job)));
/* abort on cancellation, continue otherwise */
if (!exo_job_set_error_if_cancelled (EXO_JOB (job), &err))
{
if (target_exists)
{
/* the target still exists and thus is not a directory. try to remove it */
g_file_delete (target_file,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
}
/* abort on error or cancellation, continue otherwise */
if (err == NULL)
{
/* now try to create the directory */
g_file_make_directory (target_file,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
}
}
}
}
if (G_UNLIKELY (err != NULL))
{
g_propagate_error (error, err);
return FALSE;
}
else
{
return TRUE;
}
}
/**
* thunar_transfer_job_copy_file:
* @job : a #ThunarTransferJob.
* @source_file : the source #GFile to copy.
* @target_file : the destination #GFile to copy to.
* @error : return location for errors or %NULL.
*
* Tries to copy @source_file to @target_file. The real destination is the
* return value and may differ from @target_file (e.g. if you try to copy
* the file "/foo/bar" into the same directory you'll end up with something
* like "/foo/copy of bar" instead of "/foo/bar".
*
* The return value is guaranteed to be %NULL on errors and @error will
* always be set in those cases. If the file is skipped, the return value
* will be @source_file.
*
* Return value: the destination #GFile to which @source_file was copied
* or linked. The caller is reposible to release it with
* g_object_unref() if no longer needed. It points to
* @source_file if the file was skipped and will be %NULL
* on error or cancellation.
**/
static GFile *
thunar_transfer_job_copy_file (ThunarTransferJob *job,
GFile *source_file,
GFile *target_file,
GError **error)
{
ThunarJobResponse response;
GFileCopyFlags copy_flags = G_FILE_COPY_NOFOLLOW_SYMLINKS;
GError *err = NULL;
gint n;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), NULL);
_thunar_return_val_if_fail (G_IS_FILE (source_file), NULL);
_thunar_return_val_if_fail (G_IS_FILE (target_file), NULL);
_thunar_return_val_if_fail (error == NULL || *error == NULL, NULL);
/* abort on cancellation */
if (exo_job_set_error_if_cancelled (EXO_JOB (job), error))
return NULL;
/* various attempts to copy the file */
while (err == NULL)
{
if (G_LIKELY (!g_file_equal (source_file, target_file)))
{
/* try to copy the file from source_file to the target_file */
if (ttj_copy_file (job, source_file, target_file, copy_flags, TRUE, &err))
{
/* return the real target file */
return g_object_ref (target_file);
}
}
else
{
for (n = 1; err == NULL; ++n)
{
GFile *duplicate_file = thunar_io_jobs_util_next_duplicate_file (THUNAR_JOB (job),
source_file,
TRUE, n,
&err);
if (err == NULL)
{
/* try to copy the file from source file to the duplicate file */
if (ttj_copy_file (job, source_file, duplicate_file, copy_flags, TRUE, &err))
{
/* return the real target file */
return duplicate_file;
}
g_object_unref (duplicate_file);
}
if (err != NULL && err->domain == G_IO_ERROR && err->code == G_IO_ERROR_EXISTS)
{
/* this duplicate already exists => clear the error to try the next alternative */
g_clear_error (&err);
}
}
}
/* check if we can recover from this error */
if (err->domain == G_IO_ERROR && err->code == G_IO_ERROR_EXISTS)
{
/* reset the error */
g_clear_error (&err);
/* ask the user whether to replace the target file */
response = thunar_job_ask_replace (THUNAR_JOB (job), source_file,
target_file, &err);
if (err != NULL)
break;
/* check if we should retry */
if (response == THUNAR_JOB_RESPONSE_RETRY)
continue;
/* add overwrite flag and retry if we should overwrite */
if (response == THUNAR_JOB_RESPONSE_YES)
{
copy_flags |= G_FILE_COPY_OVERWRITE;
continue;
}
/* tell the caller we skipped the file if the user
* doesn't want to retry/overwrite */
if (response == THUNAR_JOB_RESPONSE_NO)
return g_object_ref (source_file);
}
}
_thunar_assert (err != NULL);
g_propagate_error (error, err);
return NULL;
}
static void
thunar_transfer_job_copy_node (ThunarTransferJob *job,
ThunarTransferNode *node,
GFile *target_file,
GFile *target_parent_file,
GList **target_file_list_return,
GError **error)
{
ThunarThumbnailCache *thumbnail_cache;
ThunarApplication *application;
ThunarJobResponse response;
GFileInfo *info;
GError *err = NULL;
GFile *real_target_file = NULL;
gchar *base_name;
_thunar_return_if_fail (THUNAR_IS_TRANSFER_JOB (job));
_thunar_return_if_fail (node != NULL && G_IS_FILE (node->source_file));
_thunar_return_if_fail (target_file == NULL || node->next == NULL);
_thunar_return_if_fail ((target_file == NULL && target_parent_file != NULL) || (target_file != NULL && target_parent_file == NULL));
_thunar_return_if_fail (error == NULL || *error == NULL);
/* The caller can either provide a target_file or a target_parent_file, but not both. The toplevel
* transfer_nodes (for which next is NULL) should be called with target_file, to get proper behavior
* wrt restoring files from the trash. Other transfer_nodes will be called with target_parent_file.
*/
/* take a reference on the thumbnail cache */
application = thunar_application_get ();
thumbnail_cache = thunar_application_get_thumbnail_cache (application);
g_object_unref (application);
for (; err == NULL && node != NULL; node = node->next)
{
/* guess the target file for this node (unless already provided) */
if (G_LIKELY (target_file == NULL))
{
base_name = g_file_get_basename (node->source_file);
target_file = g_file_get_child (target_parent_file, base_name);
g_free (base_name);
}
else
target_file = g_object_ref (target_file);
/* query file info */
info = g_file_query_info (node->source_file,
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (EXO_JOB (job)),
&err);
/* abort on error or cancellation */
if (info == NULL)
{
g_object_unref (target_file);
break;
}
/* update progress information */
exo_job_info_message (EXO_JOB (job), g_file_info_get_display_name (info));
retry_copy:
/* copy the item specified by this node (not recursively) */
real_target_file = thunar_transfer_job_copy_file (job, node->source_file,
target_file, &err);
if (G_LIKELY (real_target_file != NULL))
{
/* node->source_file == real_target_file means to skip the file */
if (G_LIKELY (node->source_file != real_target_file))
{
/* notify the thumbnail cache of the copy operation */
thunar_thumbnail_cache_copy_file (thumbnail_cache,
node->source_file,
real_target_file);
/* check if we have children to copy */
if (node->children != NULL)
{
/* copy all children of this node */
thunar_transfer_job_copy_node (job, node->children, NULL, real_target_file, NULL, &err);
/* free resources allocted for the children */
thunar_transfer_node_free (node->children);
node->children = NULL;
}
/* check if the child copy failed */
if (G_UNLIKELY (err != NULL))
{
/* outa here, freeing the target paths */
g_object_unref (real_target_file);
g_object_unref (target_file);
break;
}
/* add the real target file to the return list */
if (G_LIKELY (target_file_list_return != NULL))
{
*target_file_list_return =
thunar_g_file_list_prepend (*target_file_list_return,
real_target_file);
}
retry_remove:
/* try to remove the source directory if we are on copy+remove fallback for move */
if (job->type == THUNAR_TRANSFER_JOB_MOVE)
{
if (g_file_delete (node->source_file,
exo_job_get_cancellable (EXO_JOB (job)),
&err))
{
/* notify the thumbnail cache of the delete operation */
thunar_thumbnail_cache_delete_file (thumbnail_cache,
node->source_file);
}
else
{
/* ask the user to retry */
response = thunar_job_ask_skip (THUNAR_JOB (job), "%s",
err->message);
/* reset the error */
g_clear_error (&err);
/* check whether to retry */
if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY))
goto retry_remove;
}
}
}
g_object_unref (real_target_file);
}
else if (err != NULL)
{
/* we can only skip if there is space left on the device */
if (err->domain != G_IO_ERROR || err->code != G_IO_ERROR_NO_SPACE)
{
/* ask the user to skip this node and all subnodes */
response = thunar_job_ask_skip (THUNAR_JOB (job), "%s", err->message);
/* reset the error */
g_clear_error (&err);
/* check whether to retry */
if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_RETRY))
goto retry_copy;
}
}
/* release the guessed target file */
g_object_unref (target_file);
target_file = NULL;
/* release file info */
g_object_unref (info);
}
/* release the thumbnail cache */
g_object_unref (thumbnail_cache);
/* propagate error if we failed or the job was cancelled */
if (G_UNLIKELY (err != NULL))
g_propagate_error (error, err);
}
static gboolean
thunar_transfer_job_execute (ExoJob *job,
GError **error)
{
ThunarThumbnailCache *thumbnail_cache;
ThunarTransferNode *node;
ThunarApplication *application;
ThunarJobResponse response;
ThunarTransferJob *transfer_job = THUNAR_TRANSFER_JOB (job);
GFileInfo *info;
gboolean parent_exists;
GError *err = NULL;
GList *new_files_list = NULL;
GList *snext;
GList *sp;
GList *tnext;
GList *tp;
GFile *target_parent;
gchar *base_name;
gchar *parent_display_name;
_thunar_return_val_if_fail (THUNAR_IS_TRANSFER_JOB (job), FALSE);
_thunar_return_val_if_fail (error == NULL || *error == NULL, FALSE);
if (exo_job_set_error_if_cancelled (job, error))
return FALSE;
exo_job_info_message (job, _("Collecting files..."));
/* take a reference on the thumbnail cache */
application = thunar_application_get ();
thumbnail_cache = thunar_application_get_thumbnail_cache (application);
g_object_unref (application);
for (sp = transfer_job->source_node_list, tp = transfer_job->target_file_list;
sp != NULL && tp != NULL && err == NULL;
sp = snext, tp = tnext)
{
/* determine the next list items */
snext = sp->next;
tnext = tp->next;
/* determine the current source transfer node */
node = sp->data;
info = g_file_query_info (node->source_file,
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
exo_job_get_cancellable (job),
&err);
if (G_UNLIKELY (info == NULL))
break;
/* check if we are moving a file out of the trash */
if (transfer_job->type == THUNAR_TRANSFER_JOB_MOVE
&& thunar_g_file_is_trashed (node->source_file))
{
/* update progress information */
exo_job_info_message (job, _("Trying to restore \"%s\""),
g_file_info_get_display_name (info));
/* determine the parent file */
target_parent = g_file_get_parent (tp->data);
/* check if the parent exists */
if (target_parent != NULL)
parent_exists = g_file_query_exists (target_parent, exo_job_get_cancellable (job));
/* abort on cancellation */
if (exo_job_set_error_if_cancelled (job, &err))
{
g_object_unref (target_parent);
break;
}
if (target_parent != NULL && !parent_exists)
{
/* determine the display name of the parent */
base_name = g_file_get_basename (target_parent);
parent_display_name = g_filename_display_name (base_name);
g_free (base_name);
/* ask the user whether he wants to create the parent folder because its gone */
response = thunar_job_ask_create (THUNAR_JOB (job),
_("The folder \"%s\" does not exist anymore but is "
"required to restore the file \"%s\" from the "
"trash"),
parent_display_name,
g_file_info_get_display_name (info));
/* abort if cancelled */
if (G_UNLIKELY (response == THUNAR_JOB_RESPONSE_CANCEL))
{
g_object_unref (target_parent);
g_free (parent_display_name);
break;
}
/* try to create the parent directory */
if (!g_file_make_directory_with_parents (target_parent,
exo_job_get_cancellable (job),
&err))
{
if (!exo_job_is_cancelled (job))
{
g_clear_error (&err);
/* overwrite the internal GIO error with something more user-friendly */
g_set_error (&err, G_IO_ERROR, G_IO_ERROR_FAILED,
_("Failed to restore the folder \"%s\""),
parent_display_name);
}
g_object_unref (target_parent);
g_free (parent_display_name);
break;
}
/* clean up */
g_free (parent_display_name);
}
if (target_parent != NULL)
g_object_unref (target_parent);
}
if (transfer_job->type == THUNAR_TRANSFER_JOB_MOVE)
{
/* update progress information */
exo_job_info_message (job, _("Trying to move \"%s\""),
g_file_info_get_display_name (info));
if (g_file_move (node->source_file, tp->data,
G_FILE_COPY_NOFOLLOW_SYMLINKS
| G_FILE_COPY_NO_FALLBACK_FOR_MOVE,
exo_job_get_cancellable (job),
NULL, NULL, &err))
{
/* notify the thumbnail cache of the move operation */
thunar_thumbnail_cache_move_file (thumbnail_cache,
node->source_file,
tp->data);
/* add the target file to the new files list */
new_files_list = thunar_g_file_list_prepend (new_files_list, tp->data);
/* release source and target files */
thunar_transfer_node_free (node);
g_object_unref (tp->data);
/* drop the matching list items */
transfer_job->source_node_list = g_list_delete_link (transfer_job->source_node_list, sp);
transfer_job->target_file_list = g_list_delete_link (transfer_job->target_file_list, tp);
}
else if (!exo_job_is_cancelled (job))
{
g_clear_error (&err);
/* update progress information */
exo_job_info_message (job, _("Could not move \"%s\" directly. "
"Collecting files for copying..."),
g_file_info_get_display_name (info));
if (!thunar_transfer_job_collect_node (transfer_job, node, &err))
{
/* failed to collect, cannot continue */
g_object_unref (info);
break;
}
}
}
else if (transfer_job->type == THUNAR_TRANSFER_JOB_COPY)
{
if (!thunar_transfer_job_collect_node (THUNAR_TRANSFER_JOB (job), node, &err))
break;
}
g_object_unref (info);
}
/* release the thumbnail cache */
g_object_unref (thumbnail_cache);
/* continue if there were no errors yet */
if (G_LIKELY (err == NULL))
{
/* perform the copy recursively for all source transfer nodes */
for (sp = transfer_job->source_node_list, tp = transfer_job->target_file_list;
sp != NULL && tp != NULL && err == NULL;
sp = sp->next, tp = tp->next)
{
thunar_transfer_job_copy_node (transfer_job, sp->data, tp->data, NULL,
&new_files_list, &err);
}
}
/* check if we failed */
if (G_UNLIKELY (err != NULL))
{
g_propagate_error (error, err);
return FALSE;
}
else
{
thunar_job_new_files (THUNAR_JOB (job), new_files_list);
thunar_g_file_list_free (new_files_list);
return TRUE;
}
}
static void
thunar_transfer_node_free (ThunarTransferNode *node)
{
ThunarTransferNode *next;
/* free all nodes in a row */
while (node != NULL)
{
/* free all children of this node */
thunar_transfer_node_free (node->children);
/* determine the next node */
next = node->next;
/* drop the source file of this node */
g_object_unref (node->source_file);
/* release the resources of this node */
g_slice_free (ThunarTransferNode, node);
/* continue with the next node */
node = next;
}
}
ThunarJob *
thunar_transfer_job_new (GList *source_node_list,
GList *target_file_list,
ThunarTransferJobType type)
{
ThunarTransferNode *node;
ThunarTransferJob *job;
GList *sp;
GList *tp;
_thunar_return_val_if_fail (source_node_list != NULL, NULL);
_thunar_return_val_if_fail (target_file_list != NULL, NULL);
_thunar_return_val_if_fail (g_list_length (source_node_list) == g_list_length (target_file_list), NULL);
job = g_object_new (THUNAR_TYPE_TRANSFER_JOB, NULL);
job->type = type;
/* add a transfer node for each source path and a matching target parent path */
for (sp = source_node_list, tp = target_file_list;
sp != NULL;
sp = sp->next, tp = tp->next)
{
/* make sure we don't transfer root directories. this should be prevented in the GUI */
if (G_UNLIKELY (thunar_g_file_is_root (sp->data) || thunar_g_file_is_root (tp->data)))
continue;
/* only process non-equal pairs unless we're copying */
if (G_LIKELY (type != THUNAR_TRANSFER_JOB_MOVE || !g_file_equal (sp->data, tp->data)))
{
/* append transfer node for this source file */
node = g_slice_new0 (ThunarTransferNode);
node->source_file = g_object_ref (sp->data);
job->source_node_list = g_list_append (job->source_node_list, node);
/* append target file */
job->target_file_list = thunar_g_file_list_append (job->target_file_list, tp->data);
}
}
/* make sure we didn't mess things up */
_thunar_assert (g_list_length (job->source_node_list) == g_list_length (job->target_file_list));
return THUNAR_JOB (job);
}
| ./CrossVul/dataset_final_sorted/CWE-134/c/bad_3455_0 |
crossvul-cpp_data_good_2266_0 | /****************************************************************************
* RRDtool 1.4.8 Copyright by Tobi Oetiker, 1997-2013
****************************************************************************
* rrd__graph.c produce graphs from data in rrdfiles
****************************************************************************/
#include <sys/stat.h>
#include <glib.h> // will use regex
#ifdef WIN32
#include "strftime.h"
#endif
#include "rrd_tool.h"
/* for basename */
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#else
#include "plbasename.h"
#endif
#if defined(WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
#include <io.h>
#include <fcntl.h>
#endif
#include <time.h>
#include <locale.h>
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#include "rrd_graph.h"
#include "rrd_client.h"
/* some constant definitions */
#ifndef RRD_DEFAULT_FONT
/* there is special code later to pick Cour.ttf when running on windows */
#define RRD_DEFAULT_FONT "DejaVu Sans Mono,Bitstream Vera Sans Mono,monospace,Courier"
#endif
text_prop_t text_prop[] = {
{8.0, RRD_DEFAULT_FONT,NULL}
, /* default */
{9.0, RRD_DEFAULT_FONT,NULL}
, /* title */
{7.0, RRD_DEFAULT_FONT,NULL}
, /* axis */
{8.0, RRD_DEFAULT_FONT,NULL}
, /* unit */
{8.0, RRD_DEFAULT_FONT,NULL} /* legend */
,
{5.5, RRD_DEFAULT_FONT,NULL} /* watermark */
};
xlab_t xlab[] = {
{0, 0, TMT_SECOND, 30, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{2, 0, TMT_MINUTE, 1, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{5, 0, TMT_MINUTE, 2, TMT_MINUTE, 10, TMT_MINUTE, 10, 0, "%H:%M"}
,
{10, 0, TMT_MINUTE, 5, TMT_MINUTE, 20, TMT_MINUTE, 20, 0, "%H:%M"}
,
{30, 0, TMT_MINUTE, 10, TMT_HOUR, 1, TMT_HOUR, 1, 0, "%H:%M"}
,
{60, 0, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 2, 0, "%H:%M"}
,
{60, 24 * 3600, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 6, 0, "%a %H:%M"}
,
{180, 0, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 6, 0, "%H:%M"}
,
{180, 24 * 3600, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 12, 0, "%a %H:%M"}
,
/*{300, 0, TMT_HOUR,3, TMT_HOUR,12, TMT_HOUR,12, 12*3600,"%a %p"}, this looks silly */
{600, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%a"}
,
{1200, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%d"}
,
{1800, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a %d"}
,
{2400, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a"}
,
{3600, 0, TMT_DAY, 1, TMT_WEEK, 1, TMT_WEEK, 1, 7 * 24 * 3600, "Week %V"}
,
{3 * 3600, 0, TMT_WEEK, 1, TMT_MONTH, 1, TMT_WEEK, 2, 7 * 24 * 3600, "Week %V"}
,
{6 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 1, TMT_MONTH, 1, 30 * 24 * 3600,
"%b"}
,
{48 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 3, TMT_MONTH, 3, 30 * 24 * 3600,
"%b"}
,
{315360, 0, TMT_MONTH, 3, TMT_YEAR, 1, TMT_YEAR, 1, 365 * 24 * 3600, "%Y"}
,
{10 * 24 * 3600, 0, TMT_YEAR, 1, TMT_YEAR, 1, TMT_YEAR, 1,
365 * 24 * 3600, "%y"}
,
{-1, 0, TMT_MONTH, 0, TMT_MONTH, 0, TMT_MONTH, 0, 0, ""}
};
/* sensible y label intervals ...*/
ylab_t ylab[] = {
{0.1, {1, 2, 5, 10}
}
,
{0.2, {1, 5, 10, 20}
}
,
{0.5, {1, 2, 4, 10}
}
,
{1.0, {1, 2, 5, 10}
}
,
{2.0, {1, 5, 10, 20}
}
,
{5.0, {1, 2, 4, 10}
}
,
{10.0, {1, 2, 5, 10}
}
,
{20.0, {1, 5, 10, 20}
}
,
{50.0, {1, 2, 4, 10}
}
,
{100.0, {1, 2, 5, 10}
}
,
{200.0, {1, 5, 10, 20}
}
,
{500.0, {1, 2, 4, 10}
}
,
{0.0, {0, 0, 0, 0}
}
};
gfx_color_t graph_col[] = /* default colors */
{
{1.00, 1.00, 1.00, 1.00}, /* canvas */
{0.95, 0.95, 0.95, 1.00}, /* background */
{0.81, 0.81, 0.81, 1.00}, /* shade A */
{0.62, 0.62, 0.62, 1.00}, /* shade B */
{0.56, 0.56, 0.56, 0.75}, /* grid */
{0.87, 0.31, 0.31, 0.60}, /* major grid */
{0.00, 0.00, 0.00, 1.00}, /* font */
{0.50, 0.12, 0.12, 1.00}, /* arrow */
{0.12, 0.12, 0.12, 1.00}, /* axis */
{0.00, 0.00, 0.00, 1.00} /* frame */
};
/* #define DEBUG */
#ifdef DEBUG
# define DPRINT(x) (void)(printf x, printf("\n"))
#else
# define DPRINT(x)
#endif
/* initialize with xtr(im,0); */
int xtr(
image_desc_t *im,
time_t mytime)
{
static double pixie;
if (mytime == 0) {
pixie = (double) im->xsize / (double) (im->end - im->start);
return im->xorigin;
}
return (int) ((double) im->xorigin + pixie * (mytime - im->start));
}
/* translate data values into y coordinates */
double ytr(
image_desc_t *im,
double value)
{
static double pixie;
double yval;
if (isnan(value)) {
if (!im->logarithmic)
pixie = (double) im->ysize / (im->maxval - im->minval);
else
pixie =
(double) im->ysize / (log10(im->maxval) - log10(im->minval));
yval = im->yorigin;
} else if (!im->logarithmic) {
yval = im->yorigin - pixie * (value - im->minval);
} else {
if (value < im->minval) {
yval = im->yorigin;
} else {
yval = im->yorigin - pixie * (log10(value) - log10(im->minval));
}
}
return yval;
}
/* conversion function for symbolic entry names */
#define conv_if(VV,VVV) \
if (strcmp(#VV, string) == 0) return VVV ;
enum gf_en gf_conv(
char *string)
{
conv_if(PRINT, GF_PRINT);
conv_if(GPRINT, GF_GPRINT);
conv_if(COMMENT, GF_COMMENT);
conv_if(HRULE, GF_HRULE);
conv_if(VRULE, GF_VRULE);
conv_if(LINE, GF_LINE);
conv_if(AREA, GF_AREA);
conv_if(STACK, GF_STACK);
conv_if(TICK, GF_TICK);
conv_if(TEXTALIGN, GF_TEXTALIGN);
conv_if(DEF, GF_DEF);
conv_if(CDEF, GF_CDEF);
conv_if(VDEF, GF_VDEF);
conv_if(XPORT, GF_XPORT);
conv_if(SHIFT, GF_SHIFT);
return (enum gf_en)(-1);
}
enum gfx_if_en if_conv(
char *string)
{
conv_if(PNG, IF_PNG);
conv_if(SVG, IF_SVG);
conv_if(EPS, IF_EPS);
conv_if(PDF, IF_PDF);
return (enum gfx_if_en)(-1);
}
enum tmt_en tmt_conv(
char *string)
{
conv_if(SECOND, TMT_SECOND);
conv_if(MINUTE, TMT_MINUTE);
conv_if(HOUR, TMT_HOUR);
conv_if(DAY, TMT_DAY);
conv_if(WEEK, TMT_WEEK);
conv_if(MONTH, TMT_MONTH);
conv_if(YEAR, TMT_YEAR);
return (enum tmt_en)(-1);
}
enum grc_en grc_conv(
char *string)
{
conv_if(BACK, GRC_BACK);
conv_if(CANVAS, GRC_CANVAS);
conv_if(SHADEA, GRC_SHADEA);
conv_if(SHADEB, GRC_SHADEB);
conv_if(GRID, GRC_GRID);
conv_if(MGRID, GRC_MGRID);
conv_if(FONT, GRC_FONT);
conv_if(ARROW, GRC_ARROW);
conv_if(AXIS, GRC_AXIS);
conv_if(FRAME, GRC_FRAME);
return (enum grc_en)(-1);
}
enum text_prop_en text_prop_conv(
char *string)
{
conv_if(DEFAULT, TEXT_PROP_DEFAULT);
conv_if(TITLE, TEXT_PROP_TITLE);
conv_if(AXIS, TEXT_PROP_AXIS);
conv_if(UNIT, TEXT_PROP_UNIT);
conv_if(LEGEND, TEXT_PROP_LEGEND);
conv_if(WATERMARK, TEXT_PROP_WATERMARK);
return (enum text_prop_en)(-1);
}
#undef conv_if
int im_free(
image_desc_t *im)
{
unsigned long i, ii;
cairo_status_t status = (cairo_status_t) 0;
if (im == NULL)
return 0;
if (im->daemon_addr != NULL)
free(im->daemon_addr);
if (im->gdef_map){
g_hash_table_destroy(im->gdef_map);
}
if (im->rrd_map){
g_hash_table_destroy(im->rrd_map);
}
for (i = 0; i < (unsigned) im->gdes_c; i++) {
if (im->gdes[i].data_first) {
/* careful here, because a single pointer can occur several times */
free(im->gdes[i].data);
if (im->gdes[i].ds_namv) {
for (ii = 0; ii < im->gdes[i].ds_cnt; ii++)
free(im->gdes[i].ds_namv[ii]);
free(im->gdes[i].ds_namv);
}
}
/* free allocated memory used for dashed lines */
if (im->gdes[i].p_dashes != NULL)
free(im->gdes[i].p_dashes);
free(im->gdes[i].p_data);
free(im->gdes[i].rpnp);
}
free(im->gdes);
for (i = 0; i < DIM(text_prop);i++){
pango_font_description_free(im->text_prop[i].font_desc);
im->text_prop[i].font_desc = NULL;
}
if (im->font_options)
cairo_font_options_destroy(im->font_options);
if (im->cr) {
status = cairo_status(im->cr);
cairo_destroy(im->cr);
}
if (im->rendered_image) {
free(im->rendered_image);
}
if (im->layout) {
g_object_unref (im->layout);
}
if (im->surface)
cairo_surface_destroy(im->surface);
if (status)
fprintf(stderr, "OOPS: Cairo has issues it can't even die: %s\n",
cairo_status_to_string(status));
return 0;
}
/* find SI magnitude symbol for the given number*/
void auto_scale(
image_desc_t *im, /* image description */
double *value,
char **symb_ptr,
double *magfact)
{
char *symbol[] = { "a", /* 10e-18 Atto */
"f", /* 10e-15 Femto */
"p", /* 10e-12 Pico */
"n", /* 10e-9 Nano */
"u", /* 10e-6 Micro */
"m", /* 10e-3 Milli */
" ", /* Base */
"k", /* 10e3 Kilo */
"M", /* 10e6 Mega */
"G", /* 10e9 Giga */
"T", /* 10e12 Tera */
"P", /* 10e15 Peta */
"E"
}; /* 10e18 Exa */
int symbcenter = 6;
int sindex;
if (*value == 0.0 || isnan(*value)) {
sindex = 0;
*magfact = 1.0;
} else {
sindex = floor(log(fabs(*value)) / log((double) im->base));
*magfact = pow((double) im->base, (double) sindex);
(*value) /= (*magfact);
}
if (sindex <= symbcenter && sindex >= -symbcenter) {
(*symb_ptr) = symbol[sindex + symbcenter];
} else {
(*symb_ptr) = "?";
}
}
/* power prefixes */
static char si_symbol[] = {
'y', /* 10e-24 Yocto */
'z', /* 10e-21 Zepto */
'a', /* 10e-18 Atto */
'f', /* 10e-15 Femto */
'p', /* 10e-12 Pico */
'n', /* 10e-9 Nano */
'u', /* 10e-6 Micro */
'm', /* 10e-3 Milli */
' ', /* Base */
'k', /* 10e3 Kilo */
'M', /* 10e6 Mega */
'G', /* 10e9 Giga */
'T', /* 10e12 Tera */
'P', /* 10e15 Peta */
'E', /* 10e18 Exa */
'Z', /* 10e21 Zeta */
'Y' /* 10e24 Yotta */
};
static const int si_symbcenter = 8;
/* find SI magnitude symbol for the numbers on the y-axis*/
void si_unit(
image_desc_t *im /* image description */
)
{
double digits, viewdigits = 0;
digits =
floor(log(max(fabs(im->minval), fabs(im->maxval))) /
log((double) im->base));
if (im->unitsexponent != 9999) {
/* unitsexponent = 9, 6, 3, 0, -3, -6, -9, etc */
viewdigits = floor((double)(im->unitsexponent / 3));
} else {
viewdigits = digits;
}
im->magfact = pow((double) im->base, digits);
#ifdef DEBUG
printf("digits %6.3f im->magfact %6.3f\n", digits, im->magfact);
#endif
im->viewfactor = im->magfact / pow((double) im->base, viewdigits);
if (((viewdigits + si_symbcenter) < sizeof(si_symbol)) &&
((viewdigits + si_symbcenter) >= 0))
im->symbol = si_symbol[(int) viewdigits + si_symbcenter];
else
im->symbol = '?';
}
/* move min and max values around to become sensible */
void expand_range(
image_desc_t *im)
{
double sensiblevalues[] = { 1000.0, 900.0, 800.0, 750.0, 700.0,
600.0, 500.0, 400.0, 300.0, 250.0,
200.0, 125.0, 100.0, 90.0, 80.0,
75.0, 70.0, 60.0, 50.0, 40.0, 30.0,
25.0, 20.0, 10.0, 9.0, 8.0,
7.0, 6.0, 5.0, 4.0, 3.5, 3.0,
2.5, 2.0, 1.8, 1.5, 1.2, 1.0,
0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0, -1
};
double scaled_min, scaled_max;
double adj;
int i;
#ifdef DEBUG
printf("Min: %6.2f Max: %6.2f MagFactor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTAUTOSCALE) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher then max/min vals
so we can see amplitude on the graph */
double delt, fact;
delt = im->maxval - im->minval;
adj = delt * 0.1;
fact = 2.0 * pow(10.0,
floor(log10
(max(fabs(im->minval), fabs(im->maxval)) /
im->magfact)) - 2);
if (delt < fact) {
adj = (fact - delt) * 0.55;
#ifdef DEBUG
printf
("Min: %6.2f Max: %6.2f delt: %6.2f fact: %6.2f adj: %6.2f\n",
im->minval, im->maxval, delt, fact, adj);
#endif
}
im->minval -= adj;
im->maxval += adj;
} else if (im->extra_flags & ALTAUTOSCALE_MIN) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly lower than min vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->minval -= adj;
} else if (im->extra_flags & ALTAUTOSCALE_MAX) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher than max vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->maxval += adj;
} else {
scaled_min = im->minval / im->magfact;
scaled_max = im->maxval / im->magfact;
for (i = 1; sensiblevalues[i] > 0; i++) {
if (sensiblevalues[i - 1] >= scaled_min &&
sensiblevalues[i] <= scaled_min)
im->minval = sensiblevalues[i] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_min &&
-sensiblevalues[i] >= scaled_min)
im->minval = -sensiblevalues[i - 1] * (im->magfact);
if (sensiblevalues[i - 1] >= scaled_max &&
sensiblevalues[i] <= scaled_max)
im->maxval = sensiblevalues[i - 1] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_max &&
-sensiblevalues[i] >= scaled_max)
im->maxval = -sensiblevalues[i] * (im->magfact);
}
}
} else {
/* adjust min and max to the grid definition if there is one */
im->minval = (double) im->ylabfact * im->ygridstep *
floor(im->minval / ((double) im->ylabfact * im->ygridstep));
im->maxval = (double) im->ylabfact * im->ygridstep *
ceil(im->maxval / ((double) im->ylabfact * im->ygridstep));
}
#ifdef DEBUG
fprintf(stderr, "SCALED Min: %6.2f Max: %6.2f Factor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
}
void apply_gridfit(
image_desc_t *im)
{
if (isnan(im->minval) || isnan(im->maxval))
return;
ytr(im, DNAN);
if (im->logarithmic) {
double ya, yb, ypix, ypixfrac;
double log10_range = log10(im->maxval) - log10(im->minval);
ya = pow((double) 10, floor(log10(im->minval)));
while (ya < im->minval)
ya *= 10;
if (ya > im->maxval)
return; /* don't have y=10^x gridline */
yb = ya * 10;
if (yb <= im->maxval) {
/* we have at least 2 y=10^x gridlines.
Make sure distance between them in pixels
are an integer by expanding im->maxval */
double y_pixel_delta = ytr(im, ya) - ytr(im, yb);
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_log10_range = factor * log10_range;
double new_ymax_log10 = log10(im->minval) + new_log10_range;
im->maxval = pow(10, new_ymax_log10);
ytr(im, DNAN); /* reset precalc */
log10_range = log10(im->maxval) - log10(im->minval);
}
/* make sure first y=10^x gridline is located on
integer pixel position by moving scale slightly
downwards (sub-pixel movement) */
ypix = ytr(im, ya) + im->ysize; /* add im->ysize so it always is positive */
ypixfrac = ypix - floor(ypix);
if (ypixfrac > 0 && ypixfrac < 1) {
double yfrac = ypixfrac / im->ysize;
im->minval = pow(10, log10(im->minval) - yfrac * log10_range);
im->maxval = pow(10, log10(im->maxval) - yfrac * log10_range);
ytr(im, DNAN); /* reset precalc */
}
} else {
/* Make sure we have an integer pixel distance between
each minor gridline */
double ypos1 = ytr(im, im->minval);
double ypos2 = ytr(im, im->minval + im->ygrid_scale.gridstep);
double y_pixel_delta = ypos1 - ypos2;
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_range = factor * (im->maxval - im->minval);
double gridstep = im->ygrid_scale.gridstep;
double minor_y, minor_y_px, minor_y_px_frac;
if (im->maxval > 0.0)
im->maxval = im->minval + new_range;
else
im->minval = im->maxval - new_range;
ytr(im, DNAN); /* reset precalc */
/* make sure first minor gridline is on integer pixel y coord */
minor_y = gridstep * floor(im->minval / gridstep);
while (minor_y < im->minval)
minor_y += gridstep;
minor_y_px = ytr(im, minor_y) + im->ysize; /* ensure > 0 by adding ysize */
minor_y_px_frac = minor_y_px - floor(minor_y_px);
if (minor_y_px_frac > 0 && minor_y_px_frac < 1) {
double yfrac = minor_y_px_frac / im->ysize;
double range = im->maxval - im->minval;
im->minval = im->minval - yfrac * range;
im->maxval = im->maxval - yfrac * range;
ytr(im, DNAN); /* reset precalc */
}
calc_horizontal_grid(im); /* recalc with changed im->maxval */
}
}
/* reduce data reimplementation by Alex */
void reduce_data(
enum cf_en cf, /* which consolidation function ? */
unsigned long cur_step, /* step the data currently is in */
time_t *start, /* start, end and step as requested ... */
time_t *end, /* ... by the application will be ... */
unsigned long *step, /* ... adjusted to represent reality */
unsigned long *ds_cnt, /* number of data sources in file */
rrd_value_t **data)
{ /* two dimensional array containing the data */
int i, reduce_factor = ceil((double) (*step) / (double) cur_step);
unsigned long col, dst_row, row_cnt, start_offset, end_offset, skiprows =
0;
rrd_value_t *srcptr, *dstptr;
(*step) = cur_step * reduce_factor; /* set new step size for reduced data */
dstptr = *data;
srcptr = *data;
row_cnt = ((*end) - (*start)) / cur_step;
#ifdef DEBUG
#define DEBUG_REDUCE
#endif
#ifdef DEBUG_REDUCE
printf("Reducing %lu rows with factor %i time %lu to %lu, step %lu\n",
row_cnt, reduce_factor, *start, *end, cur_step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * cur_step);
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
/* We have to combine [reduce_factor] rows of the source
** into one row for the destination. Doing this we also
** need to take care to combine the correct rows. First
** alter the start and end time so that they are multiples
** of the new step time. We cannot reduce the amount of
** time so we have to move the end towards the future and
** the start towards the past.
*/
end_offset = (*end) % (*step);
start_offset = (*start) % (*step);
/* If there is a start offset (which cannot be more than
** one destination row), skip the appropriate number of
** source rows and one destination row. The appropriate
** number is what we do know (start_offset/cur_step) of
** the new interval (*step/cur_step aka reduce_factor).
*/
#ifdef DEBUG_REDUCE
printf("start_offset: %lu end_offset: %lu\n", start_offset, end_offset);
printf("row_cnt before: %lu\n", row_cnt);
#endif
if (start_offset) {
(*start) = (*start) - start_offset;
skiprows = reduce_factor - start_offset / cur_step;
srcptr += skiprows * *ds_cnt;
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt between: %lu\n", row_cnt);
#endif
/* At the end we have some rows that are not going to be
** used, the amount is end_offset/cur_step
*/
if (end_offset) {
(*end) = (*end) - end_offset + (*step);
skiprows = end_offset / cur_step;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt after: %lu\n", row_cnt);
#endif
/* Sanity check: row_cnt should be multiple of reduce_factor */
/* if this gets triggered, something is REALLY WRONG ... we die immediately */
if (row_cnt % reduce_factor) {
printf("SANITY CHECK: %lu rows cannot be reduced by %i \n",
row_cnt, reduce_factor);
printf("BUG in reduce_data()\n");
exit(1);
}
/* Now combine reduce_factor intervals at a time
** into one interval for the destination.
*/
for (dst_row = 0; (long int) row_cnt >= reduce_factor; dst_row++) {
for (col = 0; col < (*ds_cnt); col++) {
rrd_value_t newval = DNAN;
unsigned long validval = 0;
for (i = 0; i < reduce_factor; i++) {
if (isnan(srcptr[i * (*ds_cnt) + col])) {
continue;
}
validval++;
if (isnan(newval))
newval = srcptr[i * (*ds_cnt) + col];
else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval += srcptr[i * (*ds_cnt) + col];
break;
case CF_MINIMUM:
newval = min(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_FAILURES:
/* an interval contains a failure if any subintervals contained a failure */
case CF_MAXIMUM:
newval = max(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_LAST:
newval = srcptr[i * (*ds_cnt) + col];
break;
}
}
}
if (validval == 0) {
newval = DNAN;
} else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval /= validval;
break;
case CF_MINIMUM:
case CF_FAILURES:
case CF_MAXIMUM:
case CF_LAST:
break;
}
}
*dstptr++ = newval;
}
srcptr += (*ds_cnt) * reduce_factor;
row_cnt -= reduce_factor;
}
/* If we had to alter the endtime, we didn't have enough
** source rows to fill the last row. Fill it with NaN.
*/
if (end_offset)
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
#ifdef DEBUG_REDUCE
row_cnt = ((*end) - (*start)) / *step;
srcptr = *data;
printf("Done reducing. Currently %lu rows, time %lu to %lu, step %lu\n",
row_cnt, *start, *end, *step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * (*step));
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
}
/* get the data required for the graphs from the
relevant rrds ... */
int data_fetch(
image_desc_t *im)
{
int i, ii;
/* pull the data from the rrd files ... */
for (i = 0; i < (int) im->gdes_c; i++) {
/* only GF_DEF elements fetch data */
if (im->gdes[i].gf != GF_DEF)
continue;
/* do we have it already ? */
gpointer value;
char *key = gdes_fetch_key(im->gdes[i]);
gboolean ok = g_hash_table_lookup_extended(im->rrd_map,key,NULL,&value);
free(key);
if (ok){
ii = GPOINTER_TO_INT(value);
im->gdes[i].start = im->gdes[ii].start;
im->gdes[i].end = im->gdes[ii].end;
im->gdes[i].step = im->gdes[ii].step;
im->gdes[i].ds_cnt = im->gdes[ii].ds_cnt;
im->gdes[i].ds_namv = im->gdes[ii].ds_namv;
im->gdes[i].data = im->gdes[ii].data;
im->gdes[i].data_first = 0;
} else {
unsigned long ft_step = im->gdes[i].step; /* ft_step will record what we got from fetch */
/* Flush the file if
* - a connection to the daemon has been established
* - this is the first occurrence of that RRD file
*/
if (rrdc_is_connected(im->daemon_addr))
{
int status;
status = 0;
for (ii = 0; ii < i; ii++)
{
if (strcmp (im->gdes[i].rrd, im->gdes[ii].rrd) == 0)
{
status = 1;
break;
}
}
if (status == 0)
{
status = rrdc_flush (im->gdes[i].rrd);
if (status != 0)
{
rrd_set_error ("rrdc_flush (%s) failed with status %i.",
im->gdes[i].rrd, status);
return (-1);
}
}
} /* if (rrdc_is_connected()) */
if ((rrd_fetch_fn(im->gdes[i].rrd,
im->gdes[i].cf,
&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
&im->gdes[i].ds_namv,
&im->gdes[i].data)) == -1) {
return -1;
}
im->gdes[i].data_first = 1;
/* must reduce to at least im->step
otherwhise we end up with more data than we can handle in the
chart and visibility of data will be random */
im->gdes[i].step = max(im->gdes[i].step,im->step);
if (ft_step < im->gdes[i].step) {
reduce_data(im->gdes[i].cf_reduce,
ft_step,
&im->gdes[i].start,
&im->gdes[i].end,
&im->gdes[i].step,
&im->gdes[i].ds_cnt, &im->gdes[i].data);
} else {
im->gdes[i].step = ft_step;
}
}
/* lets see if the required data source is really there */
for (ii = 0; ii < (int) im->gdes[i].ds_cnt; ii++) {
if (strcmp(im->gdes[i].ds_namv[ii], im->gdes[i].ds_nam) == 0) {
im->gdes[i].ds = ii;
}
}
if (im->gdes[i].ds == -1) {
rrd_set_error("No DS called '%s' in '%s'",
im->gdes[i].ds_nam, im->gdes[i].rrd);
return -1;
}
}
return 0;
}
/* evaluate the expressions in the CDEF functions */
/*************************************************************
* CDEF stuff
*************************************************************/
long find_var_wrapper(
void *arg1,
char *key)
{
return find_var((image_desc_t *) arg1, key);
}
/* find gdes containing var*/
long find_var(
image_desc_t *im,
char *key)
{
long match = -1;
gpointer value;
gboolean ok = g_hash_table_lookup_extended(im->gdef_map,key,NULL,&value);
if (ok){
match = GPOINTER_TO_INT(value);
}
/* printf("%s -> %ld\n",key,match); */
return match;
}
/* find the greatest common divisor for all the numbers
in the 0 terminated num array */
long lcd(
long *num)
{
long rest;
int i;
for (i = 0; num[i + 1] != 0; i++) {
do {
rest = num[i] % num[i + 1];
num[i] = num[i + 1];
num[i + 1] = rest;
} while (rest != 0);
num[i + 1] = num[i];
}
/* return i==0?num[i]:num[i-1]; */
return num[i];
}
/* run the rpn calculator on all the VDEF and CDEF arguments */
int data_calc(
image_desc_t *im)
{
int gdi;
int dataidx;
long *steparray, rpi;
int stepcnt;
time_t now;
rpnstack_t rpnstack;
rpnstack_init(&rpnstack);
for (gdi = 0; gdi < im->gdes_c; gdi++) {
/* Look for GF_VDEF and GF_CDEF in the same loop,
* so CDEFs can use VDEFs and vice versa
*/
switch (im->gdes[gdi].gf) {
case GF_XPORT:
break;
case GF_SHIFT:{
graph_desc_t *vdp = &im->gdes[im->gdes[gdi].vidx];
/* remove current shift */
vdp->start -= vdp->shift;
vdp->end -= vdp->shift;
/* vdef */
if (im->gdes[gdi].shidx >= 0)
vdp->shift = im->gdes[im->gdes[gdi].shidx].vf.val;
/* constant */
else
vdp->shift = im->gdes[gdi].shval;
/* normalize shift to multiple of consolidated step */
vdp->shift = (vdp->shift / (long) vdp->step) * (long) vdp->step;
/* apply shift */
vdp->start += vdp->shift;
vdp->end += vdp->shift;
break;
}
case GF_VDEF:
/* A VDEF has no DS. This also signals other parts
* of rrdtool that this is a VDEF value, not a CDEF.
*/
im->gdes[gdi].ds_cnt = 0;
if (vdef_calc(im, gdi)) {
rrd_set_error("Error processing VDEF '%s'",
im->gdes[gdi].vname);
rpnstack_free(&rpnstack);
return -1;
}
break;
case GF_CDEF:
im->gdes[gdi].ds_cnt = 1;
im->gdes[gdi].ds = 0;
im->gdes[gdi].data_first = 1;
im->gdes[gdi].start = 0;
im->gdes[gdi].end = 0;
steparray = NULL;
stepcnt = 0;
dataidx = -1;
/* Find the variables in the expression.
* - VDEF variables are substituted by their values
* and the opcode is changed into OP_NUMBER.
* - CDEF variables are analized for their step size,
* the lowest common denominator of all the step
* sizes of the data sources involved is calculated
* and the resulting number is the step size for the
* resulting data source.
*/
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
if (im->gdes[ptr].ds_cnt == 0) { /* this is a VDEF data source */
#if 0
printf
("DEBUG: inside CDEF '%s' processing VDEF '%s'\n",
im->gdes[gdi].vname, im->gdes[ptr].vname);
printf("DEBUG: value from vdef is %f\n",
im->gdes[ptr].vf.val);
#endif
im->gdes[gdi].rpnp[rpi].val = im->gdes[ptr].vf.val;
im->gdes[gdi].rpnp[rpi].op = OP_NUMBER;
} else { /* normal variables and PREF(variables) */
/* add one entry to the array that keeps track of the step sizes of the
* data sources going into the CDEF. */
if ((steparray =
(long*)rrd_realloc(steparray,
(++stepcnt +
1) * sizeof(*steparray))) == NULL) {
rrd_set_error("realloc steparray");
rpnstack_free(&rpnstack);
return -1;
};
steparray[stepcnt - 1] = im->gdes[ptr].step;
/* adjust start and end of cdef (gdi) so
* that it runs from the latest start point
* to the earliest endpoint of any of the
* rras involved (ptr)
*/
if (im->gdes[gdi].start < im->gdes[ptr].start)
im->gdes[gdi].start = im->gdes[ptr].start;
if (im->gdes[gdi].end == 0 ||
im->gdes[gdi].end > im->gdes[ptr].end)
im->gdes[gdi].end = im->gdes[ptr].end;
/* store pointer to the first element of
* the rra providing data for variable,
* further save step size and data source
* count of this rra
*/
im->gdes[gdi].rpnp[rpi].data =
im->gdes[ptr].data + im->gdes[ptr].ds;
im->gdes[gdi].rpnp[rpi].step = im->gdes[ptr].step;
im->gdes[gdi].rpnp[rpi].ds_cnt = im->gdes[ptr].ds_cnt;
/* backoff the *.data ptr; this is done so
* rpncalc() function doesn't have to treat
* the first case differently
*/
} /* if ds_cnt != 0 */
} /* if OP_VARIABLE */
} /* loop through all rpi */
/* move the data pointers to the correct period */
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
long diff =
im->gdes[gdi].start - im->gdes[ptr].start;
if (diff > 0)
im->gdes[gdi].rpnp[rpi].data +=
(diff / im->gdes[ptr].step) *
im->gdes[ptr].ds_cnt;
}
}
if (steparray == NULL) {
rrd_set_error("rpn expressions without DEF"
" or CDEF variables are not supported");
rpnstack_free(&rpnstack);
return -1;
}
steparray[stepcnt] = 0;
/* Now find the resulting step. All steps in all
* used RRAs have to be visited
*/
im->gdes[gdi].step = lcd(steparray);
free(steparray);
if ((im->gdes[gdi].data = (rrd_value_t*)malloc(((im->gdes[gdi].end -
im->gdes[gdi].start)
/ im->gdes[gdi].step)
* sizeof(double))) == NULL) {
rrd_set_error("malloc im->gdes[gdi].data");
rpnstack_free(&rpnstack);
return -1;
}
/* Step through the new cdef results array and
* calculate the values
*/
for (now = im->gdes[gdi].start + im->gdes[gdi].step;
now <= im->gdes[gdi].end; now += im->gdes[gdi].step) {
rpnp_t *rpnp = im->gdes[gdi].rpnp;
/* 3rd arg of rpn_calc is for OP_VARIABLE lookups;
* in this case we are advancing by timesteps;
* we use the fact that time_t is a synonym for long
*/
if (rpn_calc(rpnp, &rpnstack, (long) now,
im->gdes[gdi].data, ++dataidx) == -1) {
/* rpn_calc sets the error string */
rpnstack_free(&rpnstack);
return -1;
}
} /* enumerate over time steps within a CDEF */
break;
default:
continue;
}
} /* enumerate over CDEFs */
rpnstack_free(&rpnstack);
return 0;
}
/* from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm */
/* yes we are loosing precision by doing tos with floats instead of doubles
but it seems more stable this way. */
static int AlmostEqual2sComplement(
float A,
float B,
int maxUlps)
{
int aInt = *(int *) &A;
int bInt = *(int *) &B;
int intDiff;
/* Make sure maxUlps is non-negative and small enough that the
default NAN won't compare as equal to anything. */
/* assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024); */
/* Make aInt lexicographically ordered as a twos-complement int */
if (aInt < 0)
aInt = 0x80000000l - aInt;
/* Make bInt lexicographically ordered as a twos-complement int */
if (bInt < 0)
bInt = 0x80000000l - bInt;
intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return 1;
return 0;
}
/* massage data so, that we get one value for each x coordinate in the graph */
int data_proc(
image_desc_t *im)
{
long i, ii;
double pixstep = (double) (im->end - im->start)
/ (double) im->xsize; /* how much time
passes in one pixel */
double paintval;
double minval = DNAN, maxval = DNAN;
unsigned long gr_time;
/* memory for the processed data */
for (i = 0; i < im->gdes_c; i++) {
if ((im->gdes[i].gf == GF_LINE) ||
(im->gdes[i].gf == GF_AREA) || (im->gdes[i].gf == GF_TICK)) {
if ((im->gdes[i].p_data = (rrd_value_t*)malloc((im->xsize + 1)
* sizeof(rrd_value_t))) == NULL) {
rrd_set_error("malloc data_proc");
return -1;
}
}
}
for (i = 0; i < im->xsize; i++) { /* for each pixel */
long vidx;
gr_time = im->start + pixstep * i; /* time of the current step */
paintval = 0.0;
for (ii = 0; ii < im->gdes_c; ii++) {
double value;
switch (im->gdes[ii].gf) {
case GF_LINE:
case GF_AREA:
case GF_TICK:
if (!im->gdes[ii].stack)
paintval = 0.0;
value = im->gdes[ii].yrule;
if (isnan(value) || (im->gdes[ii].gf == GF_TICK)) {
/* The time of the data doesn't necessarily match
** the time of the graph. Beware.
*/
vidx = im->gdes[ii].vidx;
if (im->gdes[vidx].gf == GF_VDEF) {
value = im->gdes[vidx].vf.val;
} else
if (((long int) gr_time >=
(long int) im->gdes[vidx].start)
&& ((long int) gr_time <
(long int) im->gdes[vidx].end)) {
value = im->gdes[vidx].data[(unsigned long)
floor((double)
(gr_time -
im->gdes[vidx].
start)
/
im->gdes[vidx].step)
* im->gdes[vidx].ds_cnt +
im->gdes[vidx].ds];
} else {
value = DNAN;
}
};
if (!isnan(value)) {
paintval += value;
im->gdes[ii].p_data[i] = paintval;
/* GF_TICK: the data values are not
** relevant for min and max
*/
if (finite(paintval) && im->gdes[ii].gf != GF_TICK && !im->gdes[ii].skipscale) {
if ((isnan(minval) || paintval < minval) &&
!(im->logarithmic && paintval <= 0.0))
minval = paintval;
if (isnan(maxval) || paintval > maxval)
maxval = paintval;
}
} else {
im->gdes[ii].p_data[i] = DNAN;
}
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
default:
break;
}
}
}
/* if min or max have not been asigned a value this is because
there was no data in the graph ... this is not good ...
lets set these to dummy values then ... */
if (im->logarithmic) {
if (isnan(minval) || isnan(maxval) || maxval <= 0) {
minval = 0.0; /* catching this right away below */
maxval = 5.1;
}
/* in logarithm mode, where minval is smaller or equal
to 0 make the beast just way smaller than maxval */
if (minval <= 0) {
minval = maxval / 10e8;
}
} else {
if (isnan(minval) || isnan(maxval)) {
minval = 0.0;
maxval = 1.0;
}
}
/* adjust min and max values given by the user */
/* for logscale we add something on top */
if (isnan(im->minval)
|| ((!im->rigid) && im->minval > minval)
) {
if (im->logarithmic)
im->minval = minval / 2.0;
else
im->minval = minval;
}
if (isnan(im->maxval)
|| (!im->rigid && im->maxval < maxval)
) {
if (im->logarithmic)
im->maxval = maxval * 2.0;
else
im->maxval = maxval;
}
/* make sure min is smaller than max */
if (im->minval > im->maxval) {
if (im->minval > 0)
im->minval = 0.99 * im->maxval;
else
im->minval = 1.01 * im->maxval;
}
/* make sure min and max are not equal */
if (AlmostEqual2sComplement(im->minval, im->maxval, 4)) {
if (im->maxval > 0)
im->maxval *= 1.01;
else
im->maxval *= 0.99;
/* make sure min and max are not both zero */
if (AlmostEqual2sComplement(im->maxval, 0, 4)) {
im->maxval = 1.0;
}
}
return 0;
}
static int find_first_weekday(void){
static int first_weekday = -1;
if (first_weekday == -1){
#ifdef HAVE__NL_TIME_WEEK_1STDAY
/* according to http://sourceware.org/ml/libc-locales/2009-q1/msg00011.html */
/* See correct way here http://pasky.or.cz/dev/glibc/first_weekday.c */
first_weekday = nl_langinfo (_NL_TIME_FIRST_WEEKDAY)[0];
int week_1stday;
long week_1stday_l = (long) nl_langinfo (_NL_TIME_WEEK_1STDAY);
if (week_1stday_l == 19971130) week_1stday = 0; /* Sun */
else if (week_1stday_l == 19971201) week_1stday = 1; /* Mon */
else
{
first_weekday = 1;
return first_weekday; /* we go for a monday default */
}
first_weekday=(week_1stday + first_weekday - 1) % 7;
#else
first_weekday = 1;
#endif
}
return first_weekday;
}
/* identify the point where the first gridline, label ... gets placed */
time_t find_first_time(
time_t start, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
localtime_r(&start, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
switch (baseint) {
case TMT_SECOND:
tm. tm_sec -= tm.tm_sec % basestep;
break;
case TMT_MINUTE:
tm. tm_sec = 0;
tm. tm_min -= tm.tm_min % basestep;
break;
case TMT_HOUR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour -= tm.tm_hour % basestep;
break;
case TMT_DAY:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
break;
case TMT_WEEK:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday -= tm.tm_wday - find_first_weekday();
if (tm.tm_wday == 0 && find_first_weekday() > 0)
tm. tm_mday -= 7; /* we want the *previous* week */
break;
case TMT_MONTH:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon -= tm.tm_mon % basestep;
break;
case TMT_YEAR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon = 0;
tm. tm_year -= (
tm.tm_year + 1900) %basestep;
}
return mktime(&tm);
}
/* identify the point where the next gridline, label ... gets placed */
time_t find_next_time(
time_t current, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
time_t madetime;
localtime_r(¤t, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
int limit = 2;
switch (baseint) {
case TMT_SECOND: limit = 7200; break;
case TMT_MINUTE: limit = 120; break;
case TMT_HOUR: limit = 2; break;
default: limit = 2; break;
}
do {
switch (baseint) {
case TMT_SECOND:
tm. tm_sec += basestep;
break;
case TMT_MINUTE:
tm. tm_min += basestep;
break;
case TMT_HOUR:
tm. tm_hour += basestep;
break;
case TMT_DAY:
tm. tm_mday += basestep;
break;
case TMT_WEEK:
tm. tm_mday += 7 * basestep;
break;
case TMT_MONTH:
tm. tm_mon += basestep;
break;
case TMT_YEAR:
tm. tm_year += basestep;
}
madetime = mktime(&tm);
} while (madetime == -1 && limit-- >= 0); /* this is necessary to skip impossible times
like the daylight saving time skips */
return madetime;
}
/* calculate values required for PRINT and GPRINT functions */
int print_calc(
image_desc_t *im)
{
long i, ii, validsteps;
double printval;
struct tm tmvdef;
int graphelement = 0;
long vidx;
int max_ii;
double magfact = -1;
char *si_symb = "";
char *percent_s;
int prline_cnt = 0;
/* wow initializing tmvdef is quite a task :-) */
time_t now = time(NULL);
localtime_r(&now, &tmvdef);
for (i = 0; i < im->gdes_c; i++) {
vidx = im->gdes[i].vidx;
switch (im->gdes[i].gf) {
case GF_PRINT:
case GF_GPRINT:
/* PRINT and GPRINT can now print VDEF generated values.
* There's no need to do any calculations on them as these
* calculations were already made.
*/
if (im->gdes[vidx].gf == GF_VDEF) { /* simply use vals */
printval = im->gdes[vidx].vf.val;
localtime_r(&im->gdes[vidx].vf.when, &tmvdef);
} else { /* need to calculate max,min,avg etcetera */
max_ii = ((im->gdes[vidx].end - im->gdes[vidx].start)
/ im->gdes[vidx].step * im->gdes[vidx].ds_cnt);
printval = DNAN;
validsteps = 0;
for (ii = im->gdes[vidx].ds;
ii < max_ii; ii += im->gdes[vidx].ds_cnt) {
if (!finite(im->gdes[vidx].data[ii]))
continue;
if (isnan(printval)) {
printval = im->gdes[vidx].data[ii];
validsteps++;
continue;
}
switch (im->gdes[i].cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVPREDICT:
case CF_DEVSEASONAL:
case CF_SEASONAL:
case CF_AVERAGE:
validsteps++;
printval += im->gdes[vidx].data[ii];
break;
case CF_MINIMUM:
printval = min(printval, im->gdes[vidx].data[ii]);
break;
case CF_FAILURES:
case CF_MAXIMUM:
printval = max(printval, im->gdes[vidx].data[ii]);
break;
case CF_LAST:
printval = im->gdes[vidx].data[ii];
}
}
if (im->gdes[i].cf == CF_AVERAGE || im->gdes[i].cf > CF_LAST) {
if (validsteps > 1) {
printval = (printval / validsteps);
}
}
} /* prepare printval */
if (!im->gdes[i].strftm && (percent_s = strstr(im->gdes[i].format, "%S")) != NULL) {
/* Magfact is set to -1 upon entry to print_calc. If it
* is still less than 0, then we need to run auto_scale.
* Otherwise, put the value into the correct units. If
* the value is 0, then do not set the symbol or magnification
* so next the calculation will be performed again. */
if (magfact < 0.0) {
auto_scale(im, &printval, &si_symb, &magfact);
if (printval == 0.0)
magfact = -1.0;
} else {
printval /= magfact;
}
*(++percent_s) = 's';
} else if (!im->gdes[i].strftm && strstr(im->gdes[i].format, "%s") != NULL) {
auto_scale(im, &printval, &si_symb, &magfact);
}
if (im->gdes[i].gf == GF_PRINT) {
rrd_infoval_t prline;
if (im->gdes[i].strftm) {
prline.u_str = (char*)malloc((FMT_LEG_LEN + 2) * sizeof(char));
strftime(prline.u_str,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
} else if (bad_format_print(im->gdes[i].format)) {
return -1;
} else {
prline.u_str =
sprintf_alloc(im->gdes[i].format, printval, si_symb);
}
grinfo_push(im,
sprintf_alloc
("print[%ld]", prline_cnt++), RD_I_STR, prline);
free(prline.u_str);
} else {
/* GF_GPRINT */
if (im->gdes[i].strftm) {
strftime(im->gdes[i].legend,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
} else {
if (bad_format_print(im->gdes[i].format)) {
return -1;
}
#ifdef HAVE_SNPRINTF
snprintf(im->gdes[i].legend,
FMT_LEG_LEN - 2,
im->gdes[i].format, printval, si_symb);
#else
sprintf(im->gdes[i].legend,
im->gdes[i].format, printval, si_symb);
#endif
}
graphelement = 1;
}
break;
case GF_LINE:
case GF_AREA:
case GF_TICK:
graphelement = 1;
break;
case GF_HRULE:
if (isnan(im->gdes[i].yrule)) { /* we must set this here or the legend printer can not decide to print the legend */
im->gdes[i].yrule = im->gdes[vidx].vf.val;
};
graphelement = 1;
break;
case GF_VRULE:
if (im->gdes[i].xrule == 0) { /* again ... the legend printer needs it */
im->gdes[i].xrule = im->gdes[vidx].vf.when;
};
graphelement = 1;
break;
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_DEF:
case GF_CDEF:
case GF_VDEF:
#ifdef WITH_PIECHART
case GF_PART:
#endif
case GF_SHIFT:
case GF_XPORT:
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
}
}
return graphelement;
}
/* place legends with color spots */
int leg_place(
image_desc_t *im,
int calc_width)
{
/* graph labels */
int interleg = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int border = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int fill = 0, fill_last;
double legendwidth; // = im->ximg - 2 * border;
int leg_c = 0;
double leg_x = border;
int leg_y = 0; //im->yimg;
int leg_cc;
double glue = 0;
int i, ii, mark = 0;
char default_txtalign = TXA_JUSTIFIED; /*default line orientation */
int *legspace;
char *tab;
char saved_legend[FMT_LEG_LEN + 5];
if(calc_width){
legendwidth = 0;
}
else{
legendwidth = im->legendwidth - 2 * border;
}
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
if ((legspace = (int*)malloc(im->gdes_c * sizeof(int))) == NULL) {
rrd_set_error("malloc for legspace");
return -1;
}
for (i = 0; i < im->gdes_c; i++) {
char prt_fctn; /*special printfunctions */
if(calc_width){
strcpy(saved_legend, im->gdes[i].legend);
}
fill_last = fill;
/* hide legends for rules which are not displayed */
if (im->gdes[i].gf == GF_TEXTALIGN) {
default_txtalign = im->gdes[i].txtalign;
}
if (!(im->extra_flags & FORCE_RULES_LEGEND)) {
if (im->gdes[i].gf == GF_HRULE
&& (im->gdes[i].yrule <
im->minval || im->gdes[i].yrule > im->maxval))
im->gdes[i].legend[0] = '\0';
if (im->gdes[i].gf == GF_VRULE
&& (im->gdes[i].xrule <
im->start || im->gdes[i].xrule > im->end))
im->gdes[i].legend[0] = '\0';
}
/* turn \\t into tab */
while ((tab = strstr(im->gdes[i].legend, "\\t"))) {
memmove(tab, tab + 1, strlen(tab));
tab[0] = (char) 9;
}
leg_cc = strlen(im->gdes[i].legend);
/* is there a controle code at the end of the legend string ? */
if (leg_cc >= 2 && im->gdes[i].legend[leg_cc - 2] == '\\') {
prt_fctn = im->gdes[i].legend[leg_cc - 1];
leg_cc -= 2;
im->gdes[i].legend[leg_cc] = '\0';
} else {
prt_fctn = '\0';
}
/* only valid control codes */
if (prt_fctn != 'l' && prt_fctn != 'n' && /* a synonym for l */
prt_fctn != 'r' &&
prt_fctn != 'j' &&
prt_fctn != 'c' &&
prt_fctn != 'u' &&
prt_fctn != '.' &&
prt_fctn != 's' && prt_fctn != '\0' && prt_fctn != 'g') {
free(legspace);
rrd_set_error
("Unknown control code at the end of '%s\\%c'",
im->gdes[i].legend, prt_fctn);
return -1;
}
/* \n -> \l */
if (prt_fctn == 'n') {
prt_fctn = 'l';
}
/* \. is a null operation to allow strings ending in \x */
if (prt_fctn == '.') {
prt_fctn = '\0';
}
/* remove exess space from the end of the legend for \g */
while (prt_fctn == 'g' &&
leg_cc > 0 && im->gdes[i].legend[leg_cc - 1] == ' ') {
leg_cc--;
im->gdes[i].legend[leg_cc] = '\0';
}
if (leg_cc != 0) {
/* no interleg space if string ends in \g */
legspace[i] = (prt_fctn == 'g' ? 0 : interleg);
if (fill > 0) {
fill += legspace[i];
}
fill +=
gfx_get_text_width(im,
fill + border,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[i].legend);
leg_c++;
} else {
legspace[i] = 0;
}
/* who said there was a special tag ... ? */
if (prt_fctn == 'g') {
prt_fctn = '\0';
}
if (prt_fctn == '\0') {
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
if (i == im->gdes_c - 1 || fill > legendwidth) {
/* just one legend item is left right or center */
switch (default_txtalign) {
case TXA_RIGHT:
prt_fctn = 'r';
break;
case TXA_CENTER:
prt_fctn = 'c';
break;
case TXA_JUSTIFIED:
prt_fctn = 'j';
break;
default:
prt_fctn = 'l';
break;
}
}
/* is it time to place the legends ? */
if (fill > legendwidth) {
if (leg_c > 1) {
/* go back one */
i--;
fill = fill_last;
leg_c--;
}
}
if (leg_c == 1 && prt_fctn == 'j') {
prt_fctn = 'l';
}
}
if (prt_fctn != '\0') {
leg_x = border;
if (leg_c >= 2 && prt_fctn == 'j') {
glue = (double)(legendwidth - fill) / (double)(leg_c - 1);
} else {
glue = 0;
}
if (prt_fctn == 'c')
leg_x = border + (double)(legendwidth - fill) / 2.0;
if (prt_fctn == 'r')
leg_x = legendwidth - fill + border;
for (ii = mark; ii <= i; ii++) {
if (im->gdes[ii].legend[0] == '\0')
continue; /* skip empty legends */
im->gdes[ii].leg_x = leg_x;
im->gdes[ii].leg_y = leg_y + border;
leg_x +=
(double)gfx_get_text_width(im, leg_x,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[ii].legend)
+(double)legspace[ii]
+ glue;
}
if (leg_x > border || prt_fctn == 's')
leg_y += im->text_prop[TEXT_PROP_LEGEND].size * 1.8;
if (prt_fctn == 's')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size;
if (prt_fctn == 'u')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size *1.8;
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
fill = 0;
leg_c = 0;
mark = ii;
}
if(calc_width){
strcpy(im->gdes[i].legend, saved_legend);
}
}
if(calc_width){
im->legendwidth = legendwidth + 2 * border;
}
else{
im->legendheight = leg_y + border * 0.6;
}
free(legspace);
}
return 0;
}
/* create a grid on the graph. it determines what to do
from the values of xsize, start and end */
/* the xaxis labels are determined from the number of seconds per pixel
in the requested graph */
int calc_horizontal_grid(
image_desc_t
*im)
{
double range;
double scaledrange;
int pixel, i;
int gridind = 0;
int decimals, fractionals;
im->ygrid_scale.labfact = 2;
range = im->maxval - im->minval;
scaledrange = range / im->magfact;
/* does the scale of this graph make it impossible to put lines
on it? If so, give up. */
if (isnan(scaledrange)) {
return 0;
}
/* find grid spaceing */
pixel = 1;
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTYGRID) {
/* find the value with max number of digits. Get number of digits */
decimals =
ceil(log10
(max(fabs(im->maxval), fabs(im->minval)) *
im->viewfactor / im->magfact));
if (decimals <= 0) /* everything is small. make place for zero */
decimals = 1;
im->ygrid_scale.gridstep =
pow((double) 10,
floor(log10(range * im->viewfactor / im->magfact))) /
im->viewfactor * im->magfact;
if (im->ygrid_scale.gridstep == 0) /* range is one -> 0.1 is reasonable scale */
im->ygrid_scale.gridstep = 0.1;
/* should have at least 5 lines but no more then 15 */
if (range / im->ygrid_scale.gridstep < 5
&& im->ygrid_scale.gridstep >= 30)
im->ygrid_scale.gridstep /= 10;
if (range / im->ygrid_scale.gridstep > 15)
im->ygrid_scale.gridstep *= 10;
if (range / im->ygrid_scale.gridstep > 5) {
im->ygrid_scale.labfact = 1;
if (range / im->ygrid_scale.gridstep > 8
|| im->ygrid_scale.gridstep <
1.8 * im->text_prop[TEXT_PROP_AXIS].size)
im->ygrid_scale.labfact = 2;
} else {
im->ygrid_scale.gridstep /= 5;
im->ygrid_scale.labfact = 5;
}
fractionals =
floor(log10
(im->ygrid_scale.gridstep *
(double) im->ygrid_scale.labfact * im->viewfactor /
im->magfact));
if (fractionals < 0) { /* small amplitude. */
int len = decimals - fractionals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
sprintf(im->ygrid_scale.labfmt,
"%%%d.%df%s", len,
-fractionals, (im->symbol != ' ' ? " %c" : ""));
} else {
int len = decimals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
sprintf(im->ygrid_scale.labfmt,
"%%%d.0f%s", len, (im->symbol != ' ' ? " %c" : ""));
}
} else { /* classic rrd grid */
for (i = 0; ylab[i].grid > 0; i++) {
pixel = im->ysize / (scaledrange / ylab[i].grid);
gridind = i;
if (pixel >= 5)
break;
}
for (i = 0; i < 4; i++) {
if (pixel * ylab[gridind].lfac[i] >=
1.8 * im->text_prop[TEXT_PROP_AXIS].size) {
im->ygrid_scale.labfact = ylab[gridind].lfac[i];
break;
}
}
im->ygrid_scale.gridstep = ylab[gridind].grid * im->magfact;
}
} else {
im->ygrid_scale.gridstep = im->ygridstep;
im->ygrid_scale.labfact = im->ylabfact;
}
return 1;
}
int draw_horizontal_grid(
image_desc_t
*im)
{
int i;
double scaledstep;
char graph_label[100];
int nlabels = 0;
double X0 = im->xorigin;
double X1 = im->xorigin + im->xsize;
int sgrid = (int) (im->minval / im->ygrid_scale.gridstep - 1);
int egrid = (int) (im->maxval / im->ygrid_scale.gridstep + 1);
double MaxY;
double second_axis_magfact = 0;
char *second_axis_symb = "";
scaledstep =
im->ygrid_scale.gridstep /
(double) im->magfact * (double) im->viewfactor;
MaxY = scaledstep * (double) egrid;
for (i = sgrid; i <= egrid; i++) {
double Y0 = ytr(im,
im->ygrid_scale.gridstep * i);
double YN = ytr(im,
im->ygrid_scale.gridstep * (i + 1));
if (floor(Y0 + 0.5) >=
im->yorigin - im->ysize && floor(Y0 + 0.5) <= im->yorigin) {
/* Make sure at least 2 grid labels are shown, even if it doesn't agree
with the chosen settings. Add a label if required by settings, or if
there is only one label so far and the next grid line is out of bounds. */
if (i % im->ygrid_scale.labfact == 0
|| (nlabels == 1
&& (YN < im->yorigin - im->ysize || YN > im->yorigin))) {
if (im->symbol == ' ') {
if (im->primary_axis_format[0] == '\0'){
if (im->extra_flags & ALTYGRID) {
sprintf(graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i);
} else {
if (MaxY < 10) {
sprintf(graph_label, "%4.1f",
scaledstep * (double) i);
} else {
sprintf(graph_label, "%4.0f",
scaledstep * (double) i);
}
}
} else {
sprintf(graph_label, im->primary_axis_format,
scaledstep * (double) i);
}
} else {
char sisym = (i == 0 ? ' ' : im->symbol);
if (im->primary_axis_format[0] == '\0'){
if (im->extra_flags & ALTYGRID) {
sprintf(graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i, sisym);
} else {
if (MaxY < 10) {
sprintf(graph_label, "%4.1f %c",
scaledstep * (double) i, sisym);
} else {
sprintf(graph_label, "%4.0f %c",
scaledstep * (double) i, sisym);
}
}
} else {
sprintf(graph_label, im->primary_axis_format,
scaledstep * (double) i, sisym);
}
}
nlabels++;
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = im->ygrid_scale.gridstep*(double)i*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format[0] == '\0'){
if (!second_axis_magfact){
double dummy = im->ygrid_scale.gridstep*(double)(sgrid+egrid)/2.0*im->second_axis_scale+im->second_axis_shift;
auto_scale(im,&dummy,&second_axis_symb,&second_axis_magfact);
}
sval /= second_axis_magfact;
if(MaxY < 10) {
sprintf(graph_label_right,"%5.1f %s",sval,second_axis_symb);
} else {
sprintf(graph_label_right,"%5.0f %s",sval,second_axis_symb);
}
}
else {
sprintf(graph_label_right,im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
gfx_line(im, X0 - 2, Y0, X0, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID],
im->grid_dash_on, im->grid_dash_off);
} else if (!(im->extra_flags & NOMINOR)) {
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
}
return 1;
}
/* this is frexp for base 10 */
double frexp10(
double,
double *);
double frexp10(
double x,
double *e)
{
double mnt;
int iexp;
iexp = floor(log((double)fabs(x)) / log((double)10));
mnt = x / pow(10.0, iexp);
if (mnt >= 10.0) {
iexp++;
mnt = x / pow(10.0, iexp);
}
*e = iexp;
return mnt;
}
/* logaritmic horizontal grid */
int horizontal_log_grid(
image_desc_t
*im)
{
double yloglab[][10] = {
{
1.0, 10., 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 5.0, 10., 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 5.0, 7.0, 10., 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 4.0,
6.0, 8.0, 10.,
0.0,
0.0, 0.0, 0.0}, {
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0} /* last line */
};
int i, j, val_exp, min_exp;
double nex; /* number of decades in data */
double logscale; /* scale in logarithmic space */
int exfrac = 1; /* decade spacing */
int mid = -1; /* row in yloglab for major grid */
double mspac; /* smallest major grid spacing (pixels) */
int flab; /* first value in yloglab to use */
double value, tmp, pre_value;
double X0, X1, Y0;
char graph_label[100];
nex = log10(im->maxval / im->minval);
logscale = im->ysize / nex;
/* major spacing for data with high dynamic range */
while (logscale * exfrac < 3 * im->text_prop[TEXT_PROP_LEGEND].size) {
if (exfrac == 1)
exfrac = 3;
else
exfrac += 3;
}
/* major spacing for less dynamic data */
do {
/* search best row in yloglab */
mid++;
for (i = 0; yloglab[mid][i + 1] < 10.0; i++);
mspac = logscale * log10(10.0 / yloglab[mid][i]);
}
while (mspac >
2 * im->text_prop[TEXT_PROP_LEGEND].size && yloglab[mid][0] > 0);
if (mid)
mid--;
/* find first value in yloglab */
for (flab = 0;
yloglab[mid][flab] < 10
&& frexp10(im->minval, &tmp) > yloglab[mid][flab]; flab++);
if (yloglab[mid][flab] == 10.0) {
tmp += 1.0;
flab = 0;
}
val_exp = tmp;
if (val_exp % exfrac)
val_exp += abs(-val_exp % exfrac);
X0 = im->xorigin;
X1 = im->xorigin + im->xsize;
/* draw grid */
pre_value = DNAN;
while (1) {
value = yloglab[mid][flab] * pow(10.0, val_exp);
if (AlmostEqual2sComplement(value, pre_value, 4))
break; /* it seems we are not converging */
pre_value = value;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* major grid line */
gfx_line(im,
X0 - 2, Y0, X0, Y0, MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
/* label */
if (im->extra_flags & FORCE_UNITS_SI) {
int scale;
double pvalue;
char symbol;
scale = floor(val_exp / 3.0);
if (value >= 1.0)
pvalue = pow(10.0, val_exp % 3);
else
pvalue = pow(10.0, ((val_exp + 1) % 3) + 2);
pvalue *= yloglab[mid][flab];
if (((scale + si_symbcenter) < (int) sizeof(si_symbol))
&& ((scale + si_symbcenter) >= 0))
symbol = si_symbol[scale + si_symbcenter];
else
symbol = '?';
sprintf(graph_label, "%3.0f %c", pvalue, symbol);
} else {
sprintf(graph_label, "%3.0e", value);
}
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = value*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format[0] == '\0'){
if (im->extra_flags & FORCE_UNITS_SI) {
double mfac = 1;
char *symb = "";
auto_scale(im,&sval,&symb,&mfac);
sprintf(graph_label_right,"%4.0f %s", sval,symb);
}
else {
sprintf(graph_label_right,"%3.0e", sval);
}
}
else {
sprintf(graph_label_right,im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
/* minor grid */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line behind current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
} else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* next decade */
if (yloglab[mid][++flab] == 10.0) {
flab = 0;
val_exp += exfrac;
}
}
/* draw minor lines after highest major line */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line below current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* fancy minor gridlines */
else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
return 1;
}
void vertical_grid(
image_desc_t *im)
{
int xlab_sel; /* which sort of label and grid ? */
time_t ti, tilab, timajor;
long factor;
char graph_label[100];
double X0, Y0, Y1; /* points for filled graph and more */
struct tm tm;
/* the type of time grid is determined by finding
the number of seconds per pixel in the graph */
if (im->xlab_user.minsec == -1) {
factor = (im->end - im->start) / im->xsize;
xlab_sel = 0;
while (xlab[xlab_sel + 1].minsec !=
-1 && xlab[xlab_sel + 1].minsec <= factor) {
xlab_sel++;
} /* pick the last one */
while (xlab[xlab_sel - 1].minsec ==
xlab[xlab_sel].minsec
&& xlab[xlab_sel].length > (im->end - im->start)) {
xlab_sel--;
} /* go back to the smallest size */
im->xlab_user.gridtm = xlab[xlab_sel].gridtm;
im->xlab_user.gridst = xlab[xlab_sel].gridst;
im->xlab_user.mgridtm = xlab[xlab_sel].mgridtm;
im->xlab_user.mgridst = xlab[xlab_sel].mgridst;
im->xlab_user.labtm = xlab[xlab_sel].labtm;
im->xlab_user.labst = xlab[xlab_sel].labst;
im->xlab_user.precis = xlab[xlab_sel].precis;
im->xlab_user.stst = xlab[xlab_sel].stst;
}
/* y coords are the same for every line ... */
Y0 = im->yorigin;
Y1 = im->yorigin - im->ysize;
/* paint the minor grid */
if (!(im->extra_flags & NOMINOR)) {
for (ti = find_first_time(im->start,
im->
xlab_user.
gridtm,
im->
xlab_user.
gridst),
timajor =
find_first_time(im->start,
im->xlab_user.
mgridtm,
im->xlab_user.
mgridst);
ti < im->end && ti != -1;
ti =
find_next_time(ti, im->xlab_user.gridtm, im->xlab_user.gridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
while (timajor < ti && timajor != -1) {
timajor = find_next_time(timajor,
im->
xlab_user.
mgridtm, im->xlab_user.mgridst);
}
if (timajor == -1) break; /* fail in case of problems with time increments */
if (ti == timajor)
continue; /* skip as falls on major grid line */
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X0, Y0, X0, Y0 + 2,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0, Y0 + 1, X0,
Y1 - 1, GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* paint the major grid */
for (ti = find_first_time(im->start,
im->
xlab_user.
mgridtm,
im->
xlab_user.
mgridst);
ti < im->end && ti != -1;
ti = find_next_time(ti, im->xlab_user.mgridtm, im->xlab_user.mgridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X0, Y0, X0, Y0 + 3,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0, Y0 + 3, X0,
Y1 - 2, MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
}
/* paint the labels below the graph */
for (ti =
find_first_time(im->start -
im->xlab_user.
precis / 2,
im->xlab_user.
labtm,
im->xlab_user.
labst);
(ti <=
im->end -
im->xlab_user.precis / 2) && ti != -1;
ti = find_next_time(ti, im->xlab_user.labtm, im->xlab_user.labst)
) {
tilab = ti + im->xlab_user.precis / 2; /* correct time for the label */
/* are we inside the graph ? */
if (tilab < im->start || tilab > im->end)
continue;
#if HAVE_STRFTIME
localtime_r(&tilab, &tm);
strftime(graph_label, 99, im->xlab_user.stst, &tm);
#else
# error "your libc has no strftime I guess we'll abort the exercise here."
#endif
gfx_text(im,
xtr(im, tilab),
Y0 + 3,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_TOP, graph_label);
}
}
void axis_paint(
image_desc_t *im)
{
/* draw x and y axis */
/* gfx_line ( im->canvas, im->xorigin+im->xsize,im->yorigin,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line ( im->canvas, im->xorigin,im->yorigin-im->ysize,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]); */
gfx_line(im, im->xorigin - 4,
im->yorigin,
im->xorigin + im->xsize +
4, im->yorigin, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line(im, im->xorigin,
im->yorigin + 4,
im->xorigin,
im->yorigin - im->ysize -
4, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
/* arrow for X and Y axis direction */
gfx_new_area(im, im->xorigin + im->xsize + 2, im->yorigin - 3, im->xorigin + im->xsize + 2, im->yorigin + 3, im->xorigin + im->xsize + 7, im->yorigin, /* horyzontal */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
gfx_new_area(im, im->xorigin - 3, im->yorigin - im->ysize - 2, im->xorigin + 3, im->yorigin - im->ysize - 2, im->xorigin, im->yorigin - im->ysize - 7, /* vertical */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
if (im->second_axis_scale != 0){
gfx_line ( im, im->xorigin+im->xsize,im->yorigin+4,
im->xorigin+im->xsize,im->yorigin-im->ysize-4,
MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_new_area ( im,
im->xorigin+im->xsize-2, im->yorigin-im->ysize-2,
im->xorigin+im->xsize+3, im->yorigin-im->ysize-2,
im->xorigin+im->xsize, im->yorigin-im->ysize-7, /* LINEOFFSET */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
}
}
void grid_paint(
image_desc_t *im)
{
long i;
int res = 0;
double X0, Y0; /* points for filled graph and more */
struct gfx_color_t water_color;
if (im->draw_3d_border > 0) {
/* draw 3d border */
i = im->draw_3d_border;
gfx_new_area(im, 0, im->yimg,
i, im->yimg - i, i, i, im->graph_col[GRC_SHADEA]);
gfx_add_point(im, im->ximg - i, i);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, 0, 0);
gfx_close_path(im);
gfx_new_area(im, i, im->yimg - i,
im->ximg - i,
im->yimg - i, im->ximg - i, i, im->graph_col[GRC_SHADEB]);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, im->ximg, im->yimg);
gfx_add_point(im, 0, im->yimg);
gfx_close_path(im);
}
if (im->draw_x_grid == 1)
vertical_grid(im);
if (im->draw_y_grid == 1) {
if (im->logarithmic) {
res = horizontal_log_grid(im);
} else {
res = draw_horizontal_grid(im);
}
/* dont draw horizontal grid if there is no min and max val */
if (!res) {
char *nodata = "No Data found";
gfx_text(im, im->ximg / 2,
(2 * im->yorigin -
im->ysize) / 2,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_CENTER, nodata);
}
}
/* yaxis unit description */
if (im->ylegend[0] != '\0'){
gfx_text(im,
im->xOriginLegendY+10,
im->yOriginLegendY,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_UNIT].
font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE, GFX_H_CENTER, GFX_V_CENTER, im->ylegend);
}
if (im->second_axis_legend[0] != '\0'){
gfx_text( im,
im->xOriginLegendY2+10,
im->yOriginLegendY2,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_UNIT].font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE,
GFX_H_CENTER, GFX_V_CENTER,
im->second_axis_legend);
}
/* graph title */
gfx_text(im,
im->xOriginTitle, im->yOriginTitle+6,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_TITLE].
font_desc,
im->tabwidth, 0.0, GFX_H_CENTER, GFX_V_TOP, im->title);
/* rrdtool 'logo' */
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
double xpos = im->legendposition == EAST ? im->xOriginLegendY : im->ximg - 4;
gfx_text(im, xpos, 5,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth,
-90, GFX_H_LEFT, GFX_V_TOP, "RRDTOOL / TOBI OETIKER");
}
/* graph watermark */
if (im->watermark[0] != '\0') {
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
gfx_text(im,
im->ximg / 2, im->yimg - 6,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth, 0,
GFX_H_CENTER, GFX_V_BOTTOM, im->watermark);
}
/* graph labels */
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
for (i = 0; i < im->gdes_c; i++) {
if (im->gdes[i].legend[0] == '\0')
continue;
/* im->gdes[i].leg_y is the bottom of the legend */
X0 = im->xOriginLegend + im->gdes[i].leg_x;
Y0 = im->legenddirection == TOP_DOWN ? im->yOriginLegend + im->gdes[i].leg_y : im->yOriginLegend + im->legendheight - im->gdes[i].leg_y;
gfx_text(im, X0, Y0,
im->graph_col[GRC_FONT],
im->
text_prop
[TEXT_PROP_LEGEND].font_desc,
im->tabwidth, 0.0,
GFX_H_LEFT, GFX_V_BOTTOM, im->gdes[i].legend);
/* The legend for GRAPH items starts with "M " to have
enough space for the box */
if (im->gdes[i].gf != GF_PRINT &&
im->gdes[i].gf != GF_GPRINT && im->gdes[i].gf != GF_COMMENT) {
double boxH, boxV;
double X1, Y1;
boxH = gfx_get_text_width(im, 0,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, "o") * 1.2;
boxV = boxH;
/* shift the box up a bit */
Y0 -= boxV * 0.4;
if (im->dynamic_labels && im->gdes[i].gf == GF_HRULE) { /* [-] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0, Y0 - boxV / 2,
X0 + boxH, Y0 - boxV / 2,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_VRULE) { /* [|] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0 + boxH / 2, Y0,
X0 + boxH / 2, Y0 - boxV,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_LINE) { /* [/] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
gfx_line(im,
X0, Y0,
X0 + boxH, Y0 - boxV,
im->gdes[i].linewidth, im->gdes[i].col);
gfx_close_path(im);
} else {
/* make sure transparent colors show up the same way as in the graph */
gfx_new_area(im,
X0, Y0 - boxV,
X0, Y0, X0 + boxH, Y0, im->graph_col[GRC_BACK]);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
gfx_new_area(im, X0, Y0 - boxV, X0,
Y0, X0 + boxH, Y0, im->gdes[i].col);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
X1 = X0 + boxH;
Y1 = Y0 - boxV;
gfx_line_fit(im, &X0, &Y0);
gfx_line_fit(im, &X1, &Y1);
cairo_move_to(im->cr, X0, Y0);
cairo_line_to(im->cr, X1, Y0);
cairo_line_to(im->cr, X1, Y1);
cairo_line_to(im->cr, X0, Y1);
cairo_close_path(im->cr);
cairo_set_source_rgba(im->cr,
im->graph_col[GRC_FRAME].red,
im->graph_col[GRC_FRAME].green,
im->graph_col[GRC_FRAME].blue,
im->graph_col[GRC_FRAME].alpha);
}
if (im->gdes[i].dash) {
/* make box borders in legend dashed if the graph is dashed */
double dashes[] = {
3.0
};
cairo_set_dash(im->cr, dashes, 1, 0.0);
}
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
}
}
}
/*****************************************************
* lazy check make sure we rely need to create this graph
*****************************************************/
int lazy_check(
image_desc_t *im)
{
FILE *fd = NULL;
int size = 1;
struct stat imgstat;
if (im->lazy == 0)
return 0; /* no lazy option */
if (strlen(im->graphfile) == 0)
return 0; /* inmemory option */
if (stat(im->graphfile, &imgstat) != 0)
return 0; /* can't stat */
/* one pixel in the existing graph is more then what we would
change here ... */
if (time(NULL) - imgstat.st_mtime > (im->end - im->start) / im->xsize)
return 0;
if ((fd = fopen(im->graphfile, "rb")) == NULL)
return 0; /* the file does not exist */
switch (im->imgformat) {
case IF_PNG:
size = PngSize(fd, &(im->ximg), &(im->yimg));
break;
default:
size = 1;
}
fclose(fd);
return size;
}
int graph_size_location(
image_desc_t
*im,
int elements)
{
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area. If the option
** --full-size-mode is selected the size defines the total
** image size and the size available for the graph is
** calculated.
*/
/** +---+-----------------------------------+
** | y |...............graph title.........|
** | +---+-------------------------------+
** | a | y | |
** | x | | |
** | i | a | |
** | s | x | main graph area |
** | | i | |
** | t | s | |
** | i | | |
** | t | l | |
** | l | b +-------------------------------+
** | e | l | x axis labels |
** +---+---+-------------------------------+
** |....................legends............|
** +---------------------------------------+
** | watermark |
** +---------------------------------------+
*/
int Xvertical = 0, Xvertical2 = 0, Ytitle =
0, Xylabel = 0, Xmain = 0, Ymain =
0, Yxlabel = 0, Xspacing = 15, Yspacing = 15, Ywatermark = 4;
// no legends and no the shall be plotted it's easy
if (im->extra_flags & ONLY_GRAPH) {
im->xorigin = 0;
im->ximg = im->xsize;
im->yimg = im->ysize;
im->yorigin = im->ysize;
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
if(im->watermark[0] != '\0') {
Ywatermark = im->text_prop[TEXT_PROP_WATERMARK].size * 2;
}
// calculate the width of the left vertical legend
if (im->ylegend[0] != '\0') {
Xvertical = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
// calculate the width of the right vertical legend
if (im->second_axis_legend[0] != '\0') {
Xvertical2 = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
else{
Xvertical2 = Xspacing;
}
if (im->title[0] != '\0') {
/* The title is placed "inbetween" two text lines so it
** automatically has some vertical spacing. The horizontal
** spacing is added here, on each side.
*/
/* if necessary, reduce the font size of the title until it fits the image width */
Ytitle = im->text_prop[TEXT_PROP_TITLE].size * 2.6 + 10;
}
else{
// we have no title; get a little clearing from the top
Ytitle = Yspacing;
}
if (elements) {
if (im->draw_x_grid) {
// calculate the height of the horizontal labelling
Yxlabel = im->text_prop[TEXT_PROP_AXIS].size * 2.5;
}
if (im->draw_y_grid || im->forceleftspace) {
// calculate the width of the vertical labelling
Xylabel =
gfx_get_text_width(im, 0,
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth, "0") * im->unitslength;
}
}
// add some space to the labelling
Xylabel += Xspacing;
/* If the legend is printed besides the graph the width has to be
** calculated first. Placing the legend north or south of the
** graph requires the width calculation first, so the legend is
** skipped for the moment.
*/
im->legendheight = 0;
im->legendwidth = 0;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 1) == -1){
return -1;
}
}
}
if (im->extra_flags & FULL_SIZE_MODE) {
/* The actual size of the image to draw has been determined by the user.
** The graph area is the space remaining after accounting for the legend,
** the watermark, the axis labels, and the title.
*/
im->ximg = im->xsize;
im->yimg = im->ysize;
Xmain = im->ximg;
Ymain = im->yimg;
/* Now calculate the total size. Insert some spacing where
desired. im->xorigin and im->yorigin need to correspond
with the lower left corner of the main graph area or, if
this one is not set, the imaginary box surrounding the
pie chart area. */
/* Initial size calculation for the main graph area */
Xmain -= Xylabel;// + Xspacing;
if((im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
Xmain -= im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
Xmain -= Xylabel;
}
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
Xmain -= Xspacing;
}
Xmain -= Xvertical + Xvertical2;
/* limit the remaining space to 0 */
if(Xmain < 1){
Xmain = 1;
}
im->xsize = Xmain;
/* Putting the legend north or south, the height can now be calculated */
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
Ymain -= Yxlabel + im->legendheight;
}
else{
Ymain -= Yxlabel;
}
/* reserve space for the title *or* some padding above the graph */
Ymain -= Ytitle;
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
Ymain -= 0.5*Yspacing;
}
if (im->watermark[0] != '\0') {
Ymain -= Ywatermark;
}
/* limit the remaining height to 0 */
if(Ymain < 1){
Ymain = 1;
}
im->ysize = Ymain;
} else { /* dimension options -width and -height refer to the dimensions of the main graph area */
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area.
*/
if (elements) {
Xmain = im->xsize; // + Xspacing;
Ymain = im->ysize;
}
im->ximg = Xmain + Xylabel;
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->ximg += Xspacing;
}
if( (im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
im->ximg += im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
im->ximg += Xylabel;
}
im->ximg += Xvertical + Xvertical2;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
im->yimg = Ymain + Yxlabel;
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
im->yimg += im->legendheight;
}
/* reserve space for the title *or* some padding above the graph */
if (Ytitle) {
im->yimg += Ytitle;
} else {
im->yimg += 1.5 * Yspacing;
}
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
im->yimg += 0.5*Yspacing;
}
if (im->watermark[0] != '\0') {
im->yimg += Ywatermark;
}
}
/* In case of putting the legend in west or east position the first
** legend calculation might lead to wrong positions if some items
** are not aligned on the left hand side (e.g. centered) as the
** legendwidth wight have been increased after the item was placed.
** In this case the positions have to be recalculated.
*/
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 0) == -1){
return -1;
}
}
}
/* After calculating all dimensions
** it is now possible to calculate
** all offsets.
*/
switch(im->legendposition){
case NORTH:
im->xOriginTitle = (im->ximg / 2);
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + im->legendheight + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
break;
case WEST:
im->xOriginTitle = im->legendwidth + im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = im->legendwidth;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = im->legendwidth + Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = im->legendwidth + Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case SOUTH:
im->xOriginTitle = im->ximg / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle + Ymain + Yxlabel;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case EAST:
im->xOriginTitle = im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = Xvertical + Xylabel + Xmain + Xvertical2;
if (im->second_axis_scale != 0){
im->xOriginLegend += Xylabel;
}
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->xOriginTitle += Xspacing;
im->xOriginLegend += Xspacing;
im->xOriginLegendY += Xspacing;
im->xorigin += Xspacing;
im->xOriginLegendY2 += Xspacing;
}
break;
}
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
static cairo_status_t cairo_output(
void *closure,
const unsigned char
*data,
unsigned int length)
{
image_desc_t *im = (image_desc_t*)closure;
im->rendered_image =
(unsigned char*)realloc(im->rendered_image, im->rendered_image_size + length);
if (im->rendered_image == NULL)
return CAIRO_STATUS_WRITE_ERROR;
memcpy(im->rendered_image + im->rendered_image_size, data, length);
im->rendered_image_size += length;
return CAIRO_STATUS_SUCCESS;
}
/* draw that picture thing ... */
int graph_paint(
image_desc_t *im)
{
int i, ii;
int lazy = lazy_check(im);
double areazero = 0.0;
graph_desc_t *lastgdes = NULL;
rrd_infoval_t info;
// PangoFontMap *font_map = pango_cairo_font_map_get_default();
/* pull the data from the rrd files ... */
if (data_fetch(im) == -1)
return -1;
/* evaluate VDEF and CDEF operations ... */
if (data_calc(im) == -1)
return -1;
/* calculate and PRINT and GPRINT definitions. We have to do it at
* this point because it will affect the length of the legends
* if there are no graph elements (i==0) we stop here ...
* if we are lazy, try to quit ...
*/
i = print_calc(im);
if (i < 0)
return -1;
/* if we want and can be lazy ... quit now */
if (i == 0)
return 0;
/**************************************************************
*** Calculating sizes and locations became a bit confusing ***
*** so I moved this into a separate function. ***
**************************************************************/
if (graph_size_location(im, i) == -1)
return -1;
info.u_cnt = im->xorigin;
grinfo_push(im, sprintf_alloc("graph_left"), RD_I_CNT, info);
info.u_cnt = im->yorigin - im->ysize;
grinfo_push(im, sprintf_alloc("graph_top"), RD_I_CNT, info);
info.u_cnt = im->xsize;
grinfo_push(im, sprintf_alloc("graph_width"), RD_I_CNT, info);
info.u_cnt = im->ysize;
grinfo_push(im, sprintf_alloc("graph_height"), RD_I_CNT, info);
info.u_cnt = im->ximg;
grinfo_push(im, sprintf_alloc("image_width"), RD_I_CNT, info);
info.u_cnt = im->yimg;
grinfo_push(im, sprintf_alloc("image_height"), RD_I_CNT, info);
info.u_cnt = im->start;
grinfo_push(im, sprintf_alloc("graph_start"), RD_I_CNT, info);
info.u_cnt = im->end;
grinfo_push(im, sprintf_alloc("graph_end"), RD_I_CNT, info);
/* if we want and can be lazy ... quit now */
if (lazy)
return 0;
/* get actual drawing data and find min and max values */
if (data_proc(im) == -1)
return -1;
if (!im->logarithmic) {
si_unit(im);
}
/* identify si magnitude Kilo, Mega Giga ? */
if (!im->rigid && !im->logarithmic)
expand_range(im); /* make sure the upper and lower limit are
sensible values */
info.u_val = im->minval;
grinfo_push(im, sprintf_alloc("value_min"), RD_I_VAL, info);
info.u_val = im->maxval;
grinfo_push(im, sprintf_alloc("value_max"), RD_I_VAL, info);
if (!calc_horizontal_grid(im))
return -1;
/* reset precalc */
ytr(im, DNAN);
/* if (im->gridfit)
apply_gridfit(im); */
/* the actual graph is created by going through the individual
graph elements and then drawing them */
cairo_surface_destroy(im->surface);
switch (im->imgformat) {
case IF_PNG:
im->surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
im->ximg * im->zoom,
im->yimg * im->zoom);
break;
case IF_PDF:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
? cairo_pdf_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_pdf_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_EPS:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_ps_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_ps_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_SVG:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_svg_surface_create(im->
graphfile,
im->ximg * im->zoom, im->yimg * im->zoom)
: cairo_svg_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
cairo_svg_surface_restrict_to_version
(im->surface, CAIRO_SVG_VERSION_1_1);
break;
};
cairo_destroy(im->cr);
im->cr = cairo_create(im->surface);
cairo_set_antialias(im->cr, im->graph_antialias);
cairo_scale(im->cr, im->zoom, im->zoom);
// pango_cairo_font_map_set_resolution(PANGO_CAIRO_FONT_MAP(font_map), 100);
gfx_new_area(im, 0, 0, 0, im->yimg,
im->ximg, im->yimg, im->graph_col[GRC_BACK]);
gfx_add_point(im, im->ximg, 0);
gfx_close_path(im);
gfx_new_area(im, im->xorigin,
im->yorigin,
im->xorigin +
im->xsize, im->yorigin,
im->xorigin +
im->xsize,
im->yorigin - im->ysize, im->graph_col[GRC_CANVAS]);
gfx_add_point(im, im->xorigin, im->yorigin - im->ysize);
gfx_close_path(im);
cairo_rectangle(im->cr, im->xorigin, im->yorigin - im->ysize - 1.0,
im->xsize, im->ysize + 2.0);
cairo_clip(im->cr);
if (im->minval > 0.0)
areazero = im->minval;
if (im->maxval < 0.0)
areazero = im->maxval;
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_CDEF:
case GF_VDEF:
case GF_DEF:
case GF_PRINT:
case GF_GPRINT:
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_HRULE:
case GF_VRULE:
case GF_XPORT:
case GF_SHIFT:
break;
case GF_TICK:
for (ii = 0; ii < im->xsize; ii++) {
if (!isnan(im->gdes[i].p_data[ii])
&& im->gdes[i].p_data[ii] != 0.0) {
if (im->gdes[i].yrule > 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin + 1.0,
im->xorigin + ii,
im->yorigin -
im->gdes[i].yrule *
im->ysize, 1.0, im->gdes[i].col);
} else if (im->gdes[i].yrule < 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin - im->ysize - 1.0,
im->xorigin + ii,
im->yorigin - im->ysize -
im->gdes[i].
yrule *
im->ysize, 1.0, im->gdes[i].col);
}
}
}
break;
case GF_LINE:
case GF_AREA: {
rrd_value_t diffval = im->maxval - im->minval;
rrd_value_t maxlimit = im->maxval + 9 * diffval;
rrd_value_t minlimit = im->minval - 9 * diffval;
for (ii = 0; ii < im->xsize; ii++) {
/* fix data points at oo and -oo */
if (isinf(im->gdes[i].p_data[ii])) {
if (im->gdes[i].p_data[ii] > 0) {
im->gdes[i].p_data[ii] = im->maxval;
} else {
im->gdes[i].p_data[ii] = im->minval;
}
}
/* some versions of cairo go unstable when trying
to draw way out of the canvas ... lets not even try */
if (im->gdes[i].p_data[ii] > maxlimit) {
im->gdes[i].p_data[ii] = maxlimit;
}
if (im->gdes[i].p_data[ii] < minlimit) {
im->gdes[i].p_data[ii] = minlimit;
}
} /* for */
/* *******************************************************
a ___. (a,t)
| | ___
____| | | |
| |___|
-------|--t-1--t--------------------------------
if we know the value at time t was a then
we draw a square from t-1 to t with the value a.
********************************************************* */
if (im->gdes[i].col.alpha != 0.0) {
/* GF_LINE and friend */
if (im->gdes[i].gf == GF_LINE) {
double last_y = 0.0;
int draw_on = 0;
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
for (ii = 1; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])
|| (im->slopemode == 1
&& isnan(im->gdes[i].p_data[ii - 1]))) {
draw_on = 0;
continue;
}
if (draw_on == 0) {
last_y = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0) {
double x = ii - 1 + im->xorigin;
double y = last_y;
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
} else {
double x = ii - 1 + im->xorigin;
double y =
ytr(im, im->gdes[i].p_data[ii - 1]);
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
}
draw_on = 1;
} else {
double x1 = ii + im->xorigin;
double y1 = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0
&& !AlmostEqual2sComplement(y1, last_y, 4)) {
double x = ii - 1 + im->xorigin;
double y = y1;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
};
last_y = y1;
gfx_line_fit(im, &x1, &y1);
cairo_line_to(im->cr, x1, y1);
};
}
cairo_set_source_rgba(im->cr,
im->gdes[i].
col.red,
im->gdes[i].
col.green,
im->gdes[i].
col.blue, im->gdes[i].col.alpha);
cairo_set_line_cap(im->cr, CAIRO_LINE_CAP_ROUND);
cairo_set_line_join(im->cr, CAIRO_LINE_JOIN_ROUND);
cairo_stroke(im->cr);
cairo_restore(im->cr);
} else {
int idxI = -1;
double *foreY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *foreX =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backX =
(double *) malloc(sizeof(double) * im->xsize * 2);
int drawem = 0;
for (ii = 0; ii <= im->xsize; ii++) {
double ybase, ytop;
if (idxI > 0 && (drawem != 0 || ii == im->xsize)) {
int cntI = 1;
int lastI = 0;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI + 1], 4)) {
cntI++;
}
gfx_new_area(im,
backX[0], backY[0],
foreX[0], foreY[0],
foreX[cntI],
foreY[cntI], im->gdes[i].col);
while (cntI < idxI) {
lastI = cntI;
cntI++;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI
+ 1], 4)) {
cntI++;
}
gfx_add_point(im, foreX[cntI], foreY[cntI]);
}
gfx_add_point(im, backX[idxI], backY[idxI]);
while (idxI > 1) {
lastI = idxI;
idxI--;
while (idxI > 1
&&
AlmostEqual2sComplement(backY
[lastI],
backY[idxI], 4)
&&
AlmostEqual2sComplement(backY
[lastI],
backY
[idxI
- 1], 4)) {
idxI--;
}
gfx_add_point(im, backX[idxI], backY[idxI]);
}
idxI = -1;
drawem = 0;
gfx_close_path(im);
}
if (drawem != 0) {
drawem = 0;
idxI = -1;
}
if (ii == im->xsize)
break;
if (im->slopemode == 0 && ii == 0) {
continue;
}
if (isnan(im->gdes[i].p_data[ii])) {
drawem = 1;
continue;
}
ytop = ytr(im, im->gdes[i].p_data[ii]);
if (lastgdes && im->gdes[i].stack) {
ybase = ytr(im, lastgdes->p_data[ii]);
} else {
ybase = ytr(im, areazero);
}
if (ybase == ytop) {
drawem = 1;
continue;
}
if (ybase > ytop) {
double extra = ytop;
ytop = ybase;
ybase = extra;
}
if (im->slopemode == 0) {
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin - 1;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin - 1;
}
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin;
}
/* close up any remaining area */
free(foreY);
free(foreX);
free(backY);
free(backX);
} /* else GF_LINE */
}
/* if color != 0x0 */
/* make sure we do not run into trouble when stacking on NaN */
for (ii = 0; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])) {
if (lastgdes && (im->gdes[i].stack)) {
im->gdes[i].p_data[ii] = lastgdes->p_data[ii];
} else {
im->gdes[i].p_data[ii] = areazero;
}
}
}
lastgdes = &(im->gdes[i]);
break;
} /* GF_AREA, GF_LINE, GF_GRAD */
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
} /* switch */
}
cairo_reset_clip(im->cr);
/* grid_paint also does the text */
if (!(im->extra_flags & ONLY_GRAPH))
grid_paint(im);
if (!(im->extra_flags & ONLY_GRAPH))
axis_paint(im);
/* the RULES are the last thing to paint ... */
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_HRULE:
if (im->gdes[i].yrule >= im->minval
&& im->gdes[i].yrule <= im->maxval) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im, im->xorigin,
ytr(im, im->gdes[i].yrule),
im->xorigin + im->xsize,
ytr(im, im->gdes[i].yrule), 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
case GF_VRULE:
if (im->gdes[i].xrule >= im->start
&& im->gdes[i].xrule <= im->end) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im,
xtr(im, im->gdes[i].xrule),
im->yorigin, xtr(im,
im->
gdes[i].
xrule),
im->yorigin - im->ysize, 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
default:
break;
}
}
switch (im->imgformat) {
case IF_PNG:
{
cairo_status_t status;
status = strlen(im->graphfile) ?
cairo_surface_write_to_png(im->surface, im->graphfile)
: cairo_surface_write_to_png_stream(im->surface, &cairo_output,
im);
if (status != CAIRO_STATUS_SUCCESS) {
rrd_set_error("Could not save png to '%s'", im->graphfile);
return 1;
}
break;
}
default:
if (strlen(im->graphfile)) {
cairo_show_page(im->cr);
} else {
cairo_surface_finish(im->surface);
}
break;
}
return 0;
}
/*****************************************************
* graph stuff
*****************************************************/
int gdes_alloc(
image_desc_t *im)
{
im->gdes_c++;
if ((im->gdes = (graph_desc_t *)
rrd_realloc(im->gdes, (im->gdes_c)
* sizeof(graph_desc_t))) == NULL) {
rrd_set_error("realloc graph_descs");
return -1;
}
im->gdes[im->gdes_c - 1].step = im->step;
im->gdes[im->gdes_c - 1].step_orig = im->step;
im->gdes[im->gdes_c - 1].stack = 0;
im->gdes[im->gdes_c - 1].skipscale = 0;
im->gdes[im->gdes_c - 1].linewidth = 0;
im->gdes[im->gdes_c - 1].debug = 0;
im->gdes[im->gdes_c - 1].start = im->start;
im->gdes[im->gdes_c - 1].start_orig = im->start;
im->gdes[im->gdes_c - 1].end = im->end;
im->gdes[im->gdes_c - 1].end_orig = im->end;
im->gdes[im->gdes_c - 1].vname[0] = '\0';
im->gdes[im->gdes_c - 1].data = NULL;
im->gdes[im->gdes_c - 1].ds_namv = NULL;
im->gdes[im->gdes_c - 1].data_first = 0;
im->gdes[im->gdes_c - 1].p_data = NULL;
im->gdes[im->gdes_c - 1].rpnp = NULL;
im->gdes[im->gdes_c - 1].p_dashes = NULL;
im->gdes[im->gdes_c - 1].shift = 0.0;
im->gdes[im->gdes_c - 1].dash = 0;
im->gdes[im->gdes_c - 1].ndash = 0;
im->gdes[im->gdes_c - 1].offset = 0;
im->gdes[im->gdes_c - 1].col.red = 0.0;
im->gdes[im->gdes_c - 1].col.green = 0.0;
im->gdes[im->gdes_c - 1].col.blue = 0.0;
im->gdes[im->gdes_c - 1].col.alpha = 0.0;
im->gdes[im->gdes_c - 1].legend[0] = '\0';
im->gdes[im->gdes_c - 1].format[0] = '\0';
im->gdes[im->gdes_c - 1].strftm = 0;
im->gdes[im->gdes_c - 1].rrd[0] = '\0';
im->gdes[im->gdes_c - 1].ds = -1;
im->gdes[im->gdes_c - 1].cf_reduce = CF_AVERAGE;
im->gdes[im->gdes_c - 1].cf = CF_AVERAGE;
im->gdes[im->gdes_c - 1].yrule = DNAN;
im->gdes[im->gdes_c - 1].xrule = 0;
return 0;
}
/* copies input untill the first unescaped colon is found
or until input ends. backslashes have to be escaped as well */
int scan_for_col(
const char *const input,
int len,
char *const output)
{
int inp, outp = 0;
for (inp = 0; inp < len && input[inp] != ':' && input[inp] != '\0'; inp++) {
if (input[inp] == '\\'
&& input[inp + 1] != '\0'
&& (input[inp + 1] == '\\' || input[inp + 1] == ':')) {
output[outp++] = input[++inp];
} else {
output[outp++] = input[inp];
}
}
output[outp] = '\0';
return inp;
}
/* Now just a wrapper around rrd_graph_v */
int rrd_graph(
int argc,
char **argv,
char ***prdata,
int *xsize,
int *ysize,
FILE * stream,
double *ymin,
double *ymax)
{
int prlines = 0;
rrd_info_t *grinfo = NULL;
rrd_info_t *walker;
grinfo = rrd_graph_v(argc, argv);
if (grinfo == NULL)
return -1;
walker = grinfo;
(*prdata) = NULL;
while (walker) {
if (strcmp(walker->key, "image_info") == 0) {
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
/* imginfo goes to position 0 in the prdata array */
(*prdata)[prlines - 1] = (char*)malloc((strlen(walker->value.u_str)
+ 2) * sizeof(char));
strcpy((*prdata)[prlines - 1], walker->value.u_str);
(*prdata)[prlines] = NULL;
}
/* skip anything else */
walker = walker->next;
}
walker = grinfo;
*xsize = 0;
*ysize = 0;
*ymin = 0;
*ymax = 0;
while (walker) {
if (strcmp(walker->key, "image_width") == 0) {
*xsize = walker->value.u_cnt;
} else if (strcmp(walker->key, "image_height") == 0) {
*ysize = walker->value.u_cnt;
} else if (strcmp(walker->key, "value_min") == 0) {
*ymin = walker->value.u_val;
} else if (strcmp(walker->key, "value_max") == 0) {
*ymax = walker->value.u_val;
} else if (strncmp(walker->key, "print", 5) == 0) { /* keys are prdate[0..] */
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
(*prdata)[prlines - 1] = (char*)malloc((strlen(walker->value.u_str)
+ 2) * sizeof(char));
(*prdata)[prlines] = NULL;
strcpy((*prdata)[prlines - 1], walker->value.u_str);
} else if (strcmp(walker->key, "image") == 0) {
if ( fwrite(walker->value.u_blo.ptr, walker->value.u_blo.size, 1,
(stream ? stream : stdout)) == 0 && ferror(stream ? stream : stdout)){
rrd_set_error("writing image");
return 0;
}
}
/* skip anything else */
walker = walker->next;
}
rrd_info_free(grinfo);
return 0;
}
/* Some surgery done on this function, it became ridiculously big.
** Things moved:
** - initializing now in rrd_graph_init()
** - options parsing now in rrd_graph_options()
** - script parsing now in rrd_graph_script()
*/
rrd_info_t *rrd_graph_v(
int argc,
char **argv)
{
image_desc_t im;
rrd_info_t *grinfo;
char *old_locale;
rrd_graph_init(&im);
/* a dummy surface so that we can measure text sizes for placements */
old_locale = setlocale(LC_NUMERIC, "C");
rrd_graph_options(argc, argv, &im);
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
if (optind >= argc) {
rrd_info_free(im.grinfo);
im_free(&im);
rrd_set_error("missing filename");
return NULL;
}
if (strlen(argv[optind]) >= MAXPATH) {
rrd_set_error("filename (including path) too long");
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
strncpy(im.graphfile, argv[optind], MAXPATH - 1);
im.graphfile[MAXPATH - 1] = '\0';
if (strcmp(im.graphfile, "-") == 0) {
im.graphfile[0] = '\0';
}
rrd_graph_script(argc, argv, &im, 1);
setlocale(LC_NUMERIC, old_locale); /* reenable locale for rendering the graph */
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* Everything is now read and the actual work can start */
if (graph_paint(&im) == -1) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* The image is generated and needs to be output.
** Also, if needed, print a line with information about the image.
*/
if (im.imginfo) {
rrd_infoval_t info;
char *path;
char *filename;
if (bad_format_imginfo(im.imginfo)) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
path = strdup(im.graphfile);
filename = basename(path);
info.u_str =
sprintf_alloc(im.imginfo,
filename,
(long) (im.zoom *
im.ximg), (long) (im.zoom * im.yimg));
grinfo_push(&im, sprintf_alloc("image_info"), RD_I_STR, info);
free(info.u_str);
free(path);
}
if (im.rendered_image) {
rrd_infoval_t img;
img.u_blo.size = im.rendered_image_size;
img.u_blo.ptr = im.rendered_image;
grinfo_push(&im, sprintf_alloc("image"), RD_I_BLO, img);
}
grinfo = im.grinfo;
im_free(&im);
return grinfo;
}
static void
rrd_set_font_desc (
image_desc_t *im,int prop,char *font, double size ){
if (font){
strncpy(im->text_prop[prop].font, font, sizeof(text_prop[prop].font) - 1);
im->text_prop[prop].font[sizeof(text_prop[prop].font) - 1] = '\0';
/* if we already got one, drop it first */
pango_font_description_free(im->text_prop[prop].font_desc);
im->text_prop[prop].font_desc = pango_font_description_from_string( font );
};
if (size > 0){
im->text_prop[prop].size = size;
};
if (im->text_prop[prop].font_desc && im->text_prop[prop].size ){
pango_font_description_set_size(im->text_prop[prop].font_desc, im->text_prop[prop].size * PANGO_SCALE);
};
}
void rrd_graph_init(
image_desc_t
*im)
{
unsigned int i;
char *deffont = getenv("RRD_DEFAULT_FONT");
static PangoFontMap *fontmap = NULL;
PangoContext *context;
#ifdef HAVE_TZSET
tzset();
#endif
im->gdef_map = g_hash_table_new_full(g_str_hash, g_str_equal,g_free,NULL);
im->rrd_map = g_hash_table_new_full(g_str_hash, g_str_equal,g_free,NULL);
im->base = 1000;
im->daemon_addr = NULL;
im->draw_x_grid = 1;
im->draw_y_grid = 1;
im->draw_3d_border = 2;
im->dynamic_labels = 0;
im->extra_flags = 0;
im->font_options = cairo_font_options_create();
im->forceleftspace = 0;
im->gdes_c = 0;
im->gdes = NULL;
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
im->grid_dash_off = 1;
im->grid_dash_on = 1;
im->gridfit = 1;
im->grinfo = (rrd_info_t *) NULL;
im->grinfo_current = (rrd_info_t *) NULL;
im->imgformat = IF_PNG;
im->imginfo = NULL;
im->lazy = 0;
im->legenddirection = TOP_DOWN;
im->legendheight = 0;
im->legendposition = SOUTH;
im->legendwidth = 0;
im->logarithmic = 0;
im->maxval = DNAN;
im->minval = 0;
im->minval = DNAN;
im->magfact = 1;
im->prt_c = 0;
im->rigid = 0;
im->rendered_image_size = 0;
im->rendered_image = NULL;
im->slopemode = 0;
im->step = 0;
im->symbol = ' ';
im->tabwidth = 40.0;
im->title[0] = '\0';
im->unitsexponent = 9999;
im->unitslength = 6;
im->viewfactor = 1.0;
im->watermark[0] = '\0';
im->with_markup = 0;
im->ximg = 0;
im->xlab_user.minsec = -1;
im->xorigin = 0;
im->xOriginLegend = 0;
im->xOriginLegendY = 0;
im->xOriginLegendY2 = 0;
im->xOriginTitle = 0;
im->xsize = 400;
im->ygridstep = DNAN;
im->yimg = 0;
im->ylegend[0] = '\0';
im->second_axis_scale = 0; /* 0 disables it */
im->second_axis_shift = 0; /* no shift by default */
im->second_axis_legend[0] = '\0';
im->second_axis_format[0] = '\0';
im->primary_axis_format[0] = '\0';
im->yorigin = 0;
im->yOriginLegend = 0;
im->yOriginLegendY = 0;
im->yOriginLegendY2 = 0;
im->yOriginTitle = 0;
im->ysize = 100;
im->zoom = 1;
im->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 10, 10);
im->cr = cairo_create(im->surface);
for (i = 0; i < DIM(text_prop); i++) {
im->text_prop[i].size = -1;
im->text_prop[i].font_desc = NULL;
rrd_set_font_desc(im,i, deffont ? deffont : text_prop[i].font,text_prop[i].size);
}
if (fontmap == NULL){
fontmap = pango_cairo_font_map_get_default();
}
context = pango_cairo_font_map_create_context((PangoCairoFontMap*)fontmap);
pango_cairo_context_set_resolution(context, 100);
pango_cairo_update_context(im->cr,context);
im->layout = pango_layout_new(context);
g_object_unref (context);
// im->layout = pango_cairo_create_layout(im->cr);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
cairo_font_options_set_hint_metrics
(im->font_options, CAIRO_HINT_METRICS_ON);
cairo_font_options_set_antialias(im->font_options, CAIRO_ANTIALIAS_GRAY);
for (i = 0; i < DIM(graph_col); i++)
im->graph_col[i] = graph_col[i];
}
void rrd_graph_options(
int argc,
char *argv[],
image_desc_t
*im)
{
int stroff;
char *parsetime_error = NULL;
char scan_gtm[12], scan_mtm[12], scan_ltm[12], col_nam[12];
time_t start_tmp = 0, end_tmp = 0;
long long_tmp;
rrd_time_value_t start_tv, end_tv;
long unsigned int color;
/* defines for long options without a short equivalent. should be bytes,
and may not collide with (the ASCII value of) short options */
#define LONGOPT_UNITS_SI 255
/* *INDENT-OFF* */
struct option long_options[] = {
{ "alt-autoscale", no_argument, 0, 'A'},
{ "imgformat", required_argument, 0, 'a'},
{ "font-smoothing-threshold", required_argument, 0, 'B'},
{ "base", required_argument, 0, 'b'},
{ "color", required_argument, 0, 'c'},
{ "full-size-mode", no_argument, 0, 'D'},
{ "daemon", required_argument, 0, 'd'},
{ "slope-mode", no_argument, 0, 'E'},
{ "end", required_argument, 0, 'e'},
{ "force-rules-legend", no_argument, 0, 'F'},
{ "imginfo", required_argument, 0, 'f'},
{ "graph-render-mode", required_argument, 0, 'G'},
{ "no-legend", no_argument, 0, 'g'},
{ "height", required_argument, 0, 'h'},
{ "no-minor", no_argument, 0, 'I'},
{ "interlaced", no_argument, 0, 'i'},
{ "alt-autoscale-min", no_argument, 0, 'J'},
{ "only-graph", no_argument, 0, 'j'},
{ "units-length", required_argument, 0, 'L'},
{ "lower-limit", required_argument, 0, 'l'},
{ "alt-autoscale-max", no_argument, 0, 'M'},
{ "zoom", required_argument, 0, 'm'},
{ "no-gridfit", no_argument, 0, 'N'},
{ "font", required_argument, 0, 'n'},
{ "logarithmic", no_argument, 0, 'o'},
{ "pango-markup", no_argument, 0, 'P'},
{ "font-render-mode", required_argument, 0, 'R'},
{ "rigid", no_argument, 0, 'r'},
{ "step", required_argument, 0, 'S'},
{ "start", required_argument, 0, 's'},
{ "tabwidth", required_argument, 0, 'T'},
{ "title", required_argument, 0, 't'},
{ "upper-limit", required_argument, 0, 'u'},
{ "vertical-label", required_argument, 0, 'v'},
{ "watermark", required_argument, 0, 'W'},
{ "width", required_argument, 0, 'w'},
{ "units-exponent", required_argument, 0, 'X'},
{ "x-grid", required_argument, 0, 'x'},
{ "alt-y-grid", no_argument, 0, 'Y'},
{ "y-grid", required_argument, 0, 'y'},
{ "lazy", no_argument, 0, 'z'},
{ "units", required_argument, 0, LONGOPT_UNITS_SI},
{ "alt-y-mrtg", no_argument, 0, 1000}, /* this has no effect it is just here to save old apps from crashing when they use it */
{ "disable-rrdtool-tag",no_argument, 0, 1001},
{ "right-axis", required_argument, 0, 1002},
{ "right-axis-label", required_argument, 0, 1003},
{ "right-axis-format", required_argument, 0, 1004},
{ "legend-position", required_argument, 0, 1005},
{ "legend-direction", required_argument, 0, 1006},
{ "border", required_argument, 0, 1007},
{ "grid-dash", required_argument, 0, 1008},
{ "dynamic-labels", no_argument, 0, 1009},
{ "left-axis-format", required_argument, 0, 1010},
{ 0, 0, 0, 0}
};
/* *INDENT-ON* */
optind = 0;
opterr = 0; /* initialize getopt */
rrd_parsetime("end-24h", &start_tv);
rrd_parsetime("now", &end_tv);
while (1) {
int option_index = 0;
int opt;
int col_start, col_end;
opt = getopt_long(argc, argv,
"Aa:B:b:c:Dd:Ee:Ff:G:gh:IiJjL:l:Mm:Nn:oPR:rS:s:T:t:u:v:W:w:X:x:Yy:z",
long_options, &option_index);
if (opt == EOF)
break;
switch (opt) {
case 'I':
im->extra_flags |= NOMINOR;
break;
case 'Y':
im->extra_flags |= ALTYGRID;
break;
case 'A':
im->extra_flags |= ALTAUTOSCALE;
break;
case 'J':
im->extra_flags |= ALTAUTOSCALE_MIN;
break;
case 'M':
im->extra_flags |= ALTAUTOSCALE_MAX;
break;
case 'j':
im->extra_flags |= ONLY_GRAPH;
break;
case 'g':
im->extra_flags |= NOLEGEND;
break;
case 1005:
if (strcmp(optarg, "north") == 0) {
im->legendposition = NORTH;
} else if (strcmp(optarg, "west") == 0) {
im->legendposition = WEST;
} else if (strcmp(optarg, "south") == 0) {
im->legendposition = SOUTH;
} else if (strcmp(optarg, "east") == 0) {
im->legendposition = EAST;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 1006:
if (strcmp(optarg, "topdown") == 0) {
im->legenddirection = TOP_DOWN;
} else if (strcmp(optarg, "bottomup") == 0) {
im->legenddirection = BOTTOM_UP;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 'F':
im->extra_flags |= FORCE_RULES_LEGEND;
break;
case 1001:
im->extra_flags |= NO_RRDTOOL_TAG;
break;
case LONGOPT_UNITS_SI:
if (im->extra_flags & FORCE_UNITS) {
rrd_set_error("--units can only be used once!");
return;
}
if (strcmp(optarg, "si") == 0)
im->extra_flags |= FORCE_UNITS_SI;
else {
rrd_set_error("invalid argument for --units: %s", optarg);
return;
}
break;
case 'X':
im->unitsexponent = atoi(optarg);
break;
case 'L':
im->unitslength = atoi(optarg);
im->forceleftspace = 1;
break;
case 'T':
im->tabwidth = atof(optarg);
break;
case 'S':
im->step = atoi(optarg);
break;
case 'N':
im->gridfit = 0;
break;
case 'P':
im->with_markup = 1;
break;
case 's':
if ((parsetime_error = rrd_parsetime(optarg, &start_tv))) {
rrd_set_error("start time: %s", parsetime_error);
return;
}
break;
case 'e':
if ((parsetime_error = rrd_parsetime(optarg, &end_tv))) {
rrd_set_error("end time: %s", parsetime_error);
return;
}
break;
case 'x':
if (strcmp(optarg, "none") == 0) {
im->draw_x_grid = 0;
break;
};
if (sscanf(optarg,
"%10[A-Z]:%ld:%10[A-Z]:%ld:%10[A-Z]:%ld:%ld:%n",
scan_gtm,
&im->xlab_user.gridst,
scan_mtm,
&im->xlab_user.mgridst,
scan_ltm,
&im->xlab_user.labst,
&im->xlab_user.precis, &stroff) == 7 && stroff != 0) {
strncpy(im->xlab_form, optarg + stroff,
sizeof(im->xlab_form) - 1);
im->xlab_form[sizeof(im->xlab_form) - 1] = '\0';
if ((int)
(im->xlab_user.gridtm = tmt_conv(scan_gtm)) == -1) {
rrd_set_error("unknown keyword %s", scan_gtm);
return;
} else if ((int)
(im->xlab_user.mgridtm = tmt_conv(scan_mtm))
== -1) {
rrd_set_error("unknown keyword %s", scan_mtm);
return;
} else if ((int)
(im->xlab_user.labtm = tmt_conv(scan_ltm)) == -1) {
rrd_set_error("unknown keyword %s", scan_ltm);
return;
}
im->xlab_user.minsec = 1;
im->xlab_user.stst = im->xlab_form;
} else {
rrd_set_error("invalid x-grid format");
return;
}
break;
case 'y':
if (strcmp(optarg, "none") == 0) {
im->draw_y_grid = 0;
break;
};
if (sscanf(optarg, "%lf:%d", &im->ygridstep, &im->ylabfact) == 2) {
if (im->ygridstep <= 0) {
rrd_set_error("grid step must be > 0");
return;
} else if (im->ylabfact < 1) {
rrd_set_error("label factor must be > 0");
return;
}
} else {
rrd_set_error("invalid y-grid format");
return;
}
break;
case 1007:
im->draw_3d_border = atoi(optarg);
break;
case 1008: /* grid-dash */
if(sscanf(optarg,
"%lf:%lf",
&im->grid_dash_on,
&im->grid_dash_off) != 2) {
rrd_set_error("expected grid-dash format float:float");
return;
}
break;
case 1009: /* enable dynamic labels */
im->dynamic_labels = 1;
break;
case 1002: /* right y axis */
if(sscanf(optarg,
"%lf:%lf",
&im->second_axis_scale,
&im->second_axis_shift) == 2) {
if(im->second_axis_scale==0){
rrd_set_error("the second_axis_scale must not be 0");
return;
}
} else {
rrd_set_error("invalid right-axis format expected scale:shift");
return;
}
break;
case 1003:
strncpy(im->second_axis_legend,optarg,150);
im->second_axis_legend[150]='\0';
break;
case 1004:
if (bad_format_axis(optarg)){
return;
}
strncpy(im->second_axis_format,optarg,150);
im->second_axis_format[150]='\0';
break;
case 1010:
if (bad_format_axis(optarg)){
return;
}
strncpy(im->primary_axis_format,optarg,150);
im->primary_axis_format[150]='\0';
break;
case 'v':
strncpy(im->ylegend, optarg, 150);
im->ylegend[150] = '\0';
break;
case 'u':
im->maxval = atof(optarg);
break;
case 'l':
im->minval = atof(optarg);
break;
case 'b':
im->base = atol(optarg);
if (im->base != 1024 && im->base != 1000) {
rrd_set_error
("the only sensible value for base apart from 1000 is 1024");
return;
}
break;
case 'w':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("width below 10 pixels");
return;
}
im->xsize = long_tmp;
break;
case 'h':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("height below 10 pixels");
return;
}
im->ysize = long_tmp;
break;
case 'D':
im->extra_flags |= FULL_SIZE_MODE;
break;
case 'i':
/* interlaced png not supported at the moment */
break;
case 'r':
im->rigid = 1;
break;
case 'f':
im->imginfo = optarg;
break;
case 'a':
if ((int)
(im->imgformat = if_conv(optarg)) == -1) {
rrd_set_error("unsupported graphics format '%s'", optarg);
return;
}
break;
case 'z':
im->lazy = 1;
break;
case 'E':
im->slopemode = 1;
break;
case 'o':
im->logarithmic = 1;
break;
case 'c':
if (sscanf(optarg,
"%10[A-Z]#%n%8lx%n",
col_nam, &col_start, &color, &col_end) == 2) {
int ci;
int col_len = col_end - col_start;
switch (col_len) {
case 3:
color =
(((color & 0xF00) * 0x110000) | ((color & 0x0F0) *
0x011000) |
((color & 0x00F)
* 0x001100)
| 0x000000FF);
break;
case 4:
color =
(((color & 0xF000) *
0x11000) | ((color & 0x0F00) *
0x01100) | ((color &
0x00F0) *
0x00110) |
((color & 0x000F) * 0x00011)
);
break;
case 6:
color = (color << 8) + 0xff /* shift left by 8 */ ;
break;
case 8:
break;
default:
rrd_set_error("the color format is #RRGGBB[AA]");
return;
}
if ((ci = grc_conv(col_nam)) != -1) {
im->graph_col[ci] = gfx_hex_to_col(color);
} else {
rrd_set_error("invalid color name '%s'", col_nam);
return;
}
} else {
rrd_set_error("invalid color def format");
return;
}
break;
case 'n':{
char prop[15];
double size = 1;
int end;
if (sscanf(optarg, "%10[A-Z]:%lf%n", prop, &size, &end) >= 2) {
int sindex, propidx;
if ((sindex = text_prop_conv(prop)) != -1) {
for (propidx = sindex;
propidx < TEXT_PROP_LAST; propidx++) {
if (size > 0) {
rrd_set_font_desc(im,propidx,NULL,size);
}
if ((int) strlen(optarg) > end+2) {
if (optarg[end] == ':') {
rrd_set_font_desc(im,propidx,optarg + end + 1,0);
} else {
rrd_set_error
("expected : after font size in '%s'",
optarg);
return;
}
}
/* only run the for loop for DEFAULT (0) for
all others, we break here. woodo programming */
if (propidx == sindex && sindex != 0)
break;
}
} else {
rrd_set_error("invalid fonttag '%s'", prop);
return;
}
} else {
rrd_set_error("invalid text property format");
return;
}
break;
}
case 'm':
im->zoom = atof(optarg);
if (im->zoom <= 0.0) {
rrd_set_error("zoom factor must be > 0");
return;
}
break;
case 't':
strncpy(im->title, optarg, 150);
im->title[150] = '\0';
break;
case 'R':
if (strcmp(optarg, "normal") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else if (strcmp(optarg, "light") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_SLIGHT);
} else if (strcmp(optarg, "mono") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_NONE);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else {
rrd_set_error("unknown font-render-mode '%s'", optarg);
return;
}
break;
case 'G':
if (strcmp(optarg, "normal") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
else if (strcmp(optarg, "mono") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_NONE;
else {
rrd_set_error("unknown graph-render-mode '%s'", optarg);
return;
}
break;
case 'B':
/* not supported curently */
break;
case 'W':
strncpy(im->watermark, optarg, 100);
im->watermark[99] = '\0';
break;
case 'd':
{
if (im->daemon_addr != NULL)
{
rrd_set_error ("You cannot specify --daemon "
"more than once.");
return;
}
im->daemon_addr = strdup(optarg);
if (im->daemon_addr == NULL)
{
rrd_set_error("strdup failed");
return;
}
break;
}
case '?':
if (optopt != 0)
rrd_set_error("unknown option '%c'", optopt);
else
rrd_set_error("unknown option '%s'", argv[optind - 1]);
return;
}
} /* while (1) */
{ /* try to connect to rrdcached */
int status = rrdc_connect(im->daemon_addr);
if (status != 0) return;
}
pango_cairo_context_set_font_options(pango_layout_get_context(im->layout), im->font_options);
pango_layout_context_changed(im->layout);
if (im->logarithmic && im->minval <= 0) {
rrd_set_error
("for a logarithmic yaxis you must specify a lower-limit > 0");
return;
}
if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
/* error string is set in rrd_parsetime.c */
return;
}
if (start_tmp < 3600 * 24 * 365 * 10) {
rrd_set_error
("the first entry to fetch should be after 1980 (%ld)",
start_tmp);
return;
}
if (end_tmp < start_tmp) {
rrd_set_error
("start (%ld) should be less than end (%ld)", start_tmp, end_tmp);
return;
}
im->start = start_tmp;
im->end = end_tmp;
im->step = max((long) im->step, (im->end - im->start) / im->xsize);
}
int rrd_graph_color(
image_desc_t
*im,
char *var,
char *err,
int optional)
{
char *color;
graph_desc_t *gdp = &im->gdes[im->gdes_c - 1];
color = strstr(var, "#");
if (color == NULL) {
if (optional == 0) {
rrd_set_error("Found no color in %s", err);
return 0;
}
return 0;
} else {
int n = 0;
char *rest;
long unsigned int col;
rest = strstr(color, ":");
if (rest != NULL)
n = rest - color;
else
n = strlen(color);
switch (n) {
case 7:
sscanf(color, "#%6lx%n", &col, &n);
col = (col << 8) + 0xff /* shift left by 8 */ ;
if (n != 7)
rrd_set_error("Color problem in %s", err);
break;
case 9:
sscanf(color, "#%8lx%n", &col, &n);
if (n == 9)
break;
default:
rrd_set_error("Color problem in %s", err);
}
if (rrd_test_error())
return 0;
gdp->col = gfx_hex_to_col(col);
return n;
}
}
static int bad_format_check(const char *pattern, char *fmt) {
GError *gerr = NULL;
GRegex *re = g_regex_new(pattern, G_REGEX_EXTENDED, 0, &gerr);
GMatchInfo *mi;
if (gerr != NULL) {
rrd_set_error("cannot compile regular expression: %s (%s)", gerr->message,pattern);
return 1;
}
int m = g_regex_match(re, fmt, 0, &mi);
g_match_info_free (mi);
g_regex_unref(re);
if (!m) {
rrd_set_error("invalid format string '%s' (should match '%s')",fmt,pattern);
return 1;
}
return 0;
}
#define SAFE_STRING "(?:[^%]+|%%)*"
int bad_format_imginfo(char *fmt){
return bad_format_check("^" SAFE_STRING "%s" SAFE_STRING "%lu" SAFE_STRING "%lu" SAFE_STRING "$",fmt);
}
#define FLOAT_STRING "%[+- 0#]?[0-9]*([.][0-9]+)?l[eEfF]"
int bad_format_axis(char *fmt){
return bad_format_check("^" SAFE_STRING FLOAT_STRING SAFE_STRING "$",fmt);
}
int bad_format_print(char *fmt){
return bad_format_check("^" SAFE_STRING FLOAT_STRING SAFE_STRING "%s" SAFE_STRING "$",fmt);
}
int vdef_parse(
struct graph_desc_t
*gdes,
const char *const str)
{
/* A VDEF currently is either "func" or "param,func"
* so the parsing is rather simple. Change if needed.
*/
double param;
char func[30];
int n;
n = 0;
sscanf(str, "%le,%29[A-Z]%n", ¶m, func, &n);
if (n == (int) strlen(str)) { /* matched */
;
} else {
n = 0;
sscanf(str, "%29[A-Z]%n", func, &n);
if (n == (int) strlen(str)) { /* matched */
param = DNAN;
} else {
rrd_set_error
("Unknown function string '%s' in VDEF '%s'",
str, gdes->vname);
return -1;
}
}
if (!strcmp("PERCENT", func))
gdes->vf.op = VDEF_PERCENT;
else if (!strcmp("PERCENTNAN", func))
gdes->vf.op = VDEF_PERCENTNAN;
else if (!strcmp("MAXIMUM", func))
gdes->vf.op = VDEF_MAXIMUM;
else if (!strcmp("AVERAGE", func))
gdes->vf.op = VDEF_AVERAGE;
else if (!strcmp("STDEV", func))
gdes->vf.op = VDEF_STDEV;
else if (!strcmp("MINIMUM", func))
gdes->vf.op = VDEF_MINIMUM;
else if (!strcmp("TOTAL", func))
gdes->vf.op = VDEF_TOTAL;
else if (!strcmp("FIRST", func))
gdes->vf.op = VDEF_FIRST;
else if (!strcmp("LAST", func))
gdes->vf.op = VDEF_LAST;
else if (!strcmp("LSLSLOPE", func))
gdes->vf.op = VDEF_LSLSLOPE;
else if (!strcmp("LSLINT", func))
gdes->vf.op = VDEF_LSLINT;
else if (!strcmp("LSLCORREL", func))
gdes->vf.op = VDEF_LSLCORREL;
else {
rrd_set_error
("Unknown function '%s' in VDEF '%s'\n", func, gdes->vname);
return -1;
};
switch (gdes->vf.op) {
case VDEF_PERCENT:
case VDEF_PERCENTNAN:
if (isnan(param)) { /* no parameter given */
rrd_set_error
("Function '%s' needs parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
if (param >= 0.0 && param <= 100.0) {
gdes->vf.param = param;
gdes->vf.val = DNAN; /* undefined */
gdes->vf.when = 0; /* undefined */
} else {
rrd_set_error
("Parameter '%f' out of range in VDEF '%s'\n",
param, gdes->vname);
return -1;
};
break;
case VDEF_MAXIMUM:
case VDEF_AVERAGE:
case VDEF_STDEV:
case VDEF_MINIMUM:
case VDEF_TOTAL:
case VDEF_FIRST:
case VDEF_LAST:
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:
if (isnan(param)) {
gdes->vf.param = DNAN;
gdes->vf.val = DNAN;
gdes->vf.when = 0;
} else {
rrd_set_error
("Function '%s' needs no parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
break;
};
return 0;
}
int vdef_calc(
image_desc_t *im,
int gdi)
{
graph_desc_t *src, *dst;
rrd_value_t *data;
long step, steps;
dst = &im->gdes[gdi];
src = &im->gdes[dst->vidx];
data = src->data + src->ds;
steps = (src->end - src->start) / src->step;
#if 0
printf
("DEBUG: start == %lu, end == %lu, %lu steps\n",
src->start, src->end, steps);
#endif
switch (dst->vf.op) {
case VDEF_PERCENT:{
rrd_value_t *array;
int field;
if ((array = (rrd_value_t*)malloc(steps * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
for (step = 0; step < steps; step++) {
array[step] = data[step * src->ds_cnt];
}
qsort(array, step, sizeof(double), vdef_percent_compar);
field = round((dst->vf.param * (double)(steps - 1)) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
free(array);
#if 0
for (step = 0; step < steps; step++)
printf("DEBUG: %3li:%10.2f %c\n",
step, array[step], step == field ? '*' : ' ');
#endif
}
break;
case VDEF_PERCENTNAN:{
rrd_value_t *array;
int field;
/* count number of "valid" values */
int nancount=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) { nancount++; }
}
/* and allocate it */
if ((array = (rrd_value_t*)malloc(nancount * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
/* and fill it in */
field=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) {
array[field] = data[step * src->ds_cnt];
field++;
}
}
qsort(array, nancount, sizeof(double), vdef_percent_compar);
field = round( dst->vf.param * (double)(nancount - 1) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
free(array);
}
break;
case VDEF_MAXIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] > dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
}
step++;
}
break;
case VDEF_TOTAL:
case VDEF_STDEV:
case VDEF_AVERAGE:{
int cnt = 0;
double sum = 0.0;
double average = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += data[step * src->ds_cnt];
cnt++;
};
}
if (cnt) {
if (dst->vf.op == VDEF_TOTAL) {
dst->vf.val = sum * src->step;
dst->vf.when = 0; /* no time component */
} else if (dst->vf.op == VDEF_AVERAGE) {
dst->vf.val = sum / cnt;
dst->vf.when = 0; /* no time component */
} else {
average = sum / cnt;
sum = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += pow((data[step * src->ds_cnt] - average), 2.0);
};
}
dst->vf.val = pow(sum / cnt, 0.5);
dst->vf.when = 0; /* no time component */
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
}
}
break;
case VDEF_MINIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] < dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
}
step++;
}
break;
case VDEF_FIRST:
/* The time value returned here is one step before the
* actual time value. This is the start of the first
* non-NaN interval.
*/
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + step * src->step;
}
break;
case VDEF_LAST:
/* The time value returned here is the
* actual time value. This is the end of the last
* non-NaN interval.
*/
step = steps - 1;
while (step >= 0 && isnan(data[step * src->ds_cnt]))
step--;
if (step < 0) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
}
break;
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:{
/* Bestfit line by linear least squares method */
int cnt = 0;
double SUMx, SUMy, SUMxy, SUMxx, SUMyy, slope, y_intercept, correl;
SUMx = 0;
SUMy = 0;
SUMxy = 0;
SUMxx = 0;
SUMyy = 0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
cnt++;
SUMx += step;
SUMxx += step * step;
SUMxy += step * data[step * src->ds_cnt];
SUMy += data[step * src->ds_cnt];
SUMyy += data[step * src->ds_cnt] * data[step * src->ds_cnt];
};
}
slope = (SUMx * SUMy - cnt * SUMxy) / (SUMx * SUMx - cnt * SUMxx);
y_intercept = (SUMy - slope * SUMx) / cnt;
correl =
(SUMxy -
(SUMx * SUMy) / cnt) /
sqrt((SUMxx -
(SUMx * SUMx) / cnt) * (SUMyy - (SUMy * SUMy) / cnt));
if (cnt) {
if (dst->vf.op == VDEF_LSLSLOPE) {
dst->vf.val = slope;
dst->vf.when = 0;
} else if (dst->vf.op == VDEF_LSLINT) {
dst->vf.val = y_intercept;
dst->vf.when = 0;
} else if (dst->vf.op == VDEF_LSLCORREL) {
dst->vf.val = correl;
dst->vf.when = 0;
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
}
}
break;
}
return 0;
}
/* NaN < -INF < finite_values < INF */
int vdef_percent_compar(
const void
*a,
const void
*b)
{
/* Equality is not returned; this doesn't hurt except
* (maybe) for a little performance.
*/
/* First catch NaN values. They are smallest */
if (isnan(*(double *) a))
return -1;
if (isnan(*(double *) b))
return 1;
/* NaN doesn't reach this part so INF and -INF are extremes.
* The sign from isinf() is compatible with the sign we return
*/
if (isinf(*(double *) a))
return isinf(*(double *) a);
if (isinf(*(double *) b))
return isinf(*(double *) b);
/* If we reach this, both values must be finite */
if (*(double *) a < *(double *) b)
return -1;
else
return 1;
}
void grinfo_push(
image_desc_t *im,
char *key,
rrd_info_type_t type,
rrd_infoval_t value)
{
im->grinfo_current = rrd_info_push(im->grinfo_current, key, type, value);
if (im->grinfo == NULL) {
im->grinfo = im->grinfo_current;
}
}
| ./CrossVul/dataset_final_sorted/CWE-134/c/good_2266_0 |
crossvul-cpp_data_bad_2610_1 | /* omzmq3.c
* Copyright 2012 Talksum, Inc
* Using the czmq interface to zeromq, we output
* to a zmq socket.
* Copyright (C) 2014 Rainer Gerhards
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* Author: David Kelly
* <davidk@talksum.com>
*/
#include "config.h"
#include "rsyslog.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include "conf.h"
#include "syslogd-types.h"
#include "srUtils.h"
#include "template.h"
#include "module-template.h"
#include "errmsg.h"
#include "cfsysline.h"
#include <czmq.h>
MODULE_TYPE_OUTPUT
MODULE_TYPE_NOKEEP
MODULE_CNFNAME("omzmq3")
DEF_OMOD_STATIC_DATA
DEFobjCurrIf(errmsg)
static pthread_mutex_t mutDoAct = PTHREAD_MUTEX_INITIALIZER;
/* convienent symbols to denote a socket we want to bind
vs one we want to just connect to
*/
#define ACTION_CONNECT 1
#define ACTION_BIND 2
/* ----------------------------------------------------------------------------
* structs to describe sockets
*/
struct socket_type {
char* name;
int type;
};
/* more overkill, but seems nice to be consistent. */
struct socket_action {
char* name;
int action;
};
typedef struct _instanceData {
void* socket;
uchar* description;
int type;
int action;
int sndHWM;
int rcvHWM;
uchar* identity;
int sndBuf;
int rcvBuf;
int linger;
int backlog;
int sndTimeout;
int rcvTimeout;
int maxMsgSize;
int rate;
int recoveryIVL;
int multicastHops;
int reconnectIVL;
int reconnectIVLMax;
int ipv4Only;
int affinity;
uchar* tplName;
} instanceData;
typedef struct wrkrInstanceData {
instanceData *pData;
} wrkrInstanceData_t;
/* ----------------------------------------------------------------------------
* Static definitions/initializations
*/
/* only 1 zctx for all the sockets, with an adjustable number of
worker threads which may be useful if we use affinity in particular
sockets
*/
static zctx_t* s_context = NULL;
static int s_workerThreads = -1;
static struct socket_type types[] = {
{"PUB", ZMQ_PUB },
{"PUSH", ZMQ_PUSH },
{"DEALER", ZMQ_DEALER },
{"XPUB", ZMQ_XPUB }
};
static struct socket_action actions[] = {
{"BIND", ACTION_BIND},
{"CONNECT", ACTION_CONNECT},
};
static struct cnfparamdescr actpdescr[] = {
{ "description", eCmdHdlrGetWord, 0 },
{ "sockType", eCmdHdlrGetWord, 0 },
{ "action", eCmdHdlrGetWord, 0 },
{ "sndHWM", eCmdHdlrInt, 0 },
{ "rcvHWM", eCmdHdlrInt, 0 },
{ "identity", eCmdHdlrGetWord, 0 },
{ "sndBuf", eCmdHdlrInt, 0 },
{ "rcvBuf", eCmdHdlrInt, 0 },
{ "linger", eCmdHdlrInt, 0 },
{ "backlog", eCmdHdlrInt, 0 },
{ "sndTimeout", eCmdHdlrInt, 0 },
{ "rcvTimeout", eCmdHdlrInt, 0 },
{ "maxMsgSize", eCmdHdlrInt, 0 },
{ "rate", eCmdHdlrInt, 0 },
{ "recoveryIVL", eCmdHdlrInt, 0 },
{ "multicastHops", eCmdHdlrInt, 0 },
{ "reconnectIVL", eCmdHdlrInt, 0 },
{ "reconnectIVLMax", eCmdHdlrInt, 0 },
{ "ipv4Only", eCmdHdlrInt, 0 },
{ "affinity", eCmdHdlrInt, 0 },
{ "globalWorkerThreads", eCmdHdlrInt, 0 },
{ "template", eCmdHdlrGetWord, 1 }
};
static struct cnfparamblk actpblk = {
CNFPARAMBLK_VERSION,
sizeof(actpdescr)/sizeof(struct cnfparamdescr),
actpdescr
};
/* ----------------------------------------------------------------------------
* Helper Functions
*/
/* get the name of a socket type, return the ZMQ_XXX type
or -1 if not a supported type (see above)
*/
int getSocketType(char* name) {
int type = -1;
uint i;
for(i=0; i<sizeof(types)/sizeof(struct socket_type); ++i) {
if( !strcmp(types[i].name, name) ) {
type = types[i].type;
break;
}
}
return type;
}
static int getSocketAction(char* name) {
int action = -1;
uint i;
for(i=0; i < sizeof(actions)/sizeof(struct socket_action); ++i) {
if(!strcmp(actions[i].name, name)) {
action = actions[i].action;
break;
}
}
return action;
}
/* closeZMQ will destroy the context and
* associated socket
*/
static void closeZMQ(instanceData* pData) {
errmsg.LogError(0, NO_ERRCODE, "closeZMQ called");
if(s_context && pData->socket) {
if(pData->socket != NULL) {
zsocket_destroy(s_context, pData->socket);
}
}
}
static rsRetVal initZMQ(instanceData* pData) {
DEFiRet;
/* create the context if necessary. */
if (NULL == s_context) {
zsys_handler_set(NULL);
s_context = zctx_new();
if (s_workerThreads > 0) zctx_set_iothreads(s_context, s_workerThreads);
}
pData->socket = zsocket_new(s_context, pData->type);
if (NULL == pData->socket) {
errmsg.LogError(0, RS_RET_NO_ERRCODE,
"omzmq3: zsocket_new failed for %s: %s",
pData->description, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
/* use czmq defaults for these, unless set to non-default values */
if(pData->identity) zsocket_set_identity(pData->socket, (char*)pData->identity);
if(pData->sndBuf > -1) zsocket_set_sndbuf(pData->socket, pData->sndBuf);
if(pData->rcvBuf > -1) zsocket_set_sndbuf(pData->socket, pData->rcvBuf);
if(pData->linger > -1) zsocket_set_linger(pData->socket, pData->linger);
if(pData->backlog > -1) zsocket_set_backlog(pData->socket, pData->backlog);
if(pData->sndTimeout > -1) zsocket_set_sndtimeo(pData->socket, pData->sndTimeout);
if(pData->rcvTimeout > -1) zsocket_set_rcvtimeo(pData->socket, pData->rcvTimeout);
if(pData->maxMsgSize > -1) zsocket_set_maxmsgsize(pData->socket, pData->maxMsgSize);
if(pData->rate > -1) zsocket_set_rate(pData->socket, pData->rate);
if(pData->recoveryIVL > -1) zsocket_set_recovery_ivl(pData->socket, pData->recoveryIVL);
if(pData->multicastHops > -1) zsocket_set_multicast_hops(pData->socket, pData->multicastHops);
if(pData->reconnectIVL > -1) zsocket_set_reconnect_ivl(pData->socket, pData->reconnectIVL);
if(pData->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(pData->socket, pData->reconnectIVLMax);
if(pData->ipv4Only > -1) zsocket_set_ipv4only(pData->socket, pData->ipv4Only);
if(pData->affinity != 1) zsocket_set_affinity(pData->socket, pData->affinity);
if(pData->rcvHWM > -1) zsocket_set_rcvhwm(pData->socket, pData->rcvHWM);
if(pData->sndHWM > -1) zsocket_set_sndhwm(pData->socket, pData->sndHWM);
/* bind or connect to it */
if (pData->action == ACTION_BIND) {
/* bind asserts, so no need to test return val here
which isn't the greatest api -- oh well */
if(-1 == zsocket_bind(pData->socket, (char*)pData->description)) {
errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: bind failed for %s: %s",
pData->description, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
DBGPRINTF("omzmq3: bind to %s successful\n",pData->description);
} else {
if(-1 == zsocket_connect(pData->socket, (char*)pData->description)) {
errmsg.LogError(0, RS_RET_NO_ERRCODE, "omzmq3: connect failed for %s: %s",
pData->description, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_NO_ERRCODE);
}
DBGPRINTF("omzmq3: connect to %s successful", pData->description);
}
finalize_it:
RETiRet;
}
rsRetVal writeZMQ(uchar* msg, instanceData* pData) {
DEFiRet;
/* initialize if necessary */
if(NULL == pData->socket)
CHKiRet(initZMQ(pData));
/* send it */
int result = zstr_send(pData->socket, (char*)msg);
/* whine if things went wrong */
if (result == -1) {
errmsg.LogError(0, NO_ERRCODE, "omzmq3: send of %s failed: %s", msg, zmq_strerror(errno));
ABORT_FINALIZE(RS_RET_ERR);
}
finalize_it:
RETiRet;
}
static void
setInstParamDefaults(instanceData* pData) {
pData->description = NULL;
pData->socket = NULL;
pData->tplName = NULL;
pData->type = ZMQ_PUB;
pData->action = ACTION_BIND;
pData->sndHWM = -1;
pData->rcvHWM = -1;
pData->identity = NULL;
pData->sndBuf = -1;
pData->rcvBuf = -1;
pData->linger = -1;
pData->backlog = -1;
pData->sndTimeout = -1;
pData->rcvTimeout = -1;
pData->maxMsgSize = -1;
pData->rate = -1;
pData->recoveryIVL = -1;
pData->multicastHops = -1;
pData->reconnectIVL = -1;
pData->reconnectIVLMax = -1;
pData->ipv4Only = -1;
pData->affinity = 1;
}
/* ----------------------------------------------------------------------------
* Output Module Functions
*/
BEGINcreateInstance
CODESTARTcreateInstance
ENDcreateInstance
BEGINcreateWrkrInstance
CODESTARTcreateWrkrInstance
ENDcreateWrkrInstance
BEGINisCompatibleWithFeature
CODESTARTisCompatibleWithFeature
if(eFeat == sFEATURERepeatedMsgReduction)
iRet = RS_RET_OK;
ENDisCompatibleWithFeature
BEGINdbgPrintInstInfo
CODESTARTdbgPrintInstInfo
ENDdbgPrintInstInfo
BEGINfreeInstance
CODESTARTfreeInstance
closeZMQ(pData);
free(pData->description);
free(pData->tplName);
free(pData->identity);
ENDfreeInstance
BEGINfreeWrkrInstance
CODESTARTfreeWrkrInstance
ENDfreeWrkrInstance
BEGINtryResume
CODESTARTtryResume
pthread_mutex_lock(&mutDoAct);
if(NULL == pWrkrData->pData->socket)
iRet = initZMQ(pWrkrData->pData);
pthread_mutex_unlock(&mutDoAct);
ENDtryResume
BEGINdoAction
instanceData *pData = pWrkrData->pData;
CODESTARTdoAction
pthread_mutex_lock(&mutDoAct);
iRet = writeZMQ(ppString[0], pData);
pthread_mutex_unlock(&mutDoAct);
ENDdoAction
BEGINnewActInst
struct cnfparamvals *pvals;
int i;
CODESTARTnewActInst
if ((pvals = nvlstGetParams(lst, &actpblk, NULL)) == NULL) {
ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
}
CHKiRet(createInstance(&pData));
setInstParamDefaults(pData);
CODE_STD_STRING_REQUESTnewActInst(1)
for (i = 0; i < actpblk.nParams; ++i) {
if (!pvals[i].bUsed)
continue;
if (!strcmp(actpblk.descr[i].name, "description")) {
pData->description = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if (!strcmp(actpblk.descr[i].name, "template")) {
pData->tplName = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if (!strcmp(actpblk.descr[i].name, "sockType")){
pData->type = getSocketType(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if (!strcmp(actpblk.descr[i].name, "action")){
pData->action = getSocketAction(es_str2cstr(pvals[i].val.d.estr, NULL));
} else if (!strcmp(actpblk.descr[i].name, "sndHWM")) {
pData->sndHWM = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rcvHWM")) {
pData->rcvHWM = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "identity")){
pData->identity = (uchar*)es_str2cstr(pvals[i].val.d.estr, NULL);
} else if (!strcmp(actpblk.descr[i].name, "sndBuf")) {
pData->sndBuf = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rcvBuf")) {
pData->rcvBuf = (int) pvals[i].val.d.n;
} else if(!strcmp(actpblk.descr[i].name, "linger")) {
pData->linger = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "backlog")) {
pData->backlog = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "sndTimeout")) {
pData->sndTimeout = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rcvTimeout")) {
pData->rcvTimeout = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "maxMsgSize")) {
pData->maxMsgSize = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "rate")) {
pData->rate = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "recoveryIVL")) {
pData->recoveryIVL = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "multicastHops")) {
pData->multicastHops = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "reconnectIVL")) {
pData->reconnectIVL = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "reconnectIVLMax")) {
pData->reconnectIVLMax = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "ipv4Only")) {
pData->ipv4Only = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "affinity")) {
pData->affinity = (int) pvals[i].val.d.n;
} else if (!strcmp(actpblk.descr[i].name, "globalWorkerThreads")) {
s_workerThreads = (int) pvals[i].val.d.n;
} else {
errmsg.LogError(0, NO_ERRCODE, "omzmq3: program error, non-handled "
"param '%s'\n", actpblk.descr[i].name);
}
}
if (pData->tplName == NULL) {
CHKiRet(OMSRsetEntry(*ppOMSR, 0, (uchar*)strdup("RSYSLOG_ForwardFormat"), OMSR_NO_RQD_TPL_OPTS));
} else {
CHKiRet(OMSRsetEntry(*ppOMSR, 0, (uchar*)pData->tplName, OMSR_NO_RQD_TPL_OPTS));
}
if (NULL == pData->description) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR, "omzmq3: you didn't enter a description");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
if (pData->type == -1) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR, "omzmq3: unknown socket type.");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
if (pData->action == -1) {
errmsg.LogError(0, RS_RET_CONFIG_ERROR, "omzmq3: unknown socket action");
ABORT_FINALIZE(RS_RET_CONFIG_ERROR);
}
CODE_STD_FINALIZERnewActInst
cnfparamvalsDestruct(pvals, &actpblk);
ENDnewActInst
BEGINparseSelectorAct
CODESTARTparseSelectorAct
/* tell the engine we only want one template string */
CODE_STD_STRING_REQUESTparseSelectorAct(1)
if(!strncmp((char*) p, ":omzmq3:", sizeof(":omzmq3:") - 1))
errmsg.LogError(0, RS_RET_LEGA_ACT_NOT_SUPPORTED,
"omzmq3 supports only v6 config format, use: "
"action(type=\"omzmq3\" serverport=...)");
ABORT_FINALIZE(RS_RET_CONFLINE_UNPROCESSED);
CODE_STD_FINALIZERparseSelectorAct
ENDparseSelectorAct
BEGINinitConfVars /* (re)set config variables to defaults */
CODESTARTinitConfVars
s_workerThreads = -1;
ENDinitConfVars
BEGINmodExit
CODESTARTmodExit
if (NULL != s_context) {
zctx_destroy(&s_context);
s_context=NULL;
}
ENDmodExit
BEGINqueryEtryPt
CODESTARTqueryEtryPt
CODEqueryEtryPt_STD_OMOD_QUERIES
CODEqueryEtryPt_STD_CONF2_OMOD_QUERIES
CODEqueryEtryPt_STD_OMOD8_QUERIES
ENDqueryEtryPt
BEGINmodInit()
CODESTARTmodInit
*ipIFVersProvided = CURR_MOD_IF_VERSION; /* only supports rsyslog 6 configs */
CODEmodInit_QueryRegCFSLineHdlr
CHKiRet(objUse(errmsg, CORE_COMPONENT));
INITChkCoreFeature(bCoreSupportsBatching, CORE_FEATURE_BATCHING);
DBGPRINTF("omzmq3: module compiled with rsyslog version %s.\n", VERSION);
INITLegCnfVars
CHKiRet(omsdRegCFSLineHdlr((uchar *)"omzmq3workerthreads", 0, eCmdHdlrInt, NULL, &s_workerThreads,
STD_LOADABLE_MODULE_ID));
ENDmodInit
| ./CrossVul/dataset_final_sorted/CWE-134/c/bad_2610_1 |
crossvul-cpp_data_good_2265_0 | /****************************************************************************
* RRDtool 1.4.3 Copyright by Tobi Oetiker, 1997-2010
****************************************************************************
* rrd__graph.c produce graphs from data in rrdfiles
****************************************************************************/
#include <sys/stat.h>
#include <glib.h> // will use regex
#ifdef WIN32
#include "strftime.h"
#endif
#include "rrd_strtod.h"
#include "rrd_tool.h"
#include "unused.h"
/* for basename */
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#else
#include "plbasename.h"
#endif
#if defined(WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
#include <io.h>
#include <fcntl.h>
#endif
#include <time.h>
#include <locale.h>
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#include "rrd_graph.h"
#include "rrd_client.h"
/* some constant definitions */
#ifndef RRD_DEFAULT_FONT
/* there is special code later to pick Cour.ttf when running on windows */
#define RRD_DEFAULT_FONT "DejaVu Sans Mono,Bitstream Vera Sans Mono,monospace,Courier"
#endif
text_prop_t text_prop[] = {
{8.0, RRD_DEFAULT_FONT,NULL}
, /* default */
{9.0, RRD_DEFAULT_FONT,NULL}
, /* title */
{7.0, RRD_DEFAULT_FONT,NULL}
, /* axis */
{8.0, RRD_DEFAULT_FONT,NULL}
, /* unit */
{8.0, RRD_DEFAULT_FONT,NULL} /* legend */
,
{5.5, RRD_DEFAULT_FONT,NULL} /* watermark */
};
char week_fmt[128] = "Week %V";
xlab_t xlab[] = {
{0, 0, TMT_SECOND, 30, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{2, 0, TMT_MINUTE, 1, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{5, 0, TMT_MINUTE, 2, TMT_MINUTE, 10, TMT_MINUTE, 10, 0, "%H:%M"}
,
{10, 0, TMT_MINUTE, 5, TMT_MINUTE, 20, TMT_MINUTE, 20, 0, "%H:%M"}
,
{30, 0, TMT_MINUTE, 10, TMT_HOUR, 1, TMT_HOUR, 1, 0, "%H:%M"}
,
{60, 0, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 2, 0, "%H:%M"}
,
{60, 24 * 3600, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 6, 0, "%a %H:%M"}
,
{180, 0, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 6, 0, "%H:%M"}
,
{180, 24 * 3600, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 12, 0, "%a %H:%M"}
,
/*{300, 0, TMT_HOUR,3, TMT_HOUR,12, TMT_HOUR,12, 12*3600,"%a %p"}, this looks silly */
{600, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%a"}
,
{1200, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%d"}
,
{1800, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a %d"}
,
{2400, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a"}
,
{3600, 0, TMT_DAY, 1, TMT_WEEK, 1, TMT_WEEK, 1, 7 * 24 * 3600, week_fmt}
,
{3 * 3600, 0, TMT_WEEK, 1, TMT_MONTH, 1, TMT_WEEK, 2, 7 * 24 * 3600, week_fmt}
,
{6 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 1, TMT_MONTH, 1, 30 * 24 * 3600,
"%b"}
,
{48 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 3, TMT_MONTH, 3, 30 * 24 * 3600,
"%b"}
,
{315360, 0, TMT_MONTH, 3, TMT_YEAR, 1, TMT_YEAR, 1, 365 * 24 * 3600, "%Y"}
,
{10 * 24 * 3600, 0, TMT_YEAR, 1, TMT_YEAR, 1, TMT_YEAR, 1,
365 * 24 * 3600, "%y"}
,
{-1, 0, TMT_MONTH, 0, TMT_MONTH, 0, TMT_MONTH, 0, 0, ""}
};
/* sensible y label intervals ...*/
ylab_t ylab[] = {
{0.1, {1, 2, 5, 10}
}
,
{0.2, {1, 5, 10, 20}
}
,
{0.5, {1, 2, 4, 10}
}
,
{1.0, {1, 2, 5, 10}
}
,
{2.0, {1, 5, 10, 20}
}
,
{5.0, {1, 2, 4, 10}
}
,
{10.0, {1, 2, 5, 10}
}
,
{20.0, {1, 5, 10, 20}
}
,
{50.0, {1, 2, 4, 10}
}
,
{100.0, {1, 2, 5, 10}
}
,
{200.0, {1, 5, 10, 20}
}
,
{500.0, {1, 2, 4, 10}
}
,
{0.0, {0, 0, 0, 0}
}
};
gfx_color_t graph_col[] = /* default colors */
{
{1.00, 1.00, 1.00, 1.00}, /* canvas */
{0.95, 0.95, 0.95, 1.00}, /* background */
{0.81, 0.81, 0.81, 1.00}, /* shade A */
{0.62, 0.62, 0.62, 1.00}, /* shade B */
{0.56, 0.56, 0.56, 0.75}, /* grid */
{0.87, 0.31, 0.31, 0.60}, /* major grid */
{0.00, 0.00, 0.00, 1.00}, /* font */
{0.50, 0.12, 0.12, 1.00}, /* arrow */
{0.12, 0.12, 0.12, 1.00}, /* axis */
{0.00, 0.00, 0.00, 1.00} /* frame */
};
/* #define DEBUG */
#ifdef DEBUG
# define DPRINT(x) (void)(printf x, printf("\n"))
#else
# define DPRINT(x)
#endif
/* initialize with xtr(im,0); */
int xtr(
image_desc_t *im,
time_t mytime)
{
static double pixie;
if (mytime == 0) {
pixie = (double) im->xsize / (double) (im->end - im->start);
return im->xorigin;
}
return (int) ((double) im->xorigin + pixie * (mytime - im->start));
}
/* translate data values into y coordinates */
double ytr(
image_desc_t *im,
double value)
{
static double pixie;
double yval;
if (isnan(value)) {
if (!im->logarithmic)
pixie = (double) im->ysize / (im->maxval - im->minval);
else
pixie =
(double) im->ysize / (log10(im->maxval) - log10(im->minval));
yval = im->yorigin;
} else if (!im->logarithmic) {
yval = im->yorigin - pixie * (value - im->minval);
} else {
if (value < im->minval) {
yval = im->yorigin;
} else {
yval = im->yorigin - pixie * (log10(value) - log10(im->minval));
}
}
return yval;
}
/* conversion function for symbolic entry names */
#define conv_if(VV,VVV) \
if (strcmp(#VV, string) == 0) return VVV ;
enum gf_en gf_conv(
char *string)
{
conv_if(PRINT, GF_PRINT);
conv_if(GPRINT, GF_GPRINT);
conv_if(COMMENT, GF_COMMENT);
conv_if(HRULE, GF_HRULE);
conv_if(VRULE, GF_VRULE);
conv_if(LINE, GF_LINE);
conv_if(AREA, GF_AREA);
conv_if(GRAD, GF_GRAD);
conv_if(STACK, GF_STACK);
conv_if(TICK, GF_TICK);
conv_if(TEXTALIGN, GF_TEXTALIGN);
conv_if(DEF, GF_DEF);
conv_if(CDEF, GF_CDEF);
conv_if(VDEF, GF_VDEF);
conv_if(XPORT, GF_XPORT);
conv_if(SHIFT, GF_SHIFT);
return (enum gf_en)(-1);
}
enum gfx_if_en if_conv(
char *string)
{
conv_if(PNG, IF_PNG);
conv_if(SVG, IF_SVG);
conv_if(EPS, IF_EPS);
conv_if(PDF, IF_PDF);
conv_if(XML, IF_XML);
conv_if(XMLENUM, IF_XMLENUM);
conv_if(CSV, IF_CSV);
conv_if(TSV, IF_TSV);
conv_if(SSV, IF_SSV);
conv_if(JSON, IF_JSON);
conv_if(JSONTIME, IF_JSONTIME);
return (enum gfx_if_en)(-1);
}
enum gfx_type_en type_conv(
char *string)
{
conv_if(TIME , GTYPE_TIME);
conv_if(XY, GTYPE_XY);
return (enum gfx_type_en)(-1);
}
enum tmt_en tmt_conv(
char *string)
{
conv_if(SECOND, TMT_SECOND);
conv_if(MINUTE, TMT_MINUTE);
conv_if(HOUR, TMT_HOUR);
conv_if(DAY, TMT_DAY);
conv_if(WEEK, TMT_WEEK);
conv_if(MONTH, TMT_MONTH);
conv_if(YEAR, TMT_YEAR);
return (enum tmt_en)(-1);
}
enum grc_en grc_conv(
char *string)
{
conv_if(BACK, GRC_BACK);
conv_if(CANVAS, GRC_CANVAS);
conv_if(SHADEA, GRC_SHADEA);
conv_if(SHADEB, GRC_SHADEB);
conv_if(GRID, GRC_GRID);
conv_if(MGRID, GRC_MGRID);
conv_if(FONT, GRC_FONT);
conv_if(ARROW, GRC_ARROW);
conv_if(AXIS, GRC_AXIS);
conv_if(FRAME, GRC_FRAME);
return (enum grc_en)(-1);
}
enum text_prop_en text_prop_conv(
char *string)
{
conv_if(DEFAULT, TEXT_PROP_DEFAULT);
conv_if(TITLE, TEXT_PROP_TITLE);
conv_if(AXIS, TEXT_PROP_AXIS);
conv_if(UNIT, TEXT_PROP_UNIT);
conv_if(LEGEND, TEXT_PROP_LEGEND);
conv_if(WATERMARK, TEXT_PROP_WATERMARK);
return (enum text_prop_en)(-1);
}
#undef conv_if
int im_free(
image_desc_t *im)
{
unsigned long i, ii;
cairo_status_t status = (cairo_status_t) 0;
if (im == NULL)
return 0;
if (im->daemon_addr != NULL)
free(im->daemon_addr);
if (im->gdef_map){
g_hash_table_destroy(im->gdef_map);
}
if (im->rrd_map){
g_hash_table_destroy(im->rrd_map);
}
for (i = 0; i < (unsigned) im->gdes_c; i++) {
if (im->gdes[i].data_first) {
/* careful here, because a single pointer can occur several times */
free(im->gdes[i].data);
if (im->gdes[i].ds_namv) {
for (ii = 0; ii < im->gdes[i].ds_cnt; ii++)
free(im->gdes[i].ds_namv[ii]);
free(im->gdes[i].ds_namv);
}
}
/* free allocated memory used for dashed lines */
if (im->gdes[i].p_dashes != NULL)
free(im->gdes[i].p_dashes);
free(im->gdes[i].p_data);
free(im->gdes[i].rpnp);
}
free(im->gdes);
for (i = 0; i < DIM(text_prop);i++){
pango_font_description_free(im->text_prop[i].font_desc);
im->text_prop[i].font_desc = NULL;
}
if (im->font_options)
cairo_font_options_destroy(im->font_options);
if (im->surface)
cairo_surface_destroy(im->surface);
if (im->cr) {
status = cairo_status(im->cr);
cairo_destroy(im->cr);
}
if (status)
fprintf(stderr, "OOPS: Cairo has issues it can't even die: %s\n",
cairo_status_to_string(status));
if (im->rendered_image) {
free(im->rendered_image);
}
if (im->layout) {
g_object_unref(im->layout);
}
if (im->ylegend)
free(im->ylegend);
if (im->title)
free(im->title);
if (im->watermark)
free(im->watermark);
if (im->xlab_form)
free(im->xlab_form);
if (im->second_axis_legend)
free(im->second_axis_legend);
if (im->second_axis_format)
free(im->second_axis_format);
if (im->primary_axis_format)
free(im->primary_axis_format);
return 0;
}
/* find SI magnitude symbol for the given number*/
void auto_scale(
image_desc_t *im, /* image description */
double *value,
char **symb_ptr,
double *magfact)
{
char *symbol[] = { "a", /* 10e-18 Atto */
"f", /* 10e-15 Femto */
"p", /* 10e-12 Pico */
"n", /* 10e-9 Nano */
"u", /* 10e-6 Micro */
"m", /* 10e-3 Milli */
" ", /* Base */
"k", /* 10e3 Kilo */
"M", /* 10e6 Mega */
"G", /* 10e9 Giga */
"T", /* 10e12 Tera */
"P", /* 10e15 Peta */
"E"
}; /* 10e18 Exa */
int symbcenter = 6;
int sindex;
if (*value == 0.0 || isnan(*value)) {
sindex = 0;
*magfact = 1.0;
} else {
sindex = floor(log(fabs(*value)) / log((double) im->base));
*magfact = pow((double) im->base, (double) sindex);
(*value) /= (*magfact);
}
if (sindex <= symbcenter && sindex >= -symbcenter) {
(*symb_ptr) = symbol[sindex + symbcenter];
} else {
(*symb_ptr) = "?";
}
}
/* power prefixes */
static char si_symbol[] = {
'y', /* 10e-24 Yocto */
'z', /* 10e-21 Zepto */
'a', /* 10e-18 Atto */
'f', /* 10e-15 Femto */
'p', /* 10e-12 Pico */
'n', /* 10e-9 Nano */
'u', /* 10e-6 Micro */
'm', /* 10e-3 Milli */
' ', /* Base */
'k', /* 10e3 Kilo */
'M', /* 10e6 Mega */
'G', /* 10e9 Giga */
'T', /* 10e12 Tera */
'P', /* 10e15 Peta */
'E', /* 10e18 Exa */
'Z', /* 10e21 Zeta */
'Y' /* 10e24 Yotta */
};
static const int si_symbcenter = 8;
/* find SI magnitude symbol for the numbers on the y-axis*/
void si_unit(
image_desc_t *im /* image description */
)
{
double digits, viewdigits = 0;
digits =
floor(log(max(fabs(im->minval), fabs(im->maxval))) /
log((double) im->base));
if (im->unitsexponent != 9999) {
/* unitsexponent = 9, 6, 3, 0, -3, -6, -9, etc */
viewdigits = floor((double)(im->unitsexponent / 3));
} else {
viewdigits = digits;
}
im->magfact = pow((double) im->base, digits);
#ifdef DEBUG
printf("digits %6.3f im->magfact %6.3f\n", digits, im->magfact);
#endif
im->viewfactor = im->magfact / pow((double) im->base, viewdigits);
if (((viewdigits + si_symbcenter) < sizeof(si_symbol)) &&
((viewdigits + si_symbcenter) >= 0))
im->symbol = si_symbol[(int) viewdigits + si_symbcenter];
else
im->symbol = '?';
}
/* move min and max values around to become sensible */
void expand_range(
image_desc_t *im)
{
double sensiblevalues[] = { 1000.0, 900.0, 800.0, 750.0, 700.0,
600.0, 500.0, 400.0, 300.0, 250.0,
200.0, 125.0, 100.0, 90.0, 80.0,
75.0, 70.0, 60.0, 50.0, 40.0, 30.0,
25.0, 20.0, 10.0, 9.0, 8.0,
7.0, 6.0, 5.0, 4.0, 3.5, 3.0,
2.5, 2.0, 1.8, 1.5, 1.2, 1.0,
0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0, -1
};
double scaled_min, scaled_max;
double adj;
int i;
#ifdef DEBUG
printf("Min: %6.2f Max: %6.2f MagFactor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTAUTOSCALE) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher then max/min vals
so we can see amplitude on the graph */
double delt, fact;
delt = im->maxval - im->minval;
adj = delt * 0.1;
fact = 2.0 * pow(10.0,
floor(log10
(max(fabs(im->minval), fabs(im->maxval)) /
im->magfact)) - 2);
if (delt < fact) {
adj = (fact - delt) * 0.55;
#ifdef DEBUG
printf
("Min: %6.2f Max: %6.2f delt: %6.2f fact: %6.2f adj: %6.2f\n",
im->minval, im->maxval, delt, fact, adj);
#endif
}
im->minval -= adj;
im->maxval += adj;
} else if (im->extra_flags & ALTAUTOSCALE_MIN) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly lower than min vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->minval -= adj;
} else if (im->extra_flags & ALTAUTOSCALE_MAX) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher than max vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->maxval += adj;
} else {
scaled_min = im->minval / im->magfact;
scaled_max = im->maxval / im->magfact;
for (i = 1; sensiblevalues[i] > 0; i++) {
if (sensiblevalues[i - 1] >= scaled_min &&
sensiblevalues[i] <= scaled_min)
im->minval = sensiblevalues[i] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_min &&
-sensiblevalues[i] >= scaled_min)
im->minval = -sensiblevalues[i - 1] * (im->magfact);
if (sensiblevalues[i - 1] >= scaled_max &&
sensiblevalues[i] <= scaled_max)
im->maxval = sensiblevalues[i - 1] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_max &&
-sensiblevalues[i] >= scaled_max)
im->maxval = -sensiblevalues[i] * (im->magfact);
}
}
} else {
/* adjust min and max to the grid definition if there is one */
im->minval = (double) im->ylabfact * im->ygridstep *
floor(im->minval / ((double) im->ylabfact * im->ygridstep));
im->maxval = (double) im->ylabfact * im->ygridstep *
ceil(im->maxval / ((double) im->ylabfact * im->ygridstep));
}
#ifdef DEBUG
fprintf(stderr, "SCALED Min: %6.2f Max: %6.2f Factor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
}
void apply_gridfit(
image_desc_t *im)
{
if (isnan(im->minval) || isnan(im->maxval))
return;
ytr(im, DNAN);
if (im->logarithmic) {
double ya, yb, ypix, ypixfrac;
double log10_range = log10(im->maxval) - log10(im->minval);
ya = pow((double) 10, floor(log10(im->minval)));
while (ya < im->minval)
ya *= 10;
if (ya > im->maxval)
return; /* don't have y=10^x gridline */
yb = ya * 10;
if (yb <= im->maxval) {
/* we have at least 2 y=10^x gridlines.
Make sure distance between them in pixels
are an integer by expanding im->maxval */
double y_pixel_delta = ytr(im, ya) - ytr(im, yb);
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_log10_range = factor * log10_range;
double new_ymax_log10 = log10(im->minval) + new_log10_range;
im->maxval = pow(10, new_ymax_log10);
ytr(im, DNAN); /* reset precalc */
log10_range = log10(im->maxval) - log10(im->minval);
}
/* make sure first y=10^x gridline is located on
integer pixel position by moving scale slightly
downwards (sub-pixel movement) */
ypix = ytr(im, ya) + im->ysize; /* add im->ysize so it always is positive */
ypixfrac = ypix - floor(ypix);
if (ypixfrac > 0 && ypixfrac < 1) {
double yfrac = ypixfrac / im->ysize;
im->minval = pow(10, log10(im->minval) - yfrac * log10_range);
im->maxval = pow(10, log10(im->maxval) - yfrac * log10_range);
ytr(im, DNAN); /* reset precalc */
}
} else {
/* Make sure we have an integer pixel distance between
each minor gridline */
double ypos1 = ytr(im, im->minval);
double ypos2 = ytr(im, im->minval + im->ygrid_scale.gridstep);
double y_pixel_delta = ypos1 - ypos2;
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_range = factor * (im->maxval - im->minval);
double gridstep = im->ygrid_scale.gridstep;
double minor_y, minor_y_px, minor_y_px_frac;
if (im->maxval > 0.0)
im->maxval = im->minval + new_range;
else
im->minval = im->maxval - new_range;
ytr(im, DNAN); /* reset precalc */
/* make sure first minor gridline is on integer pixel y coord */
minor_y = gridstep * floor(im->minval / gridstep);
while (minor_y < im->minval)
minor_y += gridstep;
minor_y_px = ytr(im, minor_y) + im->ysize; /* ensure > 0 by adding ysize */
minor_y_px_frac = minor_y_px - floor(minor_y_px);
if (minor_y_px_frac > 0 && minor_y_px_frac < 1) {
double yfrac = minor_y_px_frac / im->ysize;
double range = im->maxval - im->minval;
im->minval = im->minval - yfrac * range;
im->maxval = im->maxval - yfrac * range;
ytr(im, DNAN); /* reset precalc */
}
calc_horizontal_grid(im); /* recalc with changed im->maxval */
}
}
/* reduce data reimplementation by Alex */
void reduce_data(
enum cf_en cf, /* which consolidation function ? */
unsigned long cur_step, /* step the data currently is in */
time_t *start, /* start, end and step as requested ... */
time_t *end, /* ... by the application will be ... */
unsigned long *step, /* ... adjusted to represent reality */
unsigned long *ds_cnt, /* number of data sources in file */
rrd_value_t **data)
{ /* two dimensional array containing the data */
int i, reduce_factor = ceil((double) (*step) / (double) cur_step);
unsigned long col, dst_row, row_cnt, start_offset, end_offset, skiprows =
0;
rrd_value_t *srcptr, *dstptr;
(*step) = cur_step * reduce_factor; /* set new step size for reduced data */
dstptr = *data;
srcptr = *data;
row_cnt = ((*end) - (*start)) / cur_step;
#ifdef DEBUG
#define DEBUG_REDUCE
#endif
#ifdef DEBUG_REDUCE
printf("Reducing %lu rows with factor %i time %lu to %lu, step %lu\n",
row_cnt, reduce_factor, *start, *end, cur_step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * cur_step);
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
/* We have to combine [reduce_factor] rows of the source
** into one row for the destination. Doing this we also
** need to take care to combine the correct rows. First
** alter the start and end time so that they are multiples
** of the new step time. We cannot reduce the amount of
** time so we have to move the end towards the future and
** the start towards the past.
*/
end_offset = (*end) % (*step);
start_offset = (*start) % (*step);
/* If there is a start offset (which cannot be more than
** one destination row), skip the appropriate number of
** source rows and one destination row. The appropriate
** number is what we do know (start_offset/cur_step) of
** the new interval (*step/cur_step aka reduce_factor).
*/
#ifdef DEBUG_REDUCE
printf("start_offset: %lu end_offset: %lu\n", start_offset, end_offset);
printf("row_cnt before: %lu\n", row_cnt);
#endif
if (start_offset) {
(*start) = (*start) - start_offset;
skiprows = reduce_factor - start_offset / cur_step;
srcptr += skiprows * *ds_cnt;
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt between: %lu\n", row_cnt);
#endif
/* At the end we have some rows that are not going to be
** used, the amount is end_offset/cur_step
*/
if (end_offset) {
(*end) = (*end) - end_offset + (*step);
skiprows = end_offset / cur_step;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt after: %lu\n", row_cnt);
#endif
/* Sanity check: row_cnt should be multiple of reduce_factor */
/* if this gets triggered, something is REALLY WRONG ... we die immediately */
if (row_cnt % reduce_factor) {
printf("SANITY CHECK: %lu rows cannot be reduced by %i \n",
row_cnt, reduce_factor);
printf("BUG in reduce_data()\n");
exit(1);
}
/* Now combine reduce_factor intervals at a time
** into one interval for the destination.
*/
for (dst_row = 0; (long int) row_cnt >= reduce_factor; dst_row++) {
for (col = 0; col < (*ds_cnt); col++) {
rrd_value_t newval = DNAN;
unsigned long validval = 0;
for (i = 0; i < reduce_factor; i++) {
if (isnan(srcptr[i * (*ds_cnt) + col])) {
continue;
}
validval++;
if (isnan(newval))
newval = srcptr[i * (*ds_cnt) + col];
else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval += srcptr[i * (*ds_cnt) + col];
break;
case CF_MINIMUM:
newval = min(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_FAILURES:
/* an interval contains a failure if any subintervals contained a failure */
case CF_MAXIMUM:
newval = max(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_LAST:
newval = srcptr[i * (*ds_cnt) + col];
break;
}
}
}
if (validval == 0) {
newval = DNAN;
} else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval /= validval;
break;
case CF_MINIMUM:
case CF_FAILURES:
case CF_MAXIMUM:
case CF_LAST:
break;
}
}
*dstptr++ = newval;
}
srcptr += (*ds_cnt) * reduce_factor;
row_cnt -= reduce_factor;
}
/* If we had to alter the endtime, we didn't have enough
** source rows to fill the last row. Fill it with NaN.
*/
if (end_offset)
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
#ifdef DEBUG_REDUCE
row_cnt = ((*end) - (*start)) / *step;
srcptr = *data;
printf("Done reducing. Currently %lu rows, time %lu to %lu, step %lu\n",
row_cnt, *start, *end, *step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * (*step));
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
}
/* get the data required for the graphs from the
relevant rrds ... */
int data_fetch(
image_desc_t *im)
{
int i, ii;
/* pull the data from the rrd files ... */
for (i = 0; i < (int) im->gdes_c; i++) {
/* only GF_DEF elements fetch data */
if (im->gdes[i].gf != GF_DEF)
continue;
/* do we have it already ? */
gpointer value;
char *key = gdes_fetch_key(im->gdes[i]);
gboolean ok = g_hash_table_lookup_extended(im->rrd_map,key,NULL,&value);
free(key);
if (ok){
ii = GPOINTER_TO_INT(value);
im->gdes[i].start = im->gdes[ii].start;
im->gdes[i].end = im->gdes[ii].end;
im->gdes[i].step = im->gdes[ii].step;
im->gdes[i].ds_cnt = im->gdes[ii].ds_cnt;
im->gdes[i].ds_namv = im->gdes[ii].ds_namv;
im->gdes[i].data = im->gdes[ii].data;
im->gdes[i].data_first = 0;
} else {
unsigned long ft_step = im->gdes[i].step; /* ft_step will record what we got from fetch */
const char *rrd_daemon;
int status;
if (im->gdes[i].daemon[0] != 0)
rrd_daemon = im->gdes[i].daemon;
else
rrd_daemon = im->daemon_addr;
/* "daemon" may be NULL. ENV_RRDCACHED_ADDRESS is evaluated in that
* case. If "daemon" holds the same value as in the previous
* iteration, no actual new connection is established - the
* existing connection is re-used. */
rrdc_connect (rrd_daemon);
/* If connecting was successfull, use the daemon to query the data.
* If there is no connection, for example because no daemon address
* was specified, (try to) use the local file directly. */
if (rrdc_is_connected (rrd_daemon))
{
status = rrdc_fetch (im->gdes[i].rrd,
cf_to_string (im->gdes[i].cf),
&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
&im->gdes[i].ds_namv,
&im->gdes[i].data);
if (status != 0) {
if (im->extra_flags & ALLOW_MISSING_DS) {
rrd_clear_error();
if (rrd_fetch_empty(&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
im->gdes[i].ds_nam,
&im->gdes[i].ds_namv,
&im->gdes[i].data) == -1)
return -1;
} else return (status);
}
}
else
{
if ((rrd_fetch_fn(im->gdes[i].rrd,
im->gdes[i].cf,
&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
&im->gdes[i].ds_namv,
&im->gdes[i].data)) == -1) {
if (im->extra_flags & ALLOW_MISSING_DS) {
/* Unable to fetch data, assume fake data */
rrd_clear_error();
if (rrd_fetch_empty(&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
im->gdes[i].ds_nam,
&im->gdes[i].ds_namv,
&im->gdes[i].data) == -1)
return -1;
} else return -1;
}
}
im->gdes[i].data_first = 1;
/* must reduce to at least im->step
otherwhise we end up with more data than we can handle in the
chart and visibility of data will be random */
im->gdes[i].step = max(im->gdes[i].step,im->step);
if (ft_step < im->gdes[i].step) {
reduce_data(im->gdes[i].cf_reduce_set ? im->gdes[i].cf_reduce : im->gdes[i].cf,
ft_step,
&im->gdes[i].start,
&im->gdes[i].end,
&im->gdes[i].step,
&im->gdes[i].ds_cnt, &im->gdes[i].data);
} else {
im->gdes[i].step = ft_step;
}
}
/* lets see if the required data source is really there */
for (ii = 0; ii < (int) im->gdes[i].ds_cnt; ii++) {
if (strcmp(im->gdes[i].ds_namv[ii], im->gdes[i].ds_nam) == 0) {
im->gdes[i].ds = ii;
}
}
if (im->gdes[i].ds == -1) {
rrd_set_error("No DS called '%s' in '%s'",
im->gdes[i].ds_nam, im->gdes[i].rrd);
return -1;
}
// remember that we already got this one
g_hash_table_insert(im->rrd_map,gdes_fetch_key(im->gdes[i]),GINT_TO_POINTER(i));
}
return 0;
}
/* evaluate the expressions in the CDEF functions */
/*************************************************************
* CDEF stuff
*************************************************************/
/* find the greatest common divisor for all the numbers
in the 0 terminated num array */
long lcd(
long *num)
{
long rest;
int i;
for (i = 0; num[i + 1] != 0; i++) {
do {
rest = num[i] % num[i + 1];
num[i] = num[i + 1];
num[i + 1] = rest;
} while (rest != 0);
num[i + 1] = num[i];
}
/* return i==0?num[i]:num[i-1]; */
return num[i];
}
/* run the rpn calculator on all the VDEF and CDEF arguments */
int data_calc(
image_desc_t *im)
{
int gdi;
int dataidx;
long *steparray, rpi;
int stepcnt;
time_t now;
rpnstack_t rpnstack;
rpnp_t *rpnp;
rpnstack_init(&rpnstack);
for (gdi = 0; gdi < im->gdes_c; gdi++) {
/* Look for GF_VDEF and GF_CDEF in the same loop,
* so CDEFs can use VDEFs and vice versa
*/
switch (im->gdes[gdi].gf) {
case GF_XPORT:
break;
case GF_SHIFT:{
graph_desc_t *vdp = &im->gdes[im->gdes[gdi].vidx];
/* remove current shift */
vdp->start -= vdp->shift;
vdp->end -= vdp->shift;
/* vdef */
if (im->gdes[gdi].shidx >= 0)
vdp->shift = im->gdes[im->gdes[gdi].shidx].vf.val;
/* constant */
else
vdp->shift = im->gdes[gdi].shval;
/* normalize shift to multiple of consolidated step */
vdp->shift = (vdp->shift / (long) vdp->step) * (long) vdp->step;
/* apply shift */
vdp->start += vdp->shift;
vdp->end += vdp->shift;
break;
}
case GF_VDEF:
/* A VDEF has no DS. This also signals other parts
* of rrdtool that this is a VDEF value, not a CDEF.
*/
im->gdes[gdi].ds_cnt = 0;
if (vdef_calc(im, gdi)) {
rrd_set_error("Error processing VDEF '%s'",
im->gdes[gdi].vname);
rpnstack_free(&rpnstack);
return -1;
}
break;
case GF_CDEF:
im->gdes[gdi].ds_cnt = 1;
im->gdes[gdi].ds = 0;
im->gdes[gdi].data_first = 1;
im->gdes[gdi].start = 0;
im->gdes[gdi].end = 0;
steparray = NULL;
stepcnt = 0;
dataidx = -1;
rpnp = im->gdes[gdi].rpnp;
/* Find the variables in the expression.
* - VDEF variables are substituted by their values
* and the opcode is changed into OP_NUMBER.
* - CDEF variables are analized for their step size,
* the lowest common denominator of all the step
* sizes of the data sources involved is calculated
* and the resulting number is the step size for the
* resulting data source.
*/
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
if (im->gdes[ptr].ds_cnt == 0) { /* this is a VDEF data source */
#if 0
printf
("DEBUG: inside CDEF '%s' processing VDEF '%s'\n",
im->gdes[gdi].vname, im->gdes[ptr].vname);
printf("DEBUG: value from vdef is %f\n",
im->gdes[ptr].vf.val);
#endif
im->gdes[gdi].rpnp[rpi].val = im->gdes[ptr].vf.val;
im->gdes[gdi].rpnp[rpi].op = OP_NUMBER;
} else { /* normal variables and PREF(variables) */
/* add one entry to the array that keeps track of the step sizes of the
* data sources going into the CDEF. */
if ((steparray =
(long*)rrd_realloc(steparray,
(++stepcnt +
1) * sizeof(*steparray))) == NULL) {
rrd_set_error("realloc steparray");
rpnstack_free(&rpnstack);
return -1;
};
steparray[stepcnt - 1] = im->gdes[ptr].step;
/* adjust start and end of cdef (gdi) so
* that it runs from the latest start point
* to the earliest endpoint of any of the
* rras involved (ptr)
*/
if (im->gdes[gdi].start < im->gdes[ptr].start)
im->gdes[gdi].start = im->gdes[ptr].start;
if (im->gdes[gdi].end == 0 ||
im->gdes[gdi].end > im->gdes[ptr].end)
im->gdes[gdi].end = im->gdes[ptr].end;
/* store pointer to the first element of
* the rra providing data for variable,
* further save step size and data source
* count of this rra
*/
im->gdes[gdi].rpnp[rpi].data =
im->gdes[ptr].data + im->gdes[ptr].ds;
im->gdes[gdi].rpnp[rpi].step = im->gdes[ptr].step;
im->gdes[gdi].rpnp[rpi].ds_cnt = im->gdes[ptr].ds_cnt;
/* backoff the *.data ptr; this is done so
* rpncalc() function doesn't have to treat
* the first case differently
*/
} /* if ds_cnt != 0 */
} /* if OP_VARIABLE */
} /* loop through all rpi */
/* move the data pointers to the correct period */
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
long diff =
im->gdes[gdi].start - im->gdes[ptr].start;
if (diff > 0)
im->gdes[gdi].rpnp[rpi].data +=
(diff / im->gdes[ptr].step) *
im->gdes[ptr].ds_cnt;
}
}
if (steparray == NULL) {
rrd_set_error("rpn expressions without DEF"
" or CDEF variables are not supported");
rpnstack_free(&rpnstack);
return -1;
}
steparray[stepcnt] = 0;
/* Now find the resulting step. All steps in all
* used RRAs have to be visited
*/
im->gdes[gdi].step = lcd(steparray);
free(steparray);
if ((im->gdes[gdi].data = (rrd_value_t*)malloc(((im->gdes[gdi].end -
im->gdes[gdi].start)
/ im->gdes[gdi].step)
* sizeof(double))) == NULL) {
rrd_set_error("malloc im->gdes[gdi].data");
rpnstack_free(&rpnstack);
return -1;
}
/* Step through the new cdef results array and
* calculate the values
*/
for (now = im->gdes[gdi].start + im->gdes[gdi].step;
now <= im->gdes[gdi].end; now += im->gdes[gdi].step) {
/* 3rd arg of rpn_calc is for OP_VARIABLE lookups;
* in this case we are advancing by timesteps;
* we use the fact that time_t is a synonym for long
*/
if (rpn_calc(rpnp, &rpnstack, (long) now,
im->gdes[gdi].data, ++dataidx) == -1) {
/* rpn_calc sets the error string */
rpnstack_free(&rpnstack);
rpnp_freeextra(rpnp);
return -1;
}
} /* enumerate over time steps within a CDEF */
rpnp_freeextra(rpnp);
break;
default:
continue;
}
} /* enumerate over CDEFs */
rpnstack_free(&rpnstack);
return 0;
}
/* from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm */
/* yes we are loosing precision by doing tos with floats instead of doubles
but it seems more stable this way. */
static int AlmostEqual2sComplement(
float A,
float B,
int maxUlps)
{
int aInt = *(int *) &A;
int bInt = *(int *) &B;
int intDiff;
/* Make sure maxUlps is non-negative and small enough that the
default NAN won't compare as equal to anything. */
/* assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024); */
/* Make aInt lexicographically ordered as a twos-complement int */
if (aInt < 0)
aInt = 0x80000000l - aInt;
/* Make bInt lexicographically ordered as a twos-complement int */
if (bInt < 0)
bInt = 0x80000000l - bInt;
intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return 1;
return 0;
}
/* massage data so, that we get one value for each x coordinate in the graph */
int data_proc(
image_desc_t *im)
{
long i, ii;
double pixstep = (double) (im->end - im->start)
/ (double) im->xsize; /* how much time
passes in one pixel */
double paintval;
double minval = DNAN, maxval = DNAN;
unsigned long gr_time;
/* memory for the processed data */
for (i = 0; i < im->gdes_c; i++) {
if ((im->gdes[i].gf == GF_LINE)
|| (im->gdes[i].gf == GF_AREA)
|| (im->gdes[i].gf == GF_TICK)
|| (im->gdes[i].gf == GF_GRAD)
) {
if ((im->gdes[i].p_data = (rrd_value_t*)malloc((im->xsize + 1)
* sizeof(rrd_value_t))) == NULL) {
rrd_set_error("malloc data_proc");
return -1;
}
}
}
for (i = 0; i < im->xsize; i++) { /* for each pixel */
long vidx;
gr_time = im->start + pixstep * i; /* time of the current step */
paintval = 0.0;
for (ii = 0; ii < im->gdes_c; ii++) {
double value;
switch (im->gdes[ii].gf) {
case GF_LINE:
case GF_AREA:
case GF_GRAD:
case GF_TICK:
if (!im->gdes[ii].stack)
paintval = 0.0;
value = im->gdes[ii].yrule;
if (isnan(value) || (im->gdes[ii].gf == GF_TICK)) {
/* The time of the data doesn't necessarily match
** the time of the graph. Beware.
*/
vidx = im->gdes[ii].vidx;
if (im->gdes[vidx].gf == GF_VDEF) {
value = im->gdes[vidx].vf.val;
} else
if (((long int) gr_time >=
(long int) im->gdes[vidx].start)
&& ((long int) gr_time <
(long int) im->gdes[vidx].end)) {
value = im->gdes[vidx].data[(unsigned long)
floor((double)
(gr_time -
im->gdes[vidx].
start)
/
im->gdes[vidx].step)
* im->gdes[vidx].ds_cnt +
im->gdes[vidx].ds];
} else {
value = DNAN;
}
};
if (!isnan(value)) {
paintval += value;
im->gdes[ii].p_data[i] = paintval;
/* GF_TICK: the data values are not
** relevant for min and max
*/
if (finite(paintval) && im->gdes[ii].gf != GF_TICK && !im->gdes[ii].skipscale) {
if ((isnan(minval) || paintval < minval) &&
!(im->logarithmic && paintval <= 0.0))
minval = paintval;
if (isnan(maxval) || paintval > maxval)
maxval = paintval;
}
} else {
im->gdes[ii].p_data[i] = DNAN;
}
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
default:
break;
}
}
}
/* if min or max have not been asigned a value this is because
there was no data in the graph ... this is not good ...
lets set these to dummy values then ... */
if (im->logarithmic) {
if (isnan(minval) || isnan(maxval) || maxval <= 0) {
minval = 0.0; /* catching this right away below */
maxval = 5.1;
}
/* in logarithm mode, where minval is smaller or equal
to 0 make the beast just way smaller than maxval */
if (minval <= 0) {
minval = maxval / 10e8;
}
} else {
if (isnan(minval) || isnan(maxval)) {
minval = 0.0;
maxval = 1.0;
}
}
/* adjust min and max values given by the user */
/* for logscale we add something on top */
if (isnan(im->minval)
|| ((!im->rigid) && im->minval > minval)
) {
if (im->logarithmic)
im->minval = minval / 2.0;
else
im->minval = minval;
}
if (isnan(im->maxval)
|| (!im->rigid && im->maxval < maxval)
) {
if (im->logarithmic)
im->maxval = maxval * 2.0;
else
im->maxval = maxval;
}
/* make sure min is smaller than max */
if (im->minval > im->maxval) {
if (im->minval > 0)
im->minval = 0.99 * im->maxval;
else
im->minval = 1.01 * im->maxval;
}
/* make sure min and max are not equal */
if (AlmostEqual2sComplement(im->minval, im->maxval, 4)) {
if (im->maxval > 0)
im->maxval *= 1.01;
else
im->maxval *= 0.99;
/* make sure min and max are not both zero */
if (AlmostEqual2sComplement(im->maxval, 0, 4)) {
im->maxval = 1.0;
}
}
return 0;
}
static int find_first_weekday(void){
static int first_weekday = -1;
if (first_weekday == -1){
#ifdef HAVE__NL_TIME_WEEK_1STDAY
/* according to http://sourceware.org/ml/libc-locales/2009-q1/msg00011.html */
/* See correct way here http://pasky.or.cz/dev/glibc/first_weekday.c */
first_weekday = nl_langinfo (_NL_TIME_FIRST_WEEKDAY)[0];
int week_1stday;
long week_1stday_l = (long) nl_langinfo (_NL_TIME_WEEK_1STDAY);
if (week_1stday_l == 19971130) week_1stday = 0; /* Sun */
else if (week_1stday_l == 19971201) week_1stday = 1; /* Mon */
else
{
first_weekday = 1;
return first_weekday; /* we go for a monday default */
}
first_weekday=(week_1stday + first_weekday - 1) % 7;
#else
first_weekday = 1;
#endif
}
return first_weekday;
}
/* identify the point where the first gridline, label ... gets placed */
time_t find_first_time(
time_t start, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
localtime_r(&start, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
switch (baseint) {
case TMT_SECOND:
tm. tm_sec -= tm.tm_sec % basestep;
break;
case TMT_MINUTE:
tm. tm_sec = 0;
tm. tm_min -= tm.tm_min % basestep;
break;
case TMT_HOUR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour -= tm.tm_hour % basestep;
break;
case TMT_DAY:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
break;
case TMT_WEEK:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday -= tm.tm_wday - find_first_weekday();
if (tm.tm_wday == 0 && find_first_weekday() > 0)
tm. tm_mday -= 7; /* we want the *previous* week */
break;
case TMT_MONTH:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon -= tm.tm_mon % basestep;
break;
case TMT_YEAR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon = 0;
tm. tm_year -= (
tm.tm_year + 1900) %basestep;
}
return mktime(&tm);
}
/* identify the point where the next gridline, label ... gets placed */
time_t find_next_time(
time_t current, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
time_t madetime;
localtime_r(¤t, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
int limit = 2;
switch (baseint) {
case TMT_SECOND: limit = 7200; break;
case TMT_MINUTE: limit = 120; break;
case TMT_HOUR: limit = 2; break;
default: limit = 2; break;
}
do {
switch (baseint) {
case TMT_SECOND:
tm. tm_sec += basestep;
break;
case TMT_MINUTE:
tm. tm_min += basestep;
break;
case TMT_HOUR:
tm. tm_hour += basestep;
break;
case TMT_DAY:
tm. tm_mday += basestep;
break;
case TMT_WEEK:
tm. tm_mday += 7 * basestep;
break;
case TMT_MONTH:
tm. tm_mon += basestep;
break;
case TMT_YEAR:
tm. tm_year += basestep;
}
madetime = mktime(&tm);
} while (madetime == -1 && limit-- >= 0); /* this is necessary to skip impossible times
like the daylight saving time skips */
return madetime;
}
/* calculate values required for PRINT and GPRINT functions */
int print_calc(
image_desc_t *im)
{
long i, ii, validsteps;
double printval;
struct tm tmvdef;
int graphelement = 0;
long vidx;
int max_ii;
double magfact = -1;
char *si_symb = "";
char *percent_s;
int prline_cnt = 0;
/* wow initializing tmvdef is quite a task :-) */
time_t now = time(NULL);
localtime_r(&now, &tmvdef);
for (i = 0; i < im->gdes_c; i++) {
vidx = im->gdes[i].vidx;
switch (im->gdes[i].gf) {
case GF_PRINT:
case GF_GPRINT:
/* PRINT and GPRINT can now print VDEF generated values.
* There's no need to do any calculations on them as these
* calculations were already made.
*/
if (im->gdes[vidx].gf == GF_VDEF) { /* simply use vals */
printval = im->gdes[vidx].vf.val;
localtime_r(&im->gdes[vidx].vf.when, &tmvdef);
} else { /* need to calculate max,min,avg etcetera */
max_ii = ((im->gdes[vidx].end - im->gdes[vidx].start)
/ im->gdes[vidx].step * im->gdes[vidx].ds_cnt);
printval = DNAN;
validsteps = 0;
for (ii = im->gdes[vidx].ds;
ii < max_ii; ii += im->gdes[vidx].ds_cnt) {
if (!finite(im->gdes[vidx].data[ii]))
continue;
if (isnan(printval)) {
printval = im->gdes[vidx].data[ii];
validsteps++;
continue;
}
switch (im->gdes[i].cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVPREDICT:
case CF_DEVSEASONAL:
case CF_SEASONAL:
case CF_AVERAGE:
validsteps++;
printval += im->gdes[vidx].data[ii];
break;
case CF_MINIMUM:
printval = min(printval, im->gdes[vidx].data[ii]);
break;
case CF_FAILURES:
case CF_MAXIMUM:
printval = max(printval, im->gdes[vidx].data[ii]);
break;
case CF_LAST:
printval = im->gdes[vidx].data[ii];
}
}
if (im->gdes[i].cf == CF_AVERAGE || im->gdes[i].cf > CF_LAST) {
if (validsteps > 1) {
printval = (printval / validsteps);
}
}
} /* prepare printval */
if (!im->gdes[i].strftm && (percent_s = strstr(im->gdes[i].format, "%S")) != NULL) {
/* Magfact is set to -1 upon entry to print_calc. If it
* is still less than 0, then we need to run auto_scale.
* Otherwise, put the value into the correct units. If
* the value is 0, then do not set the symbol or magnification
* so next the calculation will be performed again. */
if (magfact < 0.0) {
auto_scale(im, &printval, &si_symb, &magfact);
if (printval == 0.0)
magfact = -1.0;
} else {
printval /= magfact;
}
*(++percent_s) = 's';
} else if (!im->gdes[i].strftm && strstr(im->gdes[i].format, "%s") != NULL) {
auto_scale(im, &printval, &si_symb, &magfact);
}
if (im->gdes[i].gf == GF_PRINT) {
rrd_infoval_t prline;
if (im->gdes[i].strftm) {
prline.u_str = (char*)malloc((FMT_LEG_LEN + 2) * sizeof(char));
if (im->gdes[vidx].vf.never == 1) {
time_clean(prline.u_str, im->gdes[i].format);
} else {
strftime(prline.u_str,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
}
} else if (bad_format_print(im->gdes[i].format)) {
return -1;
} else {
prline.u_str =
sprintf_alloc(im->gdes[i].format, printval, si_symb);
}
grinfo_push(im,
sprintf_alloc
("print[%ld]", prline_cnt++), RD_I_STR, prline);
free(prline.u_str);
} else {
/* GF_GPRINT */
if (im->gdes[i].strftm) {
if (im->gdes[vidx].vf.never == 1) {
time_clean(im->gdes[i].legend, im->gdes[i].format);
} else {
strftime(im->gdes[i].legend,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
}
} else {
if (bad_format_print(im->gdes[i].format)) {
return -1;
}
snprintf(im->gdes[i].legend,
FMT_LEG_LEN - 2,
im->gdes[i].format, printval, si_symb);
}
graphelement = 1;
}
break;
case GF_LINE:
case GF_AREA:
case GF_GRAD:
case GF_TICK:
graphelement = 1;
break;
case GF_HRULE:
if (isnan(im->gdes[i].yrule)) { /* we must set this here or the legend printer can not decide to print the legend */
im->gdes[i].yrule = im->gdes[vidx].vf.val;
};
graphelement = 1;
break;
case GF_VRULE:
if (im->gdes[i].xrule == 0) { /* again ... the legend printer needs it */
im->gdes[i].xrule = im->gdes[vidx].vf.when;
};
graphelement = 1;
break;
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_DEF:
case GF_CDEF:
case GF_VDEF:
#ifdef WITH_PIECHART
case GF_PART:
#endif
case GF_SHIFT:
case GF_XPORT:
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
case GF_XAXIS:
case GF_YAXIS:
break;
}
}
return graphelement;
}
/* place legends with color spots */
int leg_place(
image_desc_t *im,
int calc_width)
{
/* graph labels */
int interleg = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int border = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int fill = 0, fill_last;
double legendwidth; // = im->ximg - 2 * border;
int leg_c = 0;
double leg_x = border;
int leg_y = 0; //im->yimg;
int leg_cc;
double glue = 0;
int i, ii, mark = 0;
char default_txtalign = TXA_JUSTIFIED; /*default line orientation */
int *legspace;
char *tab;
char saved_legend[FMT_LEG_LEN + 5];
if(calc_width){
legendwidth = 0;
}
else{
legendwidth = im->legendwidth - 2 * border;
}
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
if ((legspace = (int*)malloc(im->gdes_c * sizeof(int))) == NULL) {
rrd_set_error("malloc for legspace");
return -1;
}
for (i = 0; i < im->gdes_c; i++) {
char prt_fctn; /*special printfunctions */
if(calc_width){
strncpy(saved_legend, im->gdes[i].legend, sizeof saved_legend);
}
fill_last = fill;
/* hide legends for rules which are not displayed */
if (im->gdes[i].gf == GF_TEXTALIGN) {
default_txtalign = im->gdes[i].txtalign;
}
if (!(im->extra_flags & FORCE_RULES_LEGEND)) {
if (im->gdes[i].gf == GF_HRULE
&& (im->gdes[i].yrule <
im->minval || im->gdes[i].yrule > im->maxval))
im->gdes[i].legend[0] = '\0';
if (im->gdes[i].gf == GF_VRULE
&& (im->gdes[i].xrule <
im->start || im->gdes[i].xrule > im->end))
im->gdes[i].legend[0] = '\0';
}
/* turn \\t into tab */
while ((tab = strstr(im->gdes[i].legend, "\\t"))) {
memmove(tab, tab + 1, strlen(tab));
tab[0] = (char) 9;
}
leg_cc = strlen(im->gdes[i].legend);
/* is there a controle code at the end of the legend string ? */
if (leg_cc >= 2 && im->gdes[i].legend[leg_cc - 2] == '\\') {
prt_fctn = im->gdes[i].legend[leg_cc - 1];
leg_cc -= 2;
im->gdes[i].legend[leg_cc] = '\0';
} else {
prt_fctn = '\0';
}
/* only valid control codes */
if (prt_fctn != 'l' && prt_fctn != 'n' && /* a synonym for l */
prt_fctn != 'r' &&
prt_fctn != 'j' &&
prt_fctn != 'c' &&
prt_fctn != 'u' &&
prt_fctn != '.' &&
prt_fctn != 's' && prt_fctn != '\0' && prt_fctn != 'g') {
free(legspace);
rrd_set_error
("Unknown control code at the end of '%s\\%c'",
im->gdes[i].legend, prt_fctn);
return -1;
}
/* \n -> \l */
if (prt_fctn == 'n') {
prt_fctn = 'l';
}
/* \. is a null operation to allow strings ending in \x */
if (prt_fctn == '.') {
prt_fctn = '\0';
}
/* remove exess space from the end of the legend for \g */
while (prt_fctn == 'g' &&
leg_cc > 0 && im->gdes[i].legend[leg_cc - 1] == ' ') {
leg_cc--;
im->gdes[i].legend[leg_cc] = '\0';
}
if (leg_cc != 0) {
/* no interleg space if string ends in \g */
legspace[i] = (prt_fctn == 'g' ? 0 : interleg);
if (fill > 0) {
fill += legspace[i];
}
fill +=
gfx_get_text_width(im,
fill + border,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[i].legend);
leg_c++;
} else {
legspace[i] = 0;
}
/* who said there was a special tag ... ? */
if (prt_fctn == 'g') {
prt_fctn = '\0';
}
if (prt_fctn == '\0') {
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
if (i == im->gdes_c - 1 || fill > legendwidth) {
/* just one legend item is left right or center */
switch (default_txtalign) {
case TXA_RIGHT:
prt_fctn = 'r';
break;
case TXA_CENTER:
prt_fctn = 'c';
break;
case TXA_JUSTIFIED:
prt_fctn = 'j';
break;
default:
prt_fctn = 'l';
break;
}
}
/* is it time to place the legends ? */
if (fill > legendwidth) {
if (leg_c > 1) {
/* go back one */
i--;
fill = fill_last;
leg_c--;
}
}
if (leg_c == 1 && prt_fctn == 'j') {
prt_fctn = 'l';
}
}
if (prt_fctn != '\0') {
leg_x = border;
if (leg_c >= 2 && prt_fctn == 'j') {
glue = (double)(legendwidth - fill) / (double)(leg_c - 1);
} else {
glue = 0;
}
if (prt_fctn == 'c')
leg_x = border + (double)(legendwidth - fill) / 2.0;
if (prt_fctn == 'r')
leg_x = legendwidth - fill + border;
for (ii = mark; ii <= i; ii++) {
if (im->gdes[ii].legend[0] == '\0')
continue; /* skip empty legends */
im->gdes[ii].leg_x = leg_x;
im->gdes[ii].leg_y = leg_y + border;
leg_x +=
(double)gfx_get_text_width(im, leg_x,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[ii].legend)
+(double)legspace[ii]
+ glue;
}
if (leg_x > border || prt_fctn == 's')
leg_y += im->text_prop[TEXT_PROP_LEGEND].size * 1.8;
if (prt_fctn == 's')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size;
if (prt_fctn == 'u')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size *1.8;
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
fill = 0;
leg_c = 0;
mark = ii;
}
if(calc_width){
strncpy(im->gdes[i].legend, saved_legend, sizeof im->gdes[0].legend);
}
}
if(calc_width){
im->legendwidth = legendwidth + 2 * border;
}
else{
im->legendheight = leg_y + border * 0.6;
}
free(legspace);
}
return 0;
}
/* create a grid on the graph. it determines what to do
from the values of xsize, start and end */
/* the xaxis labels are determined from the number of seconds per pixel
in the requested graph */
int calc_horizontal_grid(
image_desc_t
*im)
{
double range;
double scaledrange;
int pixel, i;
int gridind = 0;
int decimals, fractionals;
im->ygrid_scale.labfact = 2;
range = im->maxval - im->minval;
scaledrange = range / im->magfact;
/* does the scale of this graph make it impossible to put lines
on it? If so, give up. */
if (isnan(scaledrange)) {
return 0;
}
/* find grid spaceing */
pixel = 1;
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTYGRID) {
/* find the value with max number of digits. Get number of digits */
decimals =
ceil(log10
(max(fabs(im->maxval), fabs(im->minval)) *
im->viewfactor / im->magfact));
if (decimals <= 0) /* everything is small. make place for zero */
decimals = 1;
im->ygrid_scale.gridstep =
pow((double) 10,
floor(log10(range * im->viewfactor / im->magfact))) /
im->viewfactor * im->magfact;
if (im->ygrid_scale.gridstep == 0) /* range is one -> 0.1 is reasonable scale */
im->ygrid_scale.gridstep = 0.1;
/* should have at least 5 lines but no more then 15 */
if (range / im->ygrid_scale.gridstep < 5
&& im->ygrid_scale.gridstep >= 30)
im->ygrid_scale.gridstep /= 10;
if (range / im->ygrid_scale.gridstep > 15)
im->ygrid_scale.gridstep *= 10;
if (range / im->ygrid_scale.gridstep > 5) {
im->ygrid_scale.labfact = 1;
if (range / im->ygrid_scale.gridstep > 8
|| im->ygrid_scale.gridstep <
1.8 * im->text_prop[TEXT_PROP_AXIS].size)
im->ygrid_scale.labfact = 2;
} else {
im->ygrid_scale.gridstep /= 5;
im->ygrid_scale.labfact = 5;
}
fractionals =
floor(log10
(im->ygrid_scale.gridstep *
(double) im->ygrid_scale.labfact * im->viewfactor /
im->magfact));
if (fractionals < 0) { /* small amplitude. */
int len = decimals - fractionals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
snprintf(im->ygrid_scale.labfmt, sizeof im->ygrid_scale.labfmt,
"%%%d.%df%s", len,
-fractionals, (im->symbol != ' ' ? " %c" : ""));
} else {
int len = decimals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
snprintf(im->ygrid_scale.labfmt, sizeof im->ygrid_scale.labfmt,
"%%%d.0f%s", len, (im->symbol != ' ' ? " %c" : ""));
}
} else { /* classic rrd grid */
for (i = 0; ylab[i].grid > 0; i++) {
pixel = im->ysize / (scaledrange / ylab[i].grid);
gridind = i;
if (pixel >= 5)
break;
}
for (i = 0; i < 4; i++) {
if (pixel * ylab[gridind].lfac[i] >=
1.8 * im->text_prop[TEXT_PROP_AXIS].size) {
im->ygrid_scale.labfact = ylab[gridind].lfac[i];
break;
}
}
im->ygrid_scale.gridstep = ylab[gridind].grid * im->magfact;
}
} else {
im->ygrid_scale.gridstep = im->ygridstep;
im->ygrid_scale.labfact = im->ylabfact;
}
return 1;
}
int draw_horizontal_grid(
image_desc_t
*im)
{
int i;
double scaledstep;
char graph_label[100];
int nlabels = 0;
double X0 = im->xorigin;
double X1 = im->xorigin + im->xsize;
int sgrid = (int) (im->minval / im->ygrid_scale.gridstep - 1);
int egrid = (int) (im->maxval / im->ygrid_scale.gridstep + 1);
double MaxY;
double second_axis_magfact = 0;
char *second_axis_symb = "";
scaledstep =
im->ygrid_scale.gridstep /
(double) im->magfact * (double) im->viewfactor;
MaxY = scaledstep * (double) egrid;
for (i = sgrid; i <= egrid; i++) {
double Y0 = ytr(im,
im->ygrid_scale.gridstep * i);
double YN = ytr(im,
im->ygrid_scale.gridstep * (i + 1));
if (floor(Y0 + 0.5) >=
im->yorigin - im->ysize && floor(Y0 + 0.5) <= im->yorigin) {
/* Make sure at least 2 grid labels are shown, even if it doesn't agree
with the chosen settings. Add a label if required by settings, or if
there is only one label so far and the next grid line is out of bounds. */
if (i % im->ygrid_scale.labfact == 0
|| (nlabels == 1
&& (YN < im->yorigin - im->ysize || YN > im->yorigin))) {
if (im->symbol == ' ') {
if (im->primary_axis_format == NULL || im->primary_axis_format[0] == '\0') {
if (im->extra_flags & ALTYGRID) {
snprintf(graph_label, sizeof graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i);
} else {
if (MaxY < 10) {
snprintf(graph_label, sizeof graph_label, "%4.1f",
scaledstep * (double) i);
} else {
snprintf(graph_label, sizeof graph_label,"%4.0f",
scaledstep * (double) i);
}
}
} else {
snprintf(graph_label, sizeof graph_label, im->primary_axis_format,
scaledstep * (double) i);
}
} else {
char sisym = (i == 0 ? ' ' : im->symbol);
if (im->primary_axis_format == NULL || im->primary_axis_format[0] == '\0') {
if (im->extra_flags & ALTYGRID) {
snprintf(graph_label,sizeof graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i, sisym);
} else {
if (MaxY < 10) {
snprintf(graph_label, sizeof graph_label,"%4.1f %c",
scaledstep * (double) i, sisym);
} else {
snprintf(graph_label, sizeof graph_label, "%4.0f %c",
scaledstep * (double) i, sisym);
}
}
} else {
sprintf(graph_label, im->primary_axis_format,
scaledstep * (double) i, sisym);
}
}
nlabels++;
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = im->ygrid_scale.gridstep*(double)i*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format == NULL || im->second_axis_format[0] == '\0') {
if (!second_axis_magfact){
double dummy = im->ygrid_scale.gridstep*(double)(sgrid+egrid)/2.0*im->second_axis_scale+im->second_axis_shift;
auto_scale(im,&dummy,&second_axis_symb,&second_axis_magfact);
}
sval /= second_axis_magfact;
if(MaxY < 10) {
snprintf(graph_label_right, sizeof graph_label_right, "%5.1f %s",sval,second_axis_symb);
} else {
snprintf(graph_label_right, sizeof graph_label_right, "%5.0f %s",sval,second_axis_symb);
}
}
else {
snprintf(graph_label_right, sizeof graph_label_right, im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
gfx_line(im, X0 - 2, Y0, X0, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID],
im->grid_dash_on, im->grid_dash_off);
} else if (!(im->extra_flags & NOMINOR)) {
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
}
return 1;
}
/* this is frexp for base 10 */
double frexp10(
double,
double *);
double frexp10(
double x,
double *e)
{
double mnt;
int iexp;
iexp = floor(log((double)fabs(x)) / log((double)10));
mnt = x / pow(10.0, iexp);
if (mnt >= 10.0) {
iexp++;
mnt = x / pow(10.0, iexp);
}
*e = iexp;
return mnt;
}
/* logaritmic horizontal grid */
int horizontal_log_grid(
image_desc_t
*im)
{
double yloglab[][10] = {
{
1.0, 10., 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 5.0, 10., 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 5.0, 7.0, 10., 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 4.0,
6.0, 8.0, 10.,
0.0,
0.0, 0.0, 0.0}, {
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0} /* last line */
};
int i, j, val_exp, min_exp;
double nex; /* number of decades in data */
double logscale; /* scale in logarithmic space */
int exfrac = 1; /* decade spacing */
int mid = -1; /* row in yloglab for major grid */
double mspac; /* smallest major grid spacing (pixels) */
int flab; /* first value in yloglab to use */
double value, tmp, pre_value;
double X0, X1, Y0;
char graph_label[100];
nex = log10(im->maxval / im->minval);
logscale = im->ysize / nex;
/* major spacing for data with high dynamic range */
while (logscale * exfrac < 3 * im->text_prop[TEXT_PROP_LEGEND].size) {
if (exfrac == 1)
exfrac = 3;
else
exfrac += 3;
}
/* major spacing for less dynamic data */
do {
/* search best row in yloglab */
mid++;
for (i = 0; yloglab[mid][i + 1] < 10.0; i++);
mspac = logscale * log10(10.0 / yloglab[mid][i]);
}
while (mspac >
2 * im->text_prop[TEXT_PROP_LEGEND].size && yloglab[mid][0] > 0);
if (mid)
mid--;
/* find first value in yloglab */
for (flab = 0;
yloglab[mid][flab] < 10
&& frexp10(im->minval, &tmp) > yloglab[mid][flab]; flab++);
if (yloglab[mid][flab] == 10.0) {
tmp += 1.0;
flab = 0;
}
val_exp = tmp;
if (val_exp % exfrac)
val_exp += abs(-val_exp % exfrac);
X0 = im->xorigin;
X1 = im->xorigin + im->xsize;
/* draw grid */
pre_value = DNAN;
while (1) {
value = yloglab[mid][flab] * pow(10.0, val_exp);
if (AlmostEqual2sComplement(value, pre_value, 4))
break; /* it seems we are not converging */
pre_value = value;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* major grid line */
gfx_line(im,
X0 - 2, Y0, X0, Y0, MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
/* label */
if (im->extra_flags & FORCE_UNITS_SI) {
int scale;
double pvalue;
char symbol;
scale = floor(val_exp / 3.0);
if (value >= 1.0)
pvalue = pow(10.0, val_exp % 3);
else
pvalue = pow(10.0, ((val_exp + 1) % 3) + 2);
pvalue *= yloglab[mid][flab];
if (((scale + si_symbcenter) < (int) sizeof(si_symbol))
&& ((scale + si_symbcenter) >= 0))
symbol = si_symbol[scale + si_symbcenter];
else
symbol = '?';
snprintf(graph_label, sizeof graph_label, "%3.0f %c", pvalue, symbol);
} else {
snprintf(graph_label, sizeof graph_label, "%3.0e", value);
}
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = value*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format == NULL || im->second_axis_format[0] == '\0') {
if (im->extra_flags & FORCE_UNITS_SI) {
double mfac = 1;
char *symb = "";
auto_scale(im,&sval,&symb,&mfac);
snprintf(graph_label_right, sizeof graph_label_right, "%4.0f %s", sval,symb);
}
else {
snprintf(graph_label_right, sizeof graph_label_right, "%3.0e", sval);
}
}
else {
snprintf(graph_label_right, sizeof graph_label_right, im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
/* minor grid */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line behind current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
} else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* next decade */
if (yloglab[mid][++flab] == 10.0) {
flab = 0;
val_exp += exfrac;
}
}
/* draw minor lines after highest major line */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line below current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* fancy minor gridlines */
else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
return 1;
}
void vertical_grid(
image_desc_t *im)
{
int xlab_sel; /* which sort of label and grid ? */
time_t ti, tilab, timajor;
long factor;
char graph_label[100];
double X0, Y0, Y1; /* points for filled graph and more */
struct tm tm;
/* the type of time grid is determined by finding
the number of seconds per pixel in the graph */
if (im->xlab_user.minsec == -1) {
factor = (im->end - im->start) / im->xsize;
xlab_sel = 0;
while (xlab[xlab_sel + 1].minsec !=
-1 && xlab[xlab_sel + 1].minsec <= factor) {
xlab_sel++;
} /* pick the last one */
while (xlab[xlab_sel - 1].minsec ==
xlab[xlab_sel].minsec
&& xlab[xlab_sel].length > (im->end - im->start)) {
xlab_sel--;
} /* go back to the smallest size */
im->xlab_user.gridtm = xlab[xlab_sel].gridtm;
im->xlab_user.gridst = xlab[xlab_sel].gridst;
im->xlab_user.mgridtm = xlab[xlab_sel].mgridtm;
im->xlab_user.mgridst = xlab[xlab_sel].mgridst;
im->xlab_user.labtm = xlab[xlab_sel].labtm;
im->xlab_user.labst = xlab[xlab_sel].labst;
im->xlab_user.precis = xlab[xlab_sel].precis;
im->xlab_user.stst = xlab[xlab_sel].stst;
}
/* y coords are the same for every line ... */
Y0 = im->yorigin;
Y1 = im->yorigin - im->ysize;
/* paint the minor grid */
if (!(im->extra_flags & NOMINOR)) {
for (ti = find_first_time(im->start,
im->
xlab_user.
gridtm,
im->
xlab_user.
gridst),
timajor =
find_first_time(im->start,
im->xlab_user.
mgridtm,
im->xlab_user.
mgridst);
ti < im->end && ti != -1;
ti =
find_next_time(ti, im->xlab_user.gridtm, im->xlab_user.gridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
while (timajor < ti && timajor != -1) {
timajor = find_next_time(timajor,
im->
xlab_user.
mgridtm, im->xlab_user.mgridst);
}
if (timajor == -1) break; /* fail in case of problems with time increments */
if (ti == timajor)
continue; /* skip as falls on major grid line */
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X0, Y0, X0, Y0 + 2,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0, Y0 + 1, X0,
Y1 - 1, GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* paint the major grid */
for (ti = find_first_time(im->start,
im->
xlab_user.
mgridtm,
im->
xlab_user.
mgridst);
ti < im->end && ti != -1;
ti = find_next_time(ti, im->xlab_user.mgridtm, im->xlab_user.mgridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X0, Y0, X0, Y0 + 3,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0, Y0 + 3, X0,
Y1 - 2, MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
}
/* paint the labels below the graph */
for (ti =
find_first_time(im->start -
im->xlab_user.
precis / 2,
im->xlab_user.
labtm,
im->xlab_user.
labst);
(ti <=
im->end -
im->xlab_user.precis / 2) && ti != -1;
ti = find_next_time(ti, im->xlab_user.labtm, im->xlab_user.labst)
) {
tilab = ti + im->xlab_user.precis / 2; /* correct time for the label */
/* are we inside the graph ? */
if (tilab < im->start || tilab > im->end)
continue;
#if HAVE_STRFTIME
localtime_r(&tilab, &tm);
strftime(graph_label, 99, im->xlab_user.stst, &tm);
#else
# error "your libc has no strftime I guess we'll abort the exercise here."
#endif
gfx_text(im,
xtr(im, tilab),
Y0 + 3,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_TOP, graph_label);
}
}
void axis_paint(
image_desc_t *im)
{
/* draw x and y axis */
/* gfx_line ( im->canvas, im->xorigin+im->xsize,im->yorigin,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line ( im->canvas, im->xorigin,im->yorigin-im->ysize,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]); */
gfx_line(im, im->xorigin - 4,
im->yorigin,
im->xorigin + im->xsize +
4, im->yorigin, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line(im, im->xorigin,
im->yorigin + 4,
im->xorigin,
im->yorigin - im->ysize -
4, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
/* arrow for X and Y axis direction */
gfx_new_area(im, im->xorigin + im->xsize + 2, im->yorigin - 3, im->xorigin + im->xsize + 2, im->yorigin + 3, im->xorigin + im->xsize + 7, im->yorigin, /* horyzontal */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
gfx_new_area(im, im->xorigin - 3, im->yorigin - im->ysize - 2, im->xorigin + 3, im->yorigin - im->ysize - 2, im->xorigin, im->yorigin - im->ysize - 7, /* vertical */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
if (im->second_axis_scale != 0){
gfx_line ( im, im->xorigin+im->xsize,im->yorigin+4,
im->xorigin+im->xsize,im->yorigin-im->ysize-4,
MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_new_area ( im,
im->xorigin+im->xsize-2, im->yorigin-im->ysize-2,
im->xorigin+im->xsize+3, im->yorigin-im->ysize-2,
im->xorigin+im->xsize, im->yorigin-im->ysize-7, /* LINEOFFSET */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
}
}
void grid_paint(
image_desc_t *im)
{
long i;
int res = 0;
double X0, Y0; /* points for filled graph and more */
struct gfx_color_t water_color;
if (im->draw_3d_border > 0) {
/* draw 3d border */
i = im->draw_3d_border;
gfx_new_area(im, 0, im->yimg,
i, im->yimg - i, i, i, im->graph_col[GRC_SHADEA]);
gfx_add_point(im, im->ximg - i, i);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, 0, 0);
gfx_close_path(im);
gfx_new_area(im, i, im->yimg - i,
im->ximg - i,
im->yimg - i, im->ximg - i, i, im->graph_col[GRC_SHADEB]);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, im->ximg, im->yimg);
gfx_add_point(im, 0, im->yimg);
gfx_close_path(im);
}
if (im->draw_x_grid == 1)
vertical_grid(im);
if (im->draw_y_grid == 1) {
if (im->logarithmic) {
res = horizontal_log_grid(im);
} else {
res = draw_horizontal_grid(im);
}
/* dont draw horizontal grid if there is no min and max val */
if (!res) {
char *nodata = "No Data found";
gfx_text(im, im->ximg / 2,
(2 * im->yorigin -
im->ysize) / 2,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_CENTER, nodata);
}
}
/* yaxis unit description */
if (im->ylegend && im->ylegend[0] != '\0') {
gfx_text(im,
im->xOriginLegendY+10,
im->yOriginLegendY,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_UNIT].
font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE, GFX_H_CENTER, GFX_V_CENTER, im->ylegend);
}
if (im->second_axis_legend && im->second_axis_legend[0] != '\0') {
gfx_text( im,
im->xOriginLegendY2+10,
im->yOriginLegendY2,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_UNIT].font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE,
GFX_H_CENTER, GFX_V_CENTER,
im->second_axis_legend);
}
/* graph title */
gfx_text(im,
im->xOriginTitle, im->yOriginTitle+6,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_TITLE].
font_desc,
im->tabwidth, 0.0, GFX_H_CENTER, GFX_V_TOP, im->title?im->title:"");
/* rrdtool 'logo' */
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
double xpos = im->legendposition == EAST ? im->xOriginLegendY : im->ximg - 4;
gfx_text(im, xpos, 5,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth,
-90, GFX_H_LEFT, GFX_V_TOP, "RRDTOOL / TOBI OETIKER");
}
/* graph watermark */
if (im->watermark && im->watermark[0] != '\0') {
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
gfx_text(im,
im->ximg / 2, im->yimg - 6,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth, 0,
GFX_H_CENTER, GFX_V_BOTTOM, im->watermark);
}
/* graph labels */
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
long first_noncomment = im->gdes_c, last_noncomment = 0;
/* get smallest and biggest leg_y values. Assumes
* im->gdes[i].leg_y is in order. */
double min = 0, max = 0;
int gotcha = 0;
for (i = 0; i < im->gdes_c; i++) {
if (im->gdes[i].legend[0] == '\0')
continue;
if (!gotcha) {
min = im->gdes[i].leg_y;
gotcha = 1;
}
if (im->gdes[i].gf != GF_COMMENT) {
if (im->legenddirection == BOTTOM_UP2)
min = im->gdes[i].leg_y;
first_noncomment = i;
break;
}
}
gotcha = 0;
for (i = im->gdes_c - 1; i >= 0; i--) {
if (im->gdes[i].legend[0] == '\0')
continue;
if (!gotcha) {
max = im->gdes[i].leg_y;
gotcha = 1;
}
if (im->gdes[i].gf != GF_COMMENT) {
if (im->legenddirection == BOTTOM_UP2)
max = im->gdes[i].leg_y;
last_noncomment = i;
break;
}
}
for (i = 0; i < im->gdes_c; i++) {
if (im->gdes[i].legend[0] == '\0')
continue;
/* im->gdes[i].leg_y is the bottom of the legend */
X0 = im->xOriginLegend + im->gdes[i].leg_x;
int reverse = 0;
switch (im->legenddirection) {
case TOP_DOWN:
reverse = 0;
break;
case BOTTOM_UP:
reverse = 1;
break;
case BOTTOM_UP2:
reverse = i >= first_noncomment && i <= last_noncomment;
break;
}
Y0 = reverse ?
im->yOriginLegend + max + min - im->gdes[i].leg_y :
im->yOriginLegend + im->gdes[i].leg_y;
gfx_text(im, X0, Y0,
im->graph_col[GRC_FONT],
im->
text_prop
[TEXT_PROP_LEGEND].font_desc,
im->tabwidth, 0.0,
GFX_H_LEFT, GFX_V_BOTTOM, im->gdes[i].legend);
/* The legend for GRAPH items starts with "M " to have
enough space for the box */
if (im->gdes[i].gf != GF_PRINT &&
im->gdes[i].gf != GF_GPRINT && im->gdes[i].gf != GF_COMMENT) {
double boxH, boxV;
double X1, Y1;
boxH = gfx_get_text_width(im, 0,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, "o") * 1.2;
boxV = boxH;
/* shift the box up a bit */
Y0 -= boxV * 0.4;
if (im->dynamic_labels && im->gdes[i].gf == GF_HRULE) { /* [-] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0, Y0 - boxV / 2,
X0 + boxH, Y0 - boxV / 2,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_VRULE) { /* [|] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0 + boxH / 2, Y0,
X0 + boxH / 2, Y0 - boxV,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_LINE) { /* [/] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
gfx_line(im,
X0, Y0,
X0 + boxH, Y0 - boxV,
im->gdes[i].linewidth, im->gdes[i].col);
gfx_close_path(im);
} else {
/* make sure transparent colors show up the same way as in the graph */
gfx_new_area(im,
X0, Y0 - boxV,
X0, Y0, X0 + boxH, Y0, im->graph_col[GRC_BACK]);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
gfx_new_area(im, X0, Y0 - boxV, X0,
Y0, X0 + boxH, Y0, im->gdes[i].col);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
X1 = X0 + boxH;
Y1 = Y0 - boxV;
gfx_line_fit(im, &X0, &Y0);
gfx_line_fit(im, &X1, &Y1);
cairo_move_to(im->cr, X0, Y0);
cairo_line_to(im->cr, X1, Y0);
cairo_line_to(im->cr, X1, Y1);
cairo_line_to(im->cr, X0, Y1);
cairo_close_path(im->cr);
cairo_set_source_rgba(im->cr,
im->graph_col[GRC_FRAME].red,
im->graph_col[GRC_FRAME].green,
im->graph_col[GRC_FRAME].blue,
im->graph_col[GRC_FRAME].alpha);
}
if (im->gdes[i].dash) {
/* make box borders in legend dashed if the graph is dashed */
double dashes[] = {
3.0
};
cairo_set_dash(im->cr, dashes, 1, 0.0);
}
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
}
}
}
/*****************************************************
* lazy check make sure we rely need to create this graph
*****************************************************/
int lazy_check(
image_desc_t *im)
{
FILE *fd = NULL;
int size = 1;
struct stat imgstat;
if (im->lazy == 0)
return 0; /* no lazy option */
if (strlen(im->graphfile) == 0)
return 0; /* inmemory option */
if (stat(im->graphfile, &imgstat) != 0)
return 0; /* can't stat */
/* one pixel in the existing graph is more then what we would
change here ... */
if (time(NULL) - imgstat.st_mtime > (im->end - im->start) / im->xsize)
return 0;
if ((fd = fopen(im->graphfile, "rb")) == NULL)
return 0; /* the file does not exist */
switch (im->imgformat) {
case IF_PNG:
size = PngSize(fd, &(im->ximg), &(im->yimg));
break;
default:
size = 1;
}
fclose(fd);
return size;
}
int graph_size_location(
image_desc_t
*im,
int elements)
{
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area. If the option
** --full-size-mode is selected the size defines the total
** image size and the size available for the graph is
** calculated.
*/
/** +---+-----------------------------------+
** | y |...............graph title.........|
** | +---+-------------------------------+
** | a | y | |
** | x | | |
** | i | a | |
** | s | x | main graph area |
** | | i | |
** | t | s | |
** | i | | |
** | t | l | |
** | l | b +-------------------------------+
** | e | l | x axis labels |
** +---+---+-------------------------------+
** |....................legends............|
** +---------------------------------------+
** | watermark |
** +---------------------------------------+
*/
int Xvertical = 0, Xvertical2 = 0, Ytitle =
0, Xylabel = 0, Xmain = 0, Ymain =
0, Yxlabel = 0, Xspacing = 15, Yspacing = 15, Ywatermark = 4;
// no legends and no the shall be plotted it's easy
if (im->extra_flags & ONLY_GRAPH) {
im->xorigin = 0;
im->ximg = im->xsize;
im->yimg = im->ysize;
im->yorigin = im->ysize;
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
if (im->watermark && im->watermark[0] != '\0') {
Ywatermark = im->text_prop[TEXT_PROP_WATERMARK].size * 2;
}
// calculate the width of the left vertical legend
if (im->ylegend && im->ylegend[0] != '\0') {
Xvertical = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
// calculate the width of the right vertical legend
if (im->second_axis_legend && im->second_axis_legend[0] != '\0') {
Xvertical2 = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
else{
Xvertical2 = Xspacing;
}
if (im->title && im->title[0] != '\0') {
/* The title is placed "inbetween" two text lines so it
** automatically has some vertical spacing. The horizontal
** spacing is added here, on each side.
*/
/* if necessary, reduce the font size of the title until it fits the image width */
Ytitle = im->text_prop[TEXT_PROP_TITLE].size * 2.6 + 10;
}
else{
// we have no title; get a little clearing from the top
Ytitle = Yspacing;
}
if (elements) {
if (im->draw_x_grid) {
// calculate the height of the horizontal labelling
Yxlabel = im->text_prop[TEXT_PROP_AXIS].size * 2.5;
}
if (im->draw_y_grid || im->forceleftspace) {
// calculate the width of the vertical labelling
Xylabel =
gfx_get_text_width(im, 0,
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth, "0") * im->unitslength;
}
}
// add some space to the labelling
Xylabel += Xspacing;
/* If the legend is printed besides the graph the width has to be
** calculated first. Placing the legend north or south of the
** graph requires the width calculation first, so the legend is
** skipped for the moment.
*/
im->legendheight = 0;
im->legendwidth = 0;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 1) == -1){
return -1;
}
}
}
if (im->extra_flags & FULL_SIZE_MODE) {
/* The actual size of the image to draw has been determined by the user.
** The graph area is the space remaining after accounting for the legend,
** the watermark, the axis labels, and the title.
*/
im->ximg = im->xsize;
im->yimg = im->ysize;
Xmain = im->ximg;
Ymain = im->yimg;
/* Now calculate the total size. Insert some spacing where
desired. im->xorigin and im->yorigin need to correspond
with the lower left corner of the main graph area or, if
this one is not set, the imaginary box surrounding the
pie chart area. */
/* Initial size calculation for the main graph area */
Xmain -= Xylabel;// + Xspacing;
if((im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
Xmain -= im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
Xmain -= Xylabel;
}
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
Xmain -= Xspacing;
}
Xmain -= Xvertical + Xvertical2;
/* limit the remaining space to 0 */
if(Xmain < 1){
Xmain = 1;
}
im->xsize = Xmain;
/* Putting the legend north or south, the height can now be calculated */
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
Ymain -= Yxlabel + im->legendheight;
}
else{
Ymain -= Yxlabel;
}
/* reserve space for the title *or* some padding above the graph */
Ymain -= Ytitle;
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
Ymain -= 0.5*Yspacing;
}
if (im->watermark && im->watermark[0] != '\0') {
Ymain -= Ywatermark;
}
/* limit the remaining height to 0 */
if(Ymain < 1){
Ymain = 1;
}
im->ysize = Ymain;
} else { /* dimension options -width and -height refer to the dimensions of the main graph area */
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area.
*/
if (elements) {
Xmain = im->xsize; // + Xspacing;
Ymain = im->ysize;
}
im->ximg = Xmain + Xylabel;
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->ximg += Xspacing;
}
if( (im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
im->ximg += im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
im->ximg += Xylabel;
}
im->ximg += Xvertical + Xvertical2;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
im->yimg = Ymain + Yxlabel;
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
im->yimg += im->legendheight;
}
/* reserve space for the title *or* some padding above the graph */
if (Ytitle) {
im->yimg += Ytitle;
} else {
im->yimg += 1.5 * Yspacing;
}
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
im->yimg += 0.5*Yspacing;
}
if (im->watermark && im->watermark[0] != '\0') {
im->yimg += Ywatermark;
}
}
/* In case of putting the legend in west or east position the first
** legend calculation might lead to wrong positions if some items
** are not aligned on the left hand side (e.g. centered) as the
** legendwidth wight have been increased after the item was placed.
** In this case the positions have to be recalculated.
*/
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 0) == -1){
return -1;
}
}
}
/* After calculating all dimensions
** it is now possible to calculate
** all offsets.
*/
switch(im->legendposition){
case NORTH:
im->xOriginTitle = (im->ximg / 2);
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + im->legendheight + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
break;
case WEST:
im->xOriginTitle = im->legendwidth + im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = im->legendwidth;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = im->legendwidth + Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = im->legendwidth + Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case SOUTH:
im->xOriginTitle = im->ximg / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle + Ymain + Yxlabel;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case EAST:
im->xOriginTitle = im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = Xvertical + Xylabel + Xmain + Xvertical2;
if (im->second_axis_scale != 0){
im->xOriginLegend += Xylabel;
}
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->xOriginTitle += Xspacing;
im->xOriginLegend += Xspacing;
im->xOriginLegendY += Xspacing;
im->xorigin += Xspacing;
im->xOriginLegendY2 += Xspacing;
}
break;
}
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
static cairo_status_t cairo_output(
void *closure,
const unsigned char
*data,
unsigned int length)
{
image_desc_t *im = (image_desc_t*)closure;
im->rendered_image =
(unsigned char*)realloc(im->rendered_image, im->rendered_image_size + length);
if (im->rendered_image == NULL)
return CAIRO_STATUS_WRITE_ERROR;
memcpy(im->rendered_image + im->rendered_image_size, data, length);
im->rendered_image_size += length;
return CAIRO_STATUS_SUCCESS;
}
/* draw that picture thing ... */
int graph_paint(
image_desc_t *im)
{
int lazy = lazy_check(im);
int cnt;
/* imgformat XML or higher dispatch to xport
* output format there is selected via graph_type
*/
if (im->imgformat >= IF_XML) {
return rrd_graph_xport(im);
}
/* pull the data from the rrd files ... */
if (data_fetch(im) == -1)
return -1;
/* evaluate VDEF and CDEF operations ... */
if (data_calc(im) == -1)
return -1;
/* calculate and PRINT and GPRINT definitions. We have to do it at
* this point because it will affect the length of the legends
* if there are no graph elements (i==0) we stop here ...
* if we are lazy, try to quit ...
*/
cnt = print_calc(im);
if (cnt < 0)
return -1;
/* if we want and can be lazy ... quit now */
if (cnt == 0)
return 0;
/* otherwise call graph_paint_timestring */
switch (im->graph_type) {
case GTYPE_TIME:
return graph_paint_timestring(im,lazy,cnt);
break;
case GTYPE_XY:
return graph_paint_xy(im,lazy,cnt);
break;
}
/* final return with error*/
rrd_set_error("Graph type %i is not implemented",im->graph_type);
return -1;
}
int graph_paint_timestring(
image_desc_t *im, int lazy, int cnt)
{
int i,ii;
double areazero = 0.0;
graph_desc_t *lastgdes = NULL;
rrd_infoval_t info;
/**************************************************************
*** Calculating sizes and locations became a bit confusing ***
*** so I moved this into a separate function. ***
**************************************************************/
if (graph_size_location(im, cnt) == -1)
return -1;
info.u_cnt = im->xorigin;
grinfo_push(im, sprintf_alloc("graph_left"), RD_I_CNT, info);
info.u_cnt = im->yorigin - im->ysize;
grinfo_push(im, sprintf_alloc("graph_top"), RD_I_CNT, info);
info.u_cnt = im->xsize;
grinfo_push(im, sprintf_alloc("graph_width"), RD_I_CNT, info);
info.u_cnt = im->ysize;
grinfo_push(im, sprintf_alloc("graph_height"), RD_I_CNT, info);
info.u_cnt = im->ximg;
grinfo_push(im, sprintf_alloc("image_width"), RD_I_CNT, info);
info.u_cnt = im->yimg;
grinfo_push(im, sprintf_alloc("image_height"), RD_I_CNT, info);
info.u_cnt = im->start;
grinfo_push(im, sprintf_alloc("graph_start"), RD_I_CNT, info);
info.u_cnt = im->end;
grinfo_push(im, sprintf_alloc("graph_end"), RD_I_CNT, info);
/* if we want and can be lazy ... quit now */
if (lazy)
return 0;
/* get actual drawing data and find min and max values */
if (data_proc(im) == -1)
return -1;
if (!im->logarithmic) {
si_unit(im);
}
/* identify si magnitude Kilo, Mega Giga ? */
if (!im->rigid && !im->logarithmic)
expand_range(im); /* make sure the upper and lower limit are
sensible values */
info.u_val = im->minval;
grinfo_push(im, sprintf_alloc("value_min"), RD_I_VAL, info);
info.u_val = im->maxval;
grinfo_push(im, sprintf_alloc("value_max"), RD_I_VAL, info);
if (!calc_horizontal_grid(im))
return -1;
/* reset precalc */
ytr(im, DNAN);
/* if (im->gridfit)
apply_gridfit(im); */
/* set up cairo */
if (graph_cairo_setup(im)) { return -1; }
/* other stuff */
if (im->minval > 0.0)
areazero = im->minval;
if (im->maxval < 0.0)
areazero = im->maxval;
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_CDEF:
case GF_VDEF:
case GF_DEF:
case GF_PRINT:
case GF_GPRINT:
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_HRULE:
case GF_VRULE:
case GF_XPORT:
case GF_SHIFT:
case GF_XAXIS:
case GF_YAXIS:
break;
case GF_TICK:
for (ii = 0; ii < im->xsize; ii++) {
if (!isnan(im->gdes[i].p_data[ii])
&& im->gdes[i].p_data[ii] != 0.0) {
if (im->gdes[i].yrule > 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin + 1.0,
im->xorigin + ii,
im->yorigin -
im->gdes[i].yrule *
im->ysize, 1.0, im->gdes[i].col);
} else if (im->gdes[i].yrule < 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin - im->ysize - 1.0,
im->xorigin + ii,
im->yorigin - im->ysize -
im->gdes[i].
yrule *
im->ysize, 1.0, im->gdes[i].col);
}
}
}
break;
case GF_LINE:
case GF_AREA:
case GF_GRAD: {
rrd_value_t diffval = im->maxval - im->minval;
rrd_value_t maxlimit = im->maxval + 9 * diffval;
rrd_value_t minlimit = im->minval - 9 * diffval;
for (ii = 0; ii < im->xsize; ii++) {
/* fix data points at oo and -oo */
if (isinf(im->gdes[i].p_data[ii])) {
if (im->gdes[i].p_data[ii] > 0) {
im->gdes[i].p_data[ii] = im->maxval;
} else {
im->gdes[i].p_data[ii] = im->minval;
}
}
/* some versions of cairo go unstable when trying
to draw way out of the canvas ... lets not even try */
if (im->gdes[i].p_data[ii] > maxlimit) {
im->gdes[i].p_data[ii] = maxlimit;
}
if (im->gdes[i].p_data[ii] < minlimit) {
im->gdes[i].p_data[ii] = minlimit;
}
} /* for */
/* *******************************************************
a ___. (a,t)
| | ___
____| | | |
| |___|
-------|--t-1--t--------------------------------
if we know the value at time t was a then
we draw a square from t-1 to t with the value a.
********************************************************* */
if (im->gdes[i].col.alpha != 0.0) {
/* GF_LINE and friend */
if (im->gdes[i].gf == GF_LINE) {
double last_y = 0.0;
int draw_on = 0;
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
for (ii = 1; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])
|| (im->slopemode == 1
&& isnan(im->gdes[i].p_data[ii - 1]))) {
draw_on = 0;
continue;
}
if (draw_on == 0) {
last_y = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0) {
double x = ii - 1 + im->xorigin;
double y = last_y;
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
} else {
double x = ii - 1 + im->xorigin;
double y =
ytr(im, im->gdes[i].p_data[ii - 1]);
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
}
draw_on = 1;
} else {
double x1 = ii + im->xorigin;
double y1 = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0
&& !AlmostEqual2sComplement(y1, last_y, 4)) {
double x = ii - 1 + im->xorigin;
double y = y1;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
};
last_y = y1;
gfx_line_fit(im, &x1, &y1);
cairo_line_to(im->cr, x1, y1);
};
}
cairo_set_source_rgba(im->cr,
im->gdes[i].
col.red,
im->gdes[i].
col.green,
im->gdes[i].
col.blue, im->gdes[i].col.alpha);
cairo_set_line_cap(im->cr, CAIRO_LINE_CAP_ROUND);
cairo_set_line_join(im->cr, CAIRO_LINE_JOIN_ROUND);
cairo_stroke(im->cr);
cairo_restore(im->cr);
} else {
double lastx=0;
double lasty=0;
int idxI = -1;
double *foreY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *foreX =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backX =
(double *) malloc(sizeof(double) * im->xsize * 2);
int drawem = 0;
for (ii = 0; ii <= im->xsize; ii++) {
double ybase, ytop;
if (idxI > 0 && (drawem != 0 || ii == im->xsize)) {
int cntI = 1;
int lastI = 0;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI + 1], 4)) {
cntI++;
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_new_area(im,
backX[0], backY[0],
foreX[0], foreY[0],
foreX[cntI],
foreY[cntI], im->gdes[i].col);
} else {
lastx = foreX[cntI];
lasty = foreY[cntI];
}
while (cntI < idxI) {
lastI = cntI;
cntI++;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI
+ 1], 4)) {
cntI++;
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_add_point(im, foreX[cntI], foreY[cntI]);
} else {
gfx_add_rect_fadey(im,
lastx, foreY[0],
foreX[cntI], foreY[cntI], lasty,
im->gdes[i].col,
im->gdes[i].col2,
im->gdes[i].gradheight
);
lastx = foreX[cntI];
lasty = foreY[cntI];
}
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_add_point(im, backX[idxI], backY[idxI]);
} else {
gfx_add_rect_fadey(im,
lastx, foreY[0],
backX[idxI], backY[idxI], lasty,
im->gdes[i].col,
im->gdes[i].col2,
im->gdes[i].gradheight);
lastx = backX[idxI];
lasty = backY[idxI];
}
while (idxI > 1) {
lastI = idxI;
idxI--;
while (idxI > 1
&&
AlmostEqual2sComplement(backY
[lastI],
backY[idxI], 4)
&&
AlmostEqual2sComplement(backY
[lastI],
backY
[idxI
- 1], 4)) {
idxI--;
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_add_point(im, backX[idxI], backY[idxI]);
} else {
gfx_add_rect_fadey(im,
lastx, foreY[0],
backX[idxI], backY[idxI], lasty,
im->gdes[i].col,
im->gdes[i].col2,
im->gdes[i].gradheight);
lastx = backX[idxI];
lasty = backY[idxI];
}
}
idxI = -1;
drawem = 0;
if (im->gdes[i].gf != GF_GRAD)
gfx_close_path(im);
}
if (drawem != 0) {
drawem = 0;
idxI = -1;
}
if (ii == im->xsize)
break;
if (im->slopemode == 0 && ii == 0) {
continue;
}
if (isnan(im->gdes[i].p_data[ii])) {
drawem = 1;
continue;
}
ytop = ytr(im, im->gdes[i].p_data[ii]);
if (lastgdes && im->gdes[i].stack) {
ybase = ytr(im, lastgdes->p_data[ii]);
} else {
ybase = ytr(im, areazero);
}
if (ybase == ytop) {
drawem = 1;
continue;
}
if (ybase > ytop) {
double extra = ytop;
ytop = ybase;
ybase = extra;
}
if (im->slopemode == 0) {
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin - 1;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin - 1;
}
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin;
}
/* close up any remaining area */
free(foreY);
free(foreX);
free(backY);
free(backX);
} /* else GF_LINE */
}
/* if color != 0x0 */
/* make sure we do not run into trouble when stacking on NaN */
for (ii = 0; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])) {
if (lastgdes && (im->gdes[i].stack)) {
im->gdes[i].p_data[ii] = lastgdes->p_data[ii];
} else {
im->gdes[i].p_data[ii] = areazero;
}
}
}
lastgdes = &(im->gdes[i]);
break;
} /* GF_AREA, GF_LINE, GF_GRAD */
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
} /* switch */
}
cairo_reset_clip(im->cr);
/* grid_paint also does the text */
if (!(im->extra_flags & ONLY_GRAPH))
grid_paint(im);
if (!(im->extra_flags & ONLY_GRAPH))
axis_paint(im);
/* the RULES are the last thing to paint ... */
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_HRULE:
if (im->gdes[i].yrule >= im->minval
&& im->gdes[i].yrule <= im->maxval) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im, im->xorigin,
ytr(im, im->gdes[i].yrule),
im->xorigin + im->xsize,
ytr(im, im->gdes[i].yrule), 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
case GF_VRULE:
if (im->gdes[i].xrule >= im->start
&& im->gdes[i].xrule <= im->end) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im,
xtr(im, im->gdes[i].xrule),
im->yorigin, xtr(im,
im->
gdes[i].
xrule),
im->yorigin - im->ysize, 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
default:
break;
}
}
/* close the graph via cairo*/
return graph_cairo_finish(im);
}
int graph_cairo_setup (image_desc_t *im)
{
/* the actual graph is created by going through the individual
graph elements and then drawing them */
cairo_surface_destroy(im->surface);
switch (im->imgformat) {
case IF_PNG:
im->surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
im->ximg * im->zoom,
im->yimg * im->zoom);
break;
case IF_PDF:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
? cairo_pdf_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_pdf_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_EPS:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_ps_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_ps_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_SVG:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_svg_surface_create(im->
graphfile,
im->ximg * im->zoom, im->yimg * im->zoom)
: cairo_svg_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
cairo_svg_surface_restrict_to_version
(im->surface, CAIRO_SVG_VERSION_1_1);
break;
case IF_XML:
case IF_XMLENUM:
case IF_CSV:
case IF_TSV:
case IF_SSV:
case IF_JSON:
case IF_JSONTIME:
break;
};
cairo_destroy(im->cr);
im->cr = cairo_create(im->surface);
cairo_set_antialias(im->cr, im->graph_antialias);
cairo_scale(im->cr, im->zoom, im->zoom);
// pango_cairo_font_map_set_resolution(PANGO_CAIRO_FONT_MAP(font_map), 100);
gfx_new_area(im, 0, 0, 0, im->yimg,
im->ximg, im->yimg, im->graph_col[GRC_BACK]);
gfx_add_point(im, im->ximg, 0);
gfx_close_path(im);
gfx_new_area(im, im->xorigin,
im->yorigin,
im->xorigin +
im->xsize, im->yorigin,
im->xorigin +
im->xsize,
im->yorigin - im->ysize, im->graph_col[GRC_CANVAS]);
gfx_add_point(im, im->xorigin, im->yorigin - im->ysize);
gfx_close_path(im);
cairo_rectangle(im->cr, im->xorigin, im->yorigin - im->ysize - 1.0,
im->xsize, im->ysize + 2.0);
cairo_clip(im->cr);
return 0;
}
int graph_cairo_finish (image_desc_t *im)
{
switch (im->imgformat) {
case IF_PNG:
{
cairo_status_t status;
status = strlen(im->graphfile) ?
cairo_surface_write_to_png(im->surface, im->graphfile)
: cairo_surface_write_to_png_stream(im->surface, &cairo_output,
im);
if (status != CAIRO_STATUS_SUCCESS) {
rrd_set_error("Could not save png to '%s'", im->graphfile);
return 1;
}
break;
}
case IF_XML:
case IF_XMLENUM:
case IF_CSV:
case IF_TSV:
case IF_SSV:
case IF_JSON:
case IF_JSONTIME:
break;
default:
if (strlen(im->graphfile)) {
cairo_show_page(im->cr);
} else {
cairo_surface_finish(im->surface);
}
break;
}
return 0;
}
int graph_paint_xy(
image_desc_t UNUSED(*im), int UNUSED(lazy), int UNUSED(cnt))
{
rrd_set_error("XY diagramm not implemented");
return -1;
}
/*****************************************************
* graph stuff
*****************************************************/
int gdes_alloc(
image_desc_t *im)
{
im->gdes_c++;
if ((im->gdes = (graph_desc_t *)
rrd_realloc(im->gdes, (im->gdes_c)
* sizeof(graph_desc_t))) == NULL) {
rrd_set_error("realloc graph_descs");
return -1;
}
/* set to zero */
memset(&(im->gdes[im->gdes_c - 1]),0,sizeof(graph_desc_t));
im->gdes[im->gdes_c - 1].step = im->step;
im->gdes[im->gdes_c - 1].step_orig = im->step;
im->gdes[im->gdes_c - 1].stack = 0;
im->gdes[im->gdes_c - 1].skipscale = 0;
im->gdes[im->gdes_c - 1].linewidth = 0;
im->gdes[im->gdes_c - 1].debug = 0;
im->gdes[im->gdes_c - 1].start = im->start;
im->gdes[im->gdes_c - 1].start_orig = im->start;
im->gdes[im->gdes_c - 1].end = im->end;
im->gdes[im->gdes_c - 1].end_orig = im->end;
im->gdes[im->gdes_c - 1].vname[0] = '\0';
im->gdes[im->gdes_c - 1].data = NULL;
im->gdes[im->gdes_c - 1].ds_namv = NULL;
im->gdes[im->gdes_c - 1].data_first = 0;
im->gdes[im->gdes_c - 1].p_data = NULL;
im->gdes[im->gdes_c - 1].rpnp = NULL;
im->gdes[im->gdes_c - 1].p_dashes = NULL;
im->gdes[im->gdes_c - 1].shift = 0.0;
im->gdes[im->gdes_c - 1].dash = 0;
im->gdes[im->gdes_c - 1].ndash = 0;
im->gdes[im->gdes_c - 1].offset = 0;
im->gdes[im->gdes_c - 1].col.red = 0.0;
im->gdes[im->gdes_c - 1].col.green = 0.0;
im->gdes[im->gdes_c - 1].col.blue = 0.0;
im->gdes[im->gdes_c - 1].col.alpha = 0.0;
im->gdes[im->gdes_c - 1].col2.red = 0.0;
im->gdes[im->gdes_c - 1].col2.green = 0.0;
im->gdes[im->gdes_c - 1].col2.blue = 0.0;
im->gdes[im->gdes_c - 1].col2.alpha = 0.0;
im->gdes[im->gdes_c - 1].gradheight = 50.0;
im->gdes[im->gdes_c - 1].legend[0] = '\0';
im->gdes[im->gdes_c - 1].format[0] = '\0';
im->gdes[im->gdes_c - 1].strftm = 0;
im->gdes[im->gdes_c - 1].rrd[0] = '\0';
im->gdes[im->gdes_c - 1].ds = -1;
im->gdes[im->gdes_c - 1].cf_reduce = CF_AVERAGE;
im->gdes[im->gdes_c - 1].cf_reduce_set = 0;
im->gdes[im->gdes_c - 1].cf = CF_AVERAGE;
im->gdes[im->gdes_c - 1].yrule = DNAN;
im->gdes[im->gdes_c - 1].xrule = 0;
im->gdes[im->gdes_c - 1].daemon[0] = 0;
return 0;
}
/* copies input untill the first unescaped colon is found
or until input ends. backslashes have to be escaped as well */
int scan_for_col(
const char *const input,
int len,
char *const output)
{
int inp, outp = 0;
for (inp = 0; inp < len && input[inp] != ':' && input[inp] != '\0'; inp++) {
if (input[inp] == '\\'
&& input[inp + 1] != '\0'
&& (input[inp + 1] == '\\' || input[inp + 1] == ':')) {
output[outp++] = input[++inp];
} else {
output[outp++] = input[inp];
}
}
output[outp] = '\0';
return inp;
}
/* Now just a wrapper around rrd_graph_v */
int rrd_graph(
int argc,
char **argv,
char ***prdata,
int *xsize,
int *ysize,
FILE * stream,
double *ymin,
double *ymax)
{
int prlines = 0;
rrd_info_t *grinfo = NULL;
rrd_info_t *walker;
grinfo = rrd_graph_v(argc, argv);
if (grinfo == NULL)
return -1;
walker = grinfo;
(*prdata) = NULL;
while (walker) {
if (strcmp(walker->key, "image_info") == 0) {
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
/* imginfo goes to position 0 in the prdata array */
(*prdata)[prlines - 1] = strdup(walker->value.u_str);
(*prdata)[prlines] = NULL;
}
/* skip anything else */
walker = walker->next;
}
walker = grinfo;
*xsize = 0;
*ysize = 0;
*ymin = 0;
*ymax = 0;
while (walker) {
if (strcmp(walker->key, "image_width") == 0) {
*xsize = walker->value.u_cnt;
} else if (strcmp(walker->key, "image_height") == 0) {
*ysize = walker->value.u_cnt;
} else if (strcmp(walker->key, "value_min") == 0) {
*ymin = walker->value.u_val;
} else if (strcmp(walker->key, "value_max") == 0) {
*ymax = walker->value.u_val;
} else if (strncmp(walker->key, "print", 5) == 0) { /* keys are prdate[0..] */
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
(*prdata)[prlines - 1] = strdup(walker->value.u_str);
(*prdata)[prlines] = NULL;
} else if (strcmp(walker->key, "image") == 0) {
if ( fwrite(walker->value.u_blo.ptr, walker->value.u_blo.size, 1,
(stream ? stream : stdout)) == 0 && ferror(stream ? stream : stdout)){
rrd_set_error("writing image");
return 0;
}
}
/* skip anything else */
walker = walker->next;
}
rrd_info_free(grinfo);
return 0;
}
/* Some surgery done on this function, it became ridiculously big.
** Things moved:
** - initializing now in rrd_graph_init()
** - options parsing now in rrd_graph_options()
** - script parsing now in rrd_graph_script()
*/
rrd_info_t *rrd_graph_v(
int argc,
char **argv)
{
image_desc_t im;
rrd_info_t *grinfo;
rrd_graph_init(&im);
/* a dummy surface so that we can measure text sizes for placements */
rrd_graph_options(argc, argv, &im);
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
if (optind >= argc) {
rrd_info_free(im.grinfo);
im_free(&im);
rrd_set_error("missing filename");
return NULL;
}
if (strlen(argv[optind]) >= MAXPATH) {
rrd_set_error("filename (including path) too long");
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
strncpy(im.graphfile, argv[optind], MAXPATH - 1);
im.graphfile[MAXPATH - 1] = '\0';
if (strcmp(im.graphfile, "-") == 0) {
im.graphfile[0] = '\0';
}
rrd_graph_script(argc, argv, &im, 1);
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* Everything is now read and the actual work can start */
if (graph_paint(&im) == -1) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* The image is generated and needs to be output.
** Also, if needed, print a line with information about the image.
*/
if (im.imginfo && *im.imginfo) {
rrd_infoval_t info;
char *path;
char *filename;
if (bad_format_imginfo(im.imginfo)) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
path = strdup(im.graphfile);
filename = basename(path);
info.u_str =
sprintf_alloc(im.imginfo,
filename,
(long) (im.zoom *
im.ximg), (long) (im.zoom * im.yimg));
grinfo_push(&im, sprintf_alloc("image_info"), RD_I_STR, info);
free(info.u_str);
free(path);
}
if (im.rendered_image) {
rrd_infoval_t img;
img.u_blo.size = im.rendered_image_size;
img.u_blo.ptr = im.rendered_image;
grinfo_push(&im, sprintf_alloc("image"), RD_I_BLO, img);
}
grinfo = im.grinfo;
im_free(&im);
return grinfo;
}
static void
rrd_set_font_desc (
image_desc_t *im,int prop,char *font, double size ){
if (font){
strncpy(im->text_prop[prop].font, font, sizeof(text_prop[prop].font) - 1);
im->text_prop[prop].font[sizeof(text_prop[prop].font) - 1] = '\0';
/* if we already got one, drop it first */
pango_font_description_free(im->text_prop[prop].font_desc);
im->text_prop[prop].font_desc = pango_font_description_from_string( font );
};
if (size > 0){
im->text_prop[prop].size = size;
};
if (im->text_prop[prop].font_desc && im->text_prop[prop].size ){
pango_font_description_set_size(im->text_prop[prop].font_desc, im->text_prop[prop].size * PANGO_SCALE);
};
}
void rrd_graph_init(
image_desc_t
*im)
{
unsigned int i;
char *deffont = getenv("RRD_DEFAULT_FONT");
static PangoFontMap *fontmap = NULL;
PangoContext *context;
/* zero the whole structure first */
memset(im,0,sizeof(image_desc_t));
#ifdef HAVE_TZSET
tzset();
#endif
im->gdef_map = g_hash_table_new_full(g_str_hash, g_str_equal,g_free,NULL);
//use of g_free() cause heap damage on windows. Key is allocated by malloc() in sprintf_alloc(), so free() must use
im->rrd_map = g_hash_table_new_full(g_str_hash, g_str_equal,free,NULL);
im->graph_type = GTYPE_TIME;
im->base = 1000;
im->daemon_addr = NULL;
im->draw_x_grid = 1;
im->draw_y_grid = 1;
im->draw_3d_border = 2;
im->dynamic_labels = 0;
im->extra_flags = 0;
im->font_options = cairo_font_options_create();
im->forceleftspace = 0;
im->gdes_c = 0;
im->gdes = NULL;
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
im->grid_dash_off = 1;
im->grid_dash_on = 1;
im->gridfit = 1;
im->grinfo = (rrd_info_t *) NULL;
im->grinfo_current = (rrd_info_t *) NULL;
im->imgformat = IF_PNG;
im->imginfo = NULL;
im->lazy = 0;
im->legenddirection = TOP_DOWN;
im->legendheight = 0;
im->legendposition = SOUTH;
im->legendwidth = 0;
im->logarithmic = 0;
im->maxval = DNAN;
im->minval = 0;
im->minval = DNAN;
im->magfact = 1;
im->prt_c = 0;
im->rigid = 0;
im->rendered_image_size = 0;
im->rendered_image = NULL;
im->slopemode = 0;
im->step = 0;
im->symbol = ' ';
im->tabwidth = 40.0;
im->title = NULL;
im->unitsexponent = 9999;
im->unitslength = 6;
im->viewfactor = 1.0;
im->watermark = NULL;
im->xlab_form = NULL;
im->with_markup = 0;
im->ximg = 0;
im->xlab_user.minsec = -1;
im->xorigin = 0;
im->xOriginLegend = 0;
im->xOriginLegendY = 0;
im->xOriginLegendY2 = 0;
im->xOriginTitle = 0;
im->xsize = 400;
im->ygridstep = DNAN;
im->yimg = 0;
im->ylegend = NULL;
im->second_axis_scale = 0; /* 0 disables it */
im->second_axis_shift = 0; /* no shift by default */
im->second_axis_legend = NULL;
im->second_axis_format = NULL;
im->primary_axis_format = NULL;
im->yorigin = 0;
im->yOriginLegend = 0;
im->yOriginLegendY = 0;
im->yOriginLegendY2 = 0;
im->yOriginTitle = 0;
im->ysize = 100;
im->zoom = 1;
im->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 10, 10);
im->cr = cairo_create(im->surface);
for (i = 0; i < DIM(text_prop); i++) {
im->text_prop[i].size = -1;
im->text_prop[i].font_desc = NULL;
rrd_set_font_desc(im,i, deffont ? deffont : text_prop[i].font,text_prop[i].size);
}
if (fontmap == NULL){
fontmap = pango_cairo_font_map_get_default();
}
context = pango_font_map_create_context(fontmap);
pango_cairo_context_set_resolution(context, 100);
pango_cairo_update_context(im->cr,context);
im->layout = pango_layout_new(context);
g_object_unref (context);
// im->layout = pango_cairo_create_layout(im->cr);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
cairo_font_options_set_hint_metrics
(im->font_options, CAIRO_HINT_METRICS_ON);
cairo_font_options_set_antialias(im->font_options, CAIRO_ANTIALIAS_GRAY);
for (i = 0; i < DIM(graph_col); i++)
im->graph_col[i] = graph_col[i];
}
void rrd_graph_options(
int argc,
char *argv[],
image_desc_t
*im)
{
int stroff;
char *parsetime_error = NULL;
char scan_gtm[12], scan_mtm[12], scan_ltm[12], col_nam[12];
char double_str[20], double_str2[20];
time_t start_tmp = 0, end_tmp = 0;
long long_tmp;
rrd_time_value_t start_tv, end_tv;
long unsigned int color;
/* defines for long options without a short equivalent. should be bytes,
and may not collide with (the ASCII value of) short options */
#define LONGOPT_UNITS_SI 255
/* *INDENT-OFF* */
struct option long_options[] = {
{ "alt-autoscale", no_argument, 0, 'A'},
{ "imgformat", required_argument, 0, 'a'},
{ "font-smoothing-threshold", required_argument, 0, 'B'},
{ "base", required_argument, 0, 'b'},
{ "color", required_argument, 0, 'c'},
{ "full-size-mode", no_argument, 0, 'D'},
{ "daemon", required_argument, 0, 'd'},
{ "slope-mode", no_argument, 0, 'E'},
{ "end", required_argument, 0, 'e'},
{ "force-rules-legend", no_argument, 0, 'F'},
{ "imginfo", required_argument, 0, 'f'},
{ "graph-render-mode", required_argument, 0, 'G'},
{ "no-legend", no_argument, 0, 'g'},
{ "height", required_argument, 0, 'h'},
{ "no-minor", no_argument, 0, 'I'},
{ "interlaced", no_argument, 0, 'i'},
{ "alt-autoscale-min", no_argument, 0, 'J'},
{ "only-graph", no_argument, 0, 'j'},
{ "units-length", required_argument, 0, 'L'},
{ "lower-limit", required_argument, 0, 'l'},
{ "alt-autoscale-max", no_argument, 0, 'M'},
{ "zoom", required_argument, 0, 'm'},
{ "no-gridfit", no_argument, 0, 'N'},
{ "font", required_argument, 0, 'n'},
{ "logarithmic", no_argument, 0, 'o'},
{ "pango-markup", no_argument, 0, 'P'},
{ "font-render-mode", required_argument, 0, 'R'},
{ "rigid", no_argument, 0, 'r'},
{ "step", required_argument, 0, 'S'},
{ "start", required_argument, 0, 's'},
{ "tabwidth", required_argument, 0, 'T'},
{ "title", required_argument, 0, 't'},
{ "upper-limit", required_argument, 0, 'u'},
{ "vertical-label", required_argument, 0, 'v'},
{ "watermark", required_argument, 0, 'W'},
{ "width", required_argument, 0, 'w'},
{ "units-exponent", required_argument, 0, 'X'},
{ "x-grid", required_argument, 0, 'x'},
{ "alt-y-grid", no_argument, 0, 'Y'},
{ "y-grid", required_argument, 0, 'y'},
{ "lazy", no_argument, 0, 'z'},
{ "use-nan-for-all-missing-data", no_argument, 0, 'Z'},
{ "units", required_argument, 0, LONGOPT_UNITS_SI},
{ "alt-y-mrtg", no_argument, 0, 1000}, /* this has no effect it is just here to save old apps from crashing when they use it */
{ "disable-rrdtool-tag",no_argument, 0, 1001},
{ "right-axis", required_argument, 0, 1002},
{ "right-axis-label", required_argument, 0, 1003},
{ "right-axis-format", required_argument, 0, 1004},
{ "legend-position", required_argument, 0, 1005},
{ "legend-direction", required_argument, 0, 1006},
{ "border", required_argument, 0, 1007},
{ "grid-dash", required_argument, 0, 1008},
{ "dynamic-labels", no_argument, 0, 1009},
{ "week-fmt", required_argument, 0, 1010},
{ "graph-type", required_argument, 0, 1011},
{ "left-axis-format", required_argument, 0, 1012},
{ 0, 0, 0, 0}
};
/* *INDENT-ON* */
optind = 0;
opterr = 0; /* initialize getopt */
rrd_parsetime("end-24h", &start_tv);
rrd_parsetime("now", &end_tv);
while (1) {
int option_index = 0;
int opt;
int col_start, col_end;
opt = getopt_long(argc, argv,
"Aa:B:b:c:Dd:Ee:Ff:G:gh:IiJjL:l:Mm:Nn:oPR:rS:s:T:t:u:v:W:w:X:x:Yy:Zz",
long_options, &option_index);
if (opt == EOF)
break;
switch (opt) {
case 'I':
im->extra_flags |= NOMINOR;
break;
case 'Y':
im->extra_flags |= ALTYGRID;
break;
case 'A':
im->extra_flags |= ALTAUTOSCALE;
break;
case 'J':
im->extra_flags |= ALTAUTOSCALE_MIN;
break;
case 'M':
im->extra_flags |= ALTAUTOSCALE_MAX;
break;
case 'j':
im->extra_flags |= ONLY_GRAPH;
break;
case 'g':
im->extra_flags |= NOLEGEND;
break;
case 'Z':
im->extra_flags |= ALLOW_MISSING_DS;
break;
case 1005:
if (strcmp(optarg, "north") == 0) {
im->legendposition = NORTH;
} else if (strcmp(optarg, "west") == 0) {
im->legendposition = WEST;
} else if (strcmp(optarg, "south") == 0) {
im->legendposition = SOUTH;
} else if (strcmp(optarg, "east") == 0) {
im->legendposition = EAST;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 1006:
if (strcmp(optarg, "topdown") == 0) {
im->legenddirection = TOP_DOWN;
} else if (strcmp(optarg, "bottomup") == 0) {
im->legenddirection = BOTTOM_UP;
} else if (strcmp(optarg, "bottomup2") == 0) {
im->legenddirection = BOTTOM_UP2;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 'F':
im->extra_flags |= FORCE_RULES_LEGEND;
break;
case 1001:
im->extra_flags |= NO_RRDTOOL_TAG;
break;
case LONGOPT_UNITS_SI:
if (im->extra_flags & FORCE_UNITS) {
rrd_set_error("--units can only be used once!");
return;
}
if (strcmp(optarg, "si") == 0)
im->extra_flags |= FORCE_UNITS_SI;
else {
rrd_set_error("invalid argument for --units: %s", optarg);
return;
}
break;
case 'X':
im->unitsexponent = atoi(optarg);
break;
case 'L':
im->unitslength = atoi(optarg);
im->forceleftspace = 1;
break;
case 'T':
if (rrd_strtodbl(optarg, 0, &(im->tabwidth), "option -T") != 2)
return;
break;
case 'S':
im->step = atoi(optarg);
break;
case 'N':
im->gridfit = 0;
break;
case 'P':
im->with_markup = 1;
break;
case 's':
if ((parsetime_error = rrd_parsetime(optarg, &start_tv))) {
rrd_set_error("start time: %s", parsetime_error);
return;
}
break;
case 'e':
if ((parsetime_error = rrd_parsetime(optarg, &end_tv))) {
rrd_set_error("end time: %s", parsetime_error);
return;
}
break;
case 'x':
if (strcmp(optarg, "none") == 0) {
im->draw_x_grid = 0;
break;
};
if (sscanf(optarg,
"%10[A-Z]:%ld:%10[A-Z]:%ld:%10[A-Z]:%ld:%ld:%n",
scan_gtm,
&im->xlab_user.gridst,
scan_mtm,
&im->xlab_user.mgridst,
scan_ltm,
&im->xlab_user.labst,
&im->xlab_user.precis, &stroff) == 7 && stroff != 0) {
im->xlab_form=strdup(optarg + stroff);
if (!im->xlab_form) {
rrd_set_error("cannot allocate memory for xlab_form");
return;
}
if ((int)
(im->xlab_user.gridtm = tmt_conv(scan_gtm)) == -1) {
rrd_set_error("unknown keyword %s", scan_gtm);
return;
} else if ((int)
(im->xlab_user.mgridtm = tmt_conv(scan_mtm))
== -1) {
rrd_set_error("unknown keyword %s", scan_mtm);
return;
} else if ((int)
(im->xlab_user.labtm = tmt_conv(scan_ltm)) == -1) {
rrd_set_error("unknown keyword %s", scan_ltm);
return;
}
im->xlab_user.minsec = 1;
im->xlab_user.stst = im->xlab_form ? im->xlab_form : "";
} else {
rrd_set_error("invalid x-grid format");
return;
}
break;
case 'y':
if (strcmp(optarg, "none") == 0) {
im->draw_y_grid = 0;
break;
};
if (sscanf(optarg, "%[-0-9.e+]:%d", double_str , &im->ylabfact) == 2) {
if (rrd_strtodbl( double_str, 0, &(im->ygridstep), "option -y") != 2){
return;
}
if (im->ygridstep <= 0) {
rrd_set_error("grid step must be > 0");
return;
} else if (im->ylabfact < 1) {
rrd_set_error("label factor must be > 0");
return;
}
} else {
rrd_set_error("invalid y-grid format");
return;
}
break;
case 1007:
im->draw_3d_border = atoi(optarg);
break;
case 1008: /* grid-dash */
if(sscanf(optarg,
"%[-0-9.e+]:%[-0-9.e+]",
double_str,
double_str2 ) != 2) {
if ( rrd_strtodbl( double_str, 0, &(im->grid_dash_on),NULL) !=2
|| rrd_strtodbl( double_str2, 0, &(im->grid_dash_off), NULL) != 2 ){
rrd_set_error("expected grid-dash format float:float");
return;
}
}
break;
case 1009: /* enable dynamic labels */
im->dynamic_labels = 1;
break;
case 1010:
strncpy(week_fmt,optarg,sizeof week_fmt);
week_fmt[(sizeof week_fmt)-1]='\0';
break;
case 1002: /* right y axis */
if(sscanf(optarg,
"%[-0-9.e+]:%[-0-9.e+]",
double_str,
double_str2 ) == 2
&& rrd_strtodbl( double_str, 0, &(im->second_axis_scale),NULL) == 2
&& rrd_strtodbl( double_str2, 0, &(im->second_axis_shift),NULL) == 2){
if(im->second_axis_scale==0){
rrd_set_error("the second_axis_scale must not be 0");
return;
}
} else {
rrd_set_error("invalid right-axis format expected scale:shift");
return;
}
break;
case 1003:
im->second_axis_legend=strdup(optarg);
if (!im->second_axis_legend) {
rrd_set_error("cannot allocate memory for second_axis_legend");
return;
}
break;
case 1004:
if (bad_format_axis(optarg)){
return;
}
im->second_axis_format=strdup(optarg);
if (!im->second_axis_format) {
rrd_set_error("cannot allocate memory for second_axis_format");
return;
}
break;
case 1012:
if (bad_format_axis(optarg)){
return;
}
im->primary_axis_format=strdup(optarg);
if (!im->primary_axis_format) {
rrd_set_error("cannot allocate memory for primary_axis_format");
return;
}
break;
case 'v':
im->ylegend=strdup(optarg);
if (!im->ylegend) {
rrd_set_error("cannot allocate memory for ylegend");
return;
}
break;
case 'u':
if (rrd_strtodbl(optarg, 0, &(im->maxval), "option -u") != 2){
return;
}
break;
case 'l':
if (rrd_strtodbl(optarg, 0, &(im->minval), "option -l") != 2){
return;
}
break;
case 'b':
im->base = atol(optarg);
if (im->base != 1024 && im->base != 1000) {
rrd_set_error
("the only sensible value for base apart from 1000 is 1024");
return;
}
break;
case 'w':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("width below 10 pixels");
return;
}
im->xsize = long_tmp;
break;
case 'h':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("height below 10 pixels");
return;
}
im->ysize = long_tmp;
break;
case 'D':
im->extra_flags |= FULL_SIZE_MODE;
break;
case 'i':
/* interlaced png not supported at the moment */
break;
case 'r':
im->rigid = 1;
break;
case 'f':
im->imginfo = optarg;
break;
case 'a':
if ((int)
(im->imgformat = if_conv(optarg)) == -1) {
rrd_set_error("unsupported graphics format '%s'", optarg);
return;
}
break;
case 1011:
if ((int)
(im->graph_type = type_conv(optarg)) == -1) {
rrd_set_error("unsupported graphics type '%s'", optarg);
return;
}
break;
case 'z':
im->lazy = 1;
break;
case 'E':
im->slopemode = 1;
break;
case 'o':
im->logarithmic = 1;
break;
case 'c':
if (sscanf(optarg,
"%10[A-Z]#%n%8lx%n",
col_nam, &col_start, &color, &col_end) == 2) {
int ci;
int col_len = col_end - col_start;
switch (col_len) {
case 3:
color =
(((color & 0xF00) * 0x110000) | ((color & 0x0F0) *
0x011000) |
((color & 0x00F)
* 0x001100)
| 0x000000FF);
break;
case 4:
color =
(((color & 0xF000) *
0x11000) | ((color & 0x0F00) *
0x01100) | ((color &
0x00F0) *
0x00110) |
((color & 0x000F) * 0x00011)
);
break;
case 6:
color = (color << 8) + 0xff /* shift left by 8 */ ;
break;
case 8:
break;
default:
rrd_set_error("the color format is #RRGGBB[AA]");
return;
}
if ((ci = grc_conv(col_nam)) != -1) {
im->graph_col[ci] = gfx_hex_to_col(color);
} else {
rrd_set_error("invalid color name '%s'", col_nam);
return;
}
} else {
rrd_set_error("invalid color def format");
return;
}
break;
case 'n':{
char prop[15];
double size = 1;
int end;
if (sscanf(optarg, "%10[A-Z]:%[-0-9.e+]%n", prop, double_str, &end) >= 2
&& rrd_strtodbl( double_str, 0, &size, NULL) == 2) {
int sindex, propidx;
if ((sindex = text_prop_conv(prop)) != -1) {
for (propidx = sindex;
propidx < TEXT_PROP_LAST; propidx++) {
if (size > 0) {
rrd_set_font_desc(im,propidx,NULL,size);
}
if ((int) strlen(optarg) > end+2) {
if (optarg[end] == ':') {
rrd_set_font_desc(im,propidx,optarg + end + 1,0);
} else {
rrd_set_error
("expected : after font size in '%s'",
optarg);
return;
}
}
/* only run the for loop for DEFAULT (0) for
all others, we break here. woodo programming */
if (propidx == sindex && sindex != 0)
break;
}
} else {
rrd_set_error("invalid fonttag '%s'", prop);
return;
}
} else {
rrd_set_error("invalid text property format");
return;
}
break;
}
case 'm':
if (rrd_strtodbl(optarg, 0, &(im->zoom), "option -m") != 2){
return;
}
if (im->zoom <= 0.0) {
rrd_set_error("zoom factor must be > 0");
return;
}
break;
case 't':
im->title=strdup(optarg);
if (!im->title) {
rrd_set_error("cannot allocate memory for title");
return;
}
break;
case 'R':
if (strcmp(optarg, "normal") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else if (strcmp(optarg, "light") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_SLIGHT);
} else if (strcmp(optarg, "mono") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_NONE);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else {
rrd_set_error("unknown font-render-mode '%s'", optarg);
return;
}
break;
case 'G':
if (strcmp(optarg, "normal") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
else if (strcmp(optarg, "mono") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_NONE;
else {
rrd_set_error("unknown graph-render-mode '%s'", optarg);
return;
}
break;
case 'B':
/* not supported curently */
break;
case 'W':
im->watermark=strdup(optarg);
if (!im->watermark) {
rrd_set_error("cannot allocate memory for watermark");
return;
}
break;
case 'd':
{
if (im->daemon_addr != NULL)
{
rrd_set_error ("You cannot specify --daemon "
"more than once.");
return;
}
im->daemon_addr = strdup(optarg);
if (im->daemon_addr == NULL)
{
rrd_set_error("strdup failed");
return;
}
break;
}
case '?':
if (optopt != 0)
rrd_set_error("unknown option '%c'", optopt);
else
rrd_set_error("unknown option '%s'", argv[optind - 1]);
return;
}
} /* while (1) */
pango_cairo_context_set_font_options(pango_layout_get_context(im->layout), im->font_options);
pango_layout_context_changed(im->layout);
if (im->logarithmic && im->minval <= 0) {
rrd_set_error
("for a logarithmic yaxis you must specify a lower-limit > 0");
return;
}
if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
/* error string is set in rrd_parsetime.c */
return;
}
if (start_tmp < 3600 * 24 * 365 * 10) {
rrd_set_error
("the first entry to fetch should be after 1980 (%ld)",
start_tmp);
return;
}
if (end_tmp < start_tmp) {
rrd_set_error
("start (%ld) should be less than end (%ld)", start_tmp, end_tmp);
return;
}
im->start = start_tmp;
im->end = end_tmp;
im->step = max((long) im->step, (im->end - im->start) / im->xsize);
}
int rrd_graph_color(
image_desc_t
*im,
char *var,
char *err,
int optional)
{
char *color;
graph_desc_t *gdp = &im->gdes[im->gdes_c - 1];
color = strstr(var, "#");
if (color == NULL) {
if (optional == 0) {
rrd_set_error("Found no color in %s", err);
return 0;
}
return 0;
} else {
int n = 0;
char *rest;
long unsigned int col;
rest = strstr(color, ":");
if (rest != NULL)
n = rest - color;
else
n = strlen(color);
switch (n) {
case 7:
sscanf(color, "#%6lx%n", &col, &n);
col = (col << 8) + 0xff /* shift left by 8 */ ;
if (n != 7)
rrd_set_error("Color problem in %s", err);
break;
case 9:
sscanf(color, "#%8lx%n", &col, &n);
if (n == 9)
break;
default:
rrd_set_error("Color problem in %s", err);
}
if (rrd_test_error())
return 0;
gdp->col = gfx_hex_to_col(col);
return n;
}
}
static int bad_format_check(const char *pattern, char *fmt) {
GError *gerr = NULL;
GRegex *re = g_regex_new(pattern, G_REGEX_EXTENDED, 0, &gerr);
GMatchInfo *mi;
if (gerr != NULL) {
rrd_set_error("cannot compile regular expression: %s (%s)", gerr->message,pattern);
return 1;
}
int m = g_regex_match(re, fmt, 0, &mi);
g_match_info_free (mi);
g_regex_unref(re);
if (!m) {
rrd_set_error("invalid format string '%s' (should match '%s')",fmt,pattern);
return 1;
}
return 0;
}
#define SAFE_STRING "(?:[^%]+|%%)*"
int bad_format_imginfo(char *fmt){
return bad_format_check("^" SAFE_STRING "%s" SAFE_STRING "%lu" SAFE_STRING "%lu" SAFE_STRING "$",fmt);
}
#define FLOAT_STRING "%[+- 0#]?[0-9]*([.][0-9]+)?l[eEfF]"
int bad_format_axis(char *fmt){
return bad_format_check("^" SAFE_STRING FLOAT_STRING SAFE_STRING "$",fmt);
}
int bad_format_print(char *fmt){
return bad_format_check("^" SAFE_STRING FLOAT_STRING SAFE_STRING "%s" SAFE_STRING "$",fmt);
}
int vdef_parse(
struct graph_desc_t
*gdes,
const char *const str)
{
/* A VDEF currently is either "func" or "param,func"
* so the parsing is rather simple. Change if needed.
*/
double param;
char func[30], double_str[21];
int n;
n = 0;
sscanf(str, "%20[-0-9.e+],%29[A-Z]%n", double_str, func, &n);
if ( rrd_strtodbl( double_str, NULL, ¶m, NULL) != 2 ){
n = 0;
sscanf(str, "%29[A-Z]%n", func, &n);
if (n == (int) strlen(str)) { /* matched */
param = DNAN;
} else {
rrd_set_error
("Unknown function string '%s' in VDEF '%s'",
str, gdes->vname);
return -1;
}
}
if (!strcmp("PERCENT", func))
gdes->vf.op = VDEF_PERCENT;
else if (!strcmp("PERCENTNAN", func))
gdes->vf.op = VDEF_PERCENTNAN;
else if (!strcmp("MAXIMUM", func))
gdes->vf.op = VDEF_MAXIMUM;
else if (!strcmp("AVERAGE", func))
gdes->vf.op = VDEF_AVERAGE;
else if (!strcmp("STDEV", func))
gdes->vf.op = VDEF_STDEV;
else if (!strcmp("MINIMUM", func))
gdes->vf.op = VDEF_MINIMUM;
else if (!strcmp("TOTAL", func))
gdes->vf.op = VDEF_TOTAL;
else if (!strcmp("FIRST", func))
gdes->vf.op = VDEF_FIRST;
else if (!strcmp("LAST", func))
gdes->vf.op = VDEF_LAST;
else if (!strcmp("LSLSLOPE", func))
gdes->vf.op = VDEF_LSLSLOPE;
else if (!strcmp("LSLINT", func))
gdes->vf.op = VDEF_LSLINT;
else if (!strcmp("LSLCORREL", func))
gdes->vf.op = VDEF_LSLCORREL;
else {
rrd_set_error
("Unknown function '%s' in VDEF '%s'\n", func, gdes->vname);
return -1;
};
switch (gdes->vf.op) {
case VDEF_PERCENT:
case VDEF_PERCENTNAN:
if (isnan(param)) { /* no parameter given */
rrd_set_error
("Function '%s' needs parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
if (param >= 0.0 && param <= 100.0) {
gdes->vf.param = param;
gdes->vf.val = DNAN; /* undefined */
gdes->vf.when = 0; /* undefined */
gdes->vf.never = 1;
} else {
rrd_set_error
("Parameter '%f' out of range in VDEF '%s'\n",
param, gdes->vname);
return -1;
};
break;
case VDEF_MAXIMUM:
case VDEF_AVERAGE:
case VDEF_STDEV:
case VDEF_MINIMUM:
case VDEF_TOTAL:
case VDEF_FIRST:
case VDEF_LAST:
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:
if (isnan(param)) {
gdes->vf.param = DNAN;
gdes->vf.val = DNAN;
gdes->vf.when = 0;
gdes->vf.never = 1;
} else {
rrd_set_error
("Function '%s' needs no parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
break;
};
return 0;
}
int vdef_calc(
image_desc_t *im,
int gdi)
{
graph_desc_t *src, *dst;
rrd_value_t *data;
long step, steps;
dst = &im->gdes[gdi];
src = &im->gdes[dst->vidx];
data = src->data + src->ds;
steps = (src->end - src->start) / src->step;
#if 0
printf
("DEBUG: start == %lu, end == %lu, %lu steps\n",
src->start, src->end, steps);
#endif
switch (dst->vf.op) {
case VDEF_PERCENT:{
rrd_value_t *array;
int field;
if ((array = (rrd_value_t*)malloc(steps * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
for (step = 0; step < steps; step++) {
array[step] = data[step * src->ds_cnt];
}
qsort(array, step, sizeof(double), vdef_percent_compar);
field = round((dst->vf.param * (double)(steps - 1)) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
free(array);
#if 0
for (step = 0; step < steps; step++)
printf("DEBUG: %3li:%10.2f %c\n",
step, array[step], step == field ? '*' : ' ');
#endif
}
break;
case VDEF_PERCENTNAN:{
rrd_value_t *array;
int field;
/* count number of "valid" values */
int nancount=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) { nancount++; }
}
/* and allocate it */
if ((array = (rrd_value_t*)malloc(nancount * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
/* and fill it in */
field=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) {
array[field] = data[step * src->ds_cnt];
field++;
}
}
qsort(array, nancount, sizeof(double), vdef_percent_compar);
field = round( dst->vf.param * (double)(nancount - 1) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
free(array);
}
break;
case VDEF_MAXIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] > dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
}
step++;
}
break;
case VDEF_TOTAL:
case VDEF_STDEV:
case VDEF_AVERAGE:{
int cnt = 0;
double sum = 0.0;
double average = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += data[step * src->ds_cnt];
cnt++;
};
}
if (cnt) {
if (dst->vf.op == VDEF_TOTAL) {
dst->vf.val = sum * src->step;
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
} else if (dst->vf.op == VDEF_AVERAGE) {
dst->vf.val = sum / cnt;
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
} else {
average = sum / cnt;
sum = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += pow((data[step * src->ds_cnt] - average), 2.0);
};
}
dst->vf.val = pow(sum / cnt, 0.5);
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
}
}
break;
case VDEF_MINIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] < dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
}
step++;
}
break;
case VDEF_FIRST:
/* The time value returned here is one step before the
* actual time value. This is the start of the first
* non-NaN interval.
*/
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + step * src->step;
dst->vf.never = 0;
}
break;
case VDEF_LAST:
/* The time value returned here is the
* actual time value. This is the end of the last
* non-NaN interval.
*/
step = steps - 1;
while (step >= 0 && isnan(data[step * src->ds_cnt]))
step--;
if (step < 0) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
break;
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:{
/* Bestfit line by linear least squares method */
int cnt = 0;
double SUMx, SUMy, SUMxy, SUMxx, SUMyy, slope, y_intercept, correl;
SUMx = 0;
SUMy = 0;
SUMxy = 0;
SUMxx = 0;
SUMyy = 0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
cnt++;
SUMx += step;
SUMxx += step * step;
SUMxy += step * data[step * src->ds_cnt];
SUMy += data[step * src->ds_cnt];
SUMyy += data[step * src->ds_cnt] * data[step * src->ds_cnt];
};
}
slope = (SUMx * SUMy - cnt * SUMxy) / (SUMx * SUMx - cnt * SUMxx);
y_intercept = (SUMy - slope * SUMx) / cnt;
correl =
(SUMxy -
(SUMx * SUMy) / cnt) /
sqrt((SUMxx -
(SUMx * SUMx) / cnt) * (SUMyy - (SUMy * SUMy) / cnt));
if (cnt) {
if (dst->vf.op == VDEF_LSLSLOPE) {
dst->vf.val = slope;
dst->vf.when = 0;
dst->vf.never = 1;
} else if (dst->vf.op == VDEF_LSLINT) {
dst->vf.val = y_intercept;
dst->vf.when = 0;
dst->vf.never = 1;
} else if (dst->vf.op == VDEF_LSLCORREL) {
dst->vf.val = correl;
dst->vf.when = 0;
dst->vf.never = 1;
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
}
}
break;
}
return 0;
}
/* NaN < -INF < finite_values < INF */
int vdef_percent_compar(
const void
*a,
const void
*b)
{
/* Equality is not returned; this doesn't hurt except
* (maybe) for a little performance.
*/
/* First catch NaN values. They are smallest */
if (isnan(*(double *) a))
return -1;
if (isnan(*(double *) b))
return 1;
/* NaN doesn't reach this part so INF and -INF are extremes.
* The sign from isinf() is compatible with the sign we return
*/
if (isinf(*(double *) a))
return isinf(*(double *) a);
if (isinf(*(double *) b))
return isinf(*(double *) b);
/* If we reach this, both values must be finite */
if (*(double *) a < *(double *) b)
return -1;
else
return 1;
}
void grinfo_push(
image_desc_t *im,
char *key,
rrd_info_type_t type,
rrd_infoval_t value)
{
im->grinfo_current = rrd_info_push(im->grinfo_current, key, type, value);
if (im->grinfo == NULL) {
im->grinfo = im->grinfo_current;
}
}
void time_clean(
char *result,
char *format)
{
int j, jj;
/* Handling based on
- ANSI C99 Specifications http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
- Single UNIX Specification version 2 http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html
- POSIX:2001/Single UNIX Specification version 3 http://www.opengroup.org/onlinepubs/009695399/functions/strftime.html
- POSIX:2008 Specifications http://www.opengroup.org/onlinepubs/9699919799/functions/strftime.html
Specifications tells
"If a conversion specifier is not one of the above, the behavior is undefined."
C99 tells
"A conversion specifier consists of a % character, possibly followed by an E or O modifier character (described below), followed by a character that determines the behavior of the conversion specifier.
POSIX:2001 tells
"A conversion specification consists of a '%' character, possibly followed by an E or O modifier, and a terminating conversion specifier character that determines the conversion specification's behavior."
POSIX:2008 introduce more complexe behavior that are not handled here.
According to this, this code will replace:
- % followed by @ by a %@
- % followed by by a %SPACE
- % followed by . by a %.
- % followed by % by a %
- % followed by t by a TAB
- % followed by E then anything by '-'
- % followed by O then anything by '-'
- % followed by anything else by at least one '-'. More characters may be added to better fit expected output length
*/
jj = 0;
for(j = 0; (j < FMT_LEG_LEN - 1) && (jj < FMT_LEG_LEN); j++) { /* we don't need to parse the last char */
if (format[j] == '%') {
if ((format[j+1] == 'E') || (format[j+1] == 'O')) {
result[jj++] = '-';
j+=2; /* We skip next 2 following char */
} else if ((format[j+1] == 'C') || (format[j+1] == 'd') ||
(format[j+1] == 'g') || (format[j+1] == 'H') ||
(format[j+1] == 'I') || (format[j+1] == 'm') ||
(format[j+1] == 'M') || (format[j+1] == 'S') ||
(format[j+1] == 'U') || (format[j+1] == 'V') ||
(format[j+1] == 'W') || (format[j+1] == 'y')) {
result[jj++] = '-';
if (jj < FMT_LEG_LEN) {
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'j') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if ((format[j+1] == 'G') || (format[j+1] == 'Y')) {
/* Assuming Year on 4 digit */
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 2) {
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'R') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 3) {
result[jj++] = '-';
result[jj++] = ':';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'T') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 6) {
result[jj++] = '-';
result[jj++] = ':';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = ':';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'F') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 8) {
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'D') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 6) {
result[jj++] = '-';
result[jj++] = '/';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '/';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'n') {
result[jj++] = '\r';
result[jj++] = '\n';
j++; /* We skip the following char */
} else if (format[j+1] == 't') {
result[jj++] = '\t';
j++; /* We skip the following char */
} else if (format[j+1] == '%') {
result[jj++] = '%';
j++; /* We skip the following char */
} else if (format[j+1] == ' ') {
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '%';
result[jj++] = ' ';
}
j++; /* We skip the following char */
} else if (format[j+1] == '.') {
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '%';
result[jj++] = '.';
}
j++; /* We skip the following char */
} else if (format[j+1] == '@') {
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '%';
result[jj++] = '@';
}
j++; /* We skip the following char */
} else {
result[jj++] = '-';
j++; /* We skip the following char */
}
} else {
result[jj++] = format[j];
}
}
result[jj] = '\0'; /* We must force the end of the string */
}
| ./CrossVul/dataset_final_sorted/CWE-134/c/good_2265_0 |
crossvul-cpp_data_bad_2265_0 | /****************************************************************************
* RRDtool 1.4.3 Copyright by Tobi Oetiker, 1997-2010
****************************************************************************
* rrd__graph.c produce graphs from data in rrdfiles
****************************************************************************/
#include <sys/stat.h>
#ifdef WIN32
#include "strftime.h"
#endif
#include "rrd_strtod.h"
#include "rrd_tool.h"
#include "unused.h"
/* for basename */
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#else
#include "plbasename.h"
#endif
#if defined(WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
#include <io.h>
#include <fcntl.h>
#endif
#include <time.h>
#include <locale.h>
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#include "rrd_graph.h"
#include "rrd_client.h"
/* some constant definitions */
#ifndef RRD_DEFAULT_FONT
/* there is special code later to pick Cour.ttf when running on windows */
#define RRD_DEFAULT_FONT "DejaVu Sans Mono,Bitstream Vera Sans Mono,monospace,Courier"
#endif
text_prop_t text_prop[] = {
{8.0, RRD_DEFAULT_FONT,NULL}
, /* default */
{9.0, RRD_DEFAULT_FONT,NULL}
, /* title */
{7.0, RRD_DEFAULT_FONT,NULL}
, /* axis */
{8.0, RRD_DEFAULT_FONT,NULL}
, /* unit */
{8.0, RRD_DEFAULT_FONT,NULL} /* legend */
,
{5.5, RRD_DEFAULT_FONT,NULL} /* watermark */
};
char week_fmt[128] = "Week %V";
xlab_t xlab[] = {
{0, 0, TMT_SECOND, 30, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{2, 0, TMT_MINUTE, 1, TMT_MINUTE, 5, TMT_MINUTE, 5, 0, "%H:%M"}
,
{5, 0, TMT_MINUTE, 2, TMT_MINUTE, 10, TMT_MINUTE, 10, 0, "%H:%M"}
,
{10, 0, TMT_MINUTE, 5, TMT_MINUTE, 20, TMT_MINUTE, 20, 0, "%H:%M"}
,
{30, 0, TMT_MINUTE, 10, TMT_HOUR, 1, TMT_HOUR, 1, 0, "%H:%M"}
,
{60, 0, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 2, 0, "%H:%M"}
,
{60, 24 * 3600, TMT_MINUTE, 30, TMT_HOUR, 2, TMT_HOUR, 6, 0, "%a %H:%M"}
,
{180, 0, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 6, 0, "%H:%M"}
,
{180, 24 * 3600, TMT_HOUR, 1, TMT_HOUR, 6, TMT_HOUR, 12, 0, "%a %H:%M"}
,
/*{300, 0, TMT_HOUR,3, TMT_HOUR,12, TMT_HOUR,12, 12*3600,"%a %p"}, this looks silly */
{600, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%a"}
,
{1200, 0, TMT_HOUR, 6, TMT_DAY, 1, TMT_DAY, 1, 24 * 3600, "%d"}
,
{1800, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a %d"}
,
{2400, 0, TMT_HOUR, 12, TMT_DAY, 1, TMT_DAY, 2, 24 * 3600, "%a"}
,
{3600, 0, TMT_DAY, 1, TMT_WEEK, 1, TMT_WEEK, 1, 7 * 24 * 3600, week_fmt}
,
{3 * 3600, 0, TMT_WEEK, 1, TMT_MONTH, 1, TMT_WEEK, 2, 7 * 24 * 3600, week_fmt}
,
{6 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 1, TMT_MONTH, 1, 30 * 24 * 3600,
"%b"}
,
{48 * 3600, 0, TMT_MONTH, 1, TMT_MONTH, 3, TMT_MONTH, 3, 30 * 24 * 3600,
"%b"}
,
{315360, 0, TMT_MONTH, 3, TMT_YEAR, 1, TMT_YEAR, 1, 365 * 24 * 3600, "%Y"}
,
{10 * 24 * 3600, 0, TMT_YEAR, 1, TMT_YEAR, 1, TMT_YEAR, 1,
365 * 24 * 3600, "%y"}
,
{-1, 0, TMT_MONTH, 0, TMT_MONTH, 0, TMT_MONTH, 0, 0, ""}
};
/* sensible y label intervals ...*/
ylab_t ylab[] = {
{0.1, {1, 2, 5, 10}
}
,
{0.2, {1, 5, 10, 20}
}
,
{0.5, {1, 2, 4, 10}
}
,
{1.0, {1, 2, 5, 10}
}
,
{2.0, {1, 5, 10, 20}
}
,
{5.0, {1, 2, 4, 10}
}
,
{10.0, {1, 2, 5, 10}
}
,
{20.0, {1, 5, 10, 20}
}
,
{50.0, {1, 2, 4, 10}
}
,
{100.0, {1, 2, 5, 10}
}
,
{200.0, {1, 5, 10, 20}
}
,
{500.0, {1, 2, 4, 10}
}
,
{0.0, {0, 0, 0, 0}
}
};
gfx_color_t graph_col[] = /* default colors */
{
{1.00, 1.00, 1.00, 1.00}, /* canvas */
{0.95, 0.95, 0.95, 1.00}, /* background */
{0.81, 0.81, 0.81, 1.00}, /* shade A */
{0.62, 0.62, 0.62, 1.00}, /* shade B */
{0.56, 0.56, 0.56, 0.75}, /* grid */
{0.87, 0.31, 0.31, 0.60}, /* major grid */
{0.00, 0.00, 0.00, 1.00}, /* font */
{0.50, 0.12, 0.12, 1.00}, /* arrow */
{0.12, 0.12, 0.12, 1.00}, /* axis */
{0.00, 0.00, 0.00, 1.00} /* frame */
};
/* #define DEBUG */
#ifdef DEBUG
# define DPRINT(x) (void)(printf x, printf("\n"))
#else
# define DPRINT(x)
#endif
/* initialize with xtr(im,0); */
int xtr(
image_desc_t *im,
time_t mytime)
{
static double pixie;
if (mytime == 0) {
pixie = (double) im->xsize / (double) (im->end - im->start);
return im->xorigin;
}
return (int) ((double) im->xorigin + pixie * (mytime - im->start));
}
/* translate data values into y coordinates */
double ytr(
image_desc_t *im,
double value)
{
static double pixie;
double yval;
if (isnan(value)) {
if (!im->logarithmic)
pixie = (double) im->ysize / (im->maxval - im->minval);
else
pixie =
(double) im->ysize / (log10(im->maxval) - log10(im->minval));
yval = im->yorigin;
} else if (!im->logarithmic) {
yval = im->yorigin - pixie * (value - im->minval);
} else {
if (value < im->minval) {
yval = im->yorigin;
} else {
yval = im->yorigin - pixie * (log10(value) - log10(im->minval));
}
}
return yval;
}
/* conversion function for symbolic entry names */
#define conv_if(VV,VVV) \
if (strcmp(#VV, string) == 0) return VVV ;
enum gf_en gf_conv(
char *string)
{
conv_if(PRINT, GF_PRINT);
conv_if(GPRINT, GF_GPRINT);
conv_if(COMMENT, GF_COMMENT);
conv_if(HRULE, GF_HRULE);
conv_if(VRULE, GF_VRULE);
conv_if(LINE, GF_LINE);
conv_if(AREA, GF_AREA);
conv_if(GRAD, GF_GRAD);
conv_if(STACK, GF_STACK);
conv_if(TICK, GF_TICK);
conv_if(TEXTALIGN, GF_TEXTALIGN);
conv_if(DEF, GF_DEF);
conv_if(CDEF, GF_CDEF);
conv_if(VDEF, GF_VDEF);
conv_if(XPORT, GF_XPORT);
conv_if(SHIFT, GF_SHIFT);
return (enum gf_en)(-1);
}
enum gfx_if_en if_conv(
char *string)
{
conv_if(PNG, IF_PNG);
conv_if(SVG, IF_SVG);
conv_if(EPS, IF_EPS);
conv_if(PDF, IF_PDF);
conv_if(XML, IF_XML);
conv_if(XMLENUM, IF_XMLENUM);
conv_if(CSV, IF_CSV);
conv_if(TSV, IF_TSV);
conv_if(SSV, IF_SSV);
conv_if(JSON, IF_JSON);
conv_if(JSONTIME, IF_JSONTIME);
return (enum gfx_if_en)(-1);
}
enum gfx_type_en type_conv(
char *string)
{
conv_if(TIME , GTYPE_TIME);
conv_if(XY, GTYPE_XY);
return (enum gfx_type_en)(-1);
}
enum tmt_en tmt_conv(
char *string)
{
conv_if(SECOND, TMT_SECOND);
conv_if(MINUTE, TMT_MINUTE);
conv_if(HOUR, TMT_HOUR);
conv_if(DAY, TMT_DAY);
conv_if(WEEK, TMT_WEEK);
conv_if(MONTH, TMT_MONTH);
conv_if(YEAR, TMT_YEAR);
return (enum tmt_en)(-1);
}
enum grc_en grc_conv(
char *string)
{
conv_if(BACK, GRC_BACK);
conv_if(CANVAS, GRC_CANVAS);
conv_if(SHADEA, GRC_SHADEA);
conv_if(SHADEB, GRC_SHADEB);
conv_if(GRID, GRC_GRID);
conv_if(MGRID, GRC_MGRID);
conv_if(FONT, GRC_FONT);
conv_if(ARROW, GRC_ARROW);
conv_if(AXIS, GRC_AXIS);
conv_if(FRAME, GRC_FRAME);
return (enum grc_en)(-1);
}
enum text_prop_en text_prop_conv(
char *string)
{
conv_if(DEFAULT, TEXT_PROP_DEFAULT);
conv_if(TITLE, TEXT_PROP_TITLE);
conv_if(AXIS, TEXT_PROP_AXIS);
conv_if(UNIT, TEXT_PROP_UNIT);
conv_if(LEGEND, TEXT_PROP_LEGEND);
conv_if(WATERMARK, TEXT_PROP_WATERMARK);
return (enum text_prop_en)(-1);
}
#undef conv_if
int im_free(
image_desc_t *im)
{
unsigned long i, ii;
cairo_status_t status = (cairo_status_t) 0;
if (im == NULL)
return 0;
if (im->daemon_addr != NULL)
free(im->daemon_addr);
if (im->gdef_map){
g_hash_table_destroy(im->gdef_map);
}
if (im->rrd_map){
g_hash_table_destroy(im->rrd_map);
}
for (i = 0; i < (unsigned) im->gdes_c; i++) {
if (im->gdes[i].data_first) {
/* careful here, because a single pointer can occur several times */
free(im->gdes[i].data);
if (im->gdes[i].ds_namv) {
for (ii = 0; ii < im->gdes[i].ds_cnt; ii++)
free(im->gdes[i].ds_namv[ii]);
free(im->gdes[i].ds_namv);
}
}
/* free allocated memory used for dashed lines */
if (im->gdes[i].p_dashes != NULL)
free(im->gdes[i].p_dashes);
free(im->gdes[i].p_data);
free(im->gdes[i].rpnp);
}
free(im->gdes);
for (i = 0; i < DIM(text_prop);i++){
pango_font_description_free(im->text_prop[i].font_desc);
im->text_prop[i].font_desc = NULL;
}
if (im->font_options)
cairo_font_options_destroy(im->font_options);
if (im->surface)
cairo_surface_destroy(im->surface);
if (im->cr) {
status = cairo_status(im->cr);
cairo_destroy(im->cr);
}
if (status)
fprintf(stderr, "OOPS: Cairo has issues it can't even die: %s\n",
cairo_status_to_string(status));
if (im->rendered_image) {
free(im->rendered_image);
}
if (im->layout) {
g_object_unref(im->layout);
}
if (im->ylegend)
free(im->ylegend);
if (im->title)
free(im->title);
if (im->watermark)
free(im->watermark);
if (im->xlab_form)
free(im->xlab_form);
if (im->second_axis_legend)
free(im->second_axis_legend);
if (im->second_axis_format)
free(im->second_axis_format);
if (im->primary_axis_format)
free(im->primary_axis_format);
return 0;
}
/* find SI magnitude symbol for the given number*/
void auto_scale(
image_desc_t *im, /* image description */
double *value,
char **symb_ptr,
double *magfact)
{
char *symbol[] = { "a", /* 10e-18 Atto */
"f", /* 10e-15 Femto */
"p", /* 10e-12 Pico */
"n", /* 10e-9 Nano */
"u", /* 10e-6 Micro */
"m", /* 10e-3 Milli */
" ", /* Base */
"k", /* 10e3 Kilo */
"M", /* 10e6 Mega */
"G", /* 10e9 Giga */
"T", /* 10e12 Tera */
"P", /* 10e15 Peta */
"E"
}; /* 10e18 Exa */
int symbcenter = 6;
int sindex;
if (*value == 0.0 || isnan(*value)) {
sindex = 0;
*magfact = 1.0;
} else {
sindex = floor(log(fabs(*value)) / log((double) im->base));
*magfact = pow((double) im->base, (double) sindex);
(*value) /= (*magfact);
}
if (sindex <= symbcenter && sindex >= -symbcenter) {
(*symb_ptr) = symbol[sindex + symbcenter];
} else {
(*symb_ptr) = "?";
}
}
/* power prefixes */
static char si_symbol[] = {
'y', /* 10e-24 Yocto */
'z', /* 10e-21 Zepto */
'a', /* 10e-18 Atto */
'f', /* 10e-15 Femto */
'p', /* 10e-12 Pico */
'n', /* 10e-9 Nano */
'u', /* 10e-6 Micro */
'm', /* 10e-3 Milli */
' ', /* Base */
'k', /* 10e3 Kilo */
'M', /* 10e6 Mega */
'G', /* 10e9 Giga */
'T', /* 10e12 Tera */
'P', /* 10e15 Peta */
'E', /* 10e18 Exa */
'Z', /* 10e21 Zeta */
'Y' /* 10e24 Yotta */
};
static const int si_symbcenter = 8;
/* find SI magnitude symbol for the numbers on the y-axis*/
void si_unit(
image_desc_t *im /* image description */
)
{
double digits, viewdigits = 0;
digits =
floor(log(max(fabs(im->minval), fabs(im->maxval))) /
log((double) im->base));
if (im->unitsexponent != 9999) {
/* unitsexponent = 9, 6, 3, 0, -3, -6, -9, etc */
viewdigits = floor((double)(im->unitsexponent / 3));
} else {
viewdigits = digits;
}
im->magfact = pow((double) im->base, digits);
#ifdef DEBUG
printf("digits %6.3f im->magfact %6.3f\n", digits, im->magfact);
#endif
im->viewfactor = im->magfact / pow((double) im->base, viewdigits);
if (((viewdigits + si_symbcenter) < sizeof(si_symbol)) &&
((viewdigits + si_symbcenter) >= 0))
im->symbol = si_symbol[(int) viewdigits + si_symbcenter];
else
im->symbol = '?';
}
/* move min and max values around to become sensible */
void expand_range(
image_desc_t *im)
{
double sensiblevalues[] = { 1000.0, 900.0, 800.0, 750.0, 700.0,
600.0, 500.0, 400.0, 300.0, 250.0,
200.0, 125.0, 100.0, 90.0, 80.0,
75.0, 70.0, 60.0, 50.0, 40.0, 30.0,
25.0, 20.0, 10.0, 9.0, 8.0,
7.0, 6.0, 5.0, 4.0, 3.5, 3.0,
2.5, 2.0, 1.8, 1.5, 1.2, 1.0,
0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0, -1
};
double scaled_min, scaled_max;
double adj;
int i;
#ifdef DEBUG
printf("Min: %6.2f Max: %6.2f MagFactor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTAUTOSCALE) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher then max/min vals
so we can see amplitude on the graph */
double delt, fact;
delt = im->maxval - im->minval;
adj = delt * 0.1;
fact = 2.0 * pow(10.0,
floor(log10
(max(fabs(im->minval), fabs(im->maxval)) /
im->magfact)) - 2);
if (delt < fact) {
adj = (fact - delt) * 0.55;
#ifdef DEBUG
printf
("Min: %6.2f Max: %6.2f delt: %6.2f fact: %6.2f adj: %6.2f\n",
im->minval, im->maxval, delt, fact, adj);
#endif
}
im->minval -= adj;
im->maxval += adj;
} else if (im->extra_flags & ALTAUTOSCALE_MIN) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly lower than min vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->minval -= adj;
} else if (im->extra_flags & ALTAUTOSCALE_MAX) {
/* measure the amplitude of the function. Make sure that
graph boundaries are slightly higher than max vals
so we can see amplitude on the graph */
adj = (im->maxval - im->minval) * 0.1;
im->maxval += adj;
} else {
scaled_min = im->minval / im->magfact;
scaled_max = im->maxval / im->magfact;
for (i = 1; sensiblevalues[i] > 0; i++) {
if (sensiblevalues[i - 1] >= scaled_min &&
sensiblevalues[i] <= scaled_min)
im->minval = sensiblevalues[i] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_min &&
-sensiblevalues[i] >= scaled_min)
im->minval = -sensiblevalues[i - 1] * (im->magfact);
if (sensiblevalues[i - 1] >= scaled_max &&
sensiblevalues[i] <= scaled_max)
im->maxval = sensiblevalues[i - 1] * (im->magfact);
if (-sensiblevalues[i - 1] <= scaled_max &&
-sensiblevalues[i] >= scaled_max)
im->maxval = -sensiblevalues[i] * (im->magfact);
}
}
} else {
/* adjust min and max to the grid definition if there is one */
im->minval = (double) im->ylabfact * im->ygridstep *
floor(im->minval / ((double) im->ylabfact * im->ygridstep));
im->maxval = (double) im->ylabfact * im->ygridstep *
ceil(im->maxval / ((double) im->ylabfact * im->ygridstep));
}
#ifdef DEBUG
fprintf(stderr, "SCALED Min: %6.2f Max: %6.2f Factor: %6.2f\n",
im->minval, im->maxval, im->magfact);
#endif
}
void apply_gridfit(
image_desc_t *im)
{
if (isnan(im->minval) || isnan(im->maxval))
return;
ytr(im, DNAN);
if (im->logarithmic) {
double ya, yb, ypix, ypixfrac;
double log10_range = log10(im->maxval) - log10(im->minval);
ya = pow((double) 10, floor(log10(im->minval)));
while (ya < im->minval)
ya *= 10;
if (ya > im->maxval)
return; /* don't have y=10^x gridline */
yb = ya * 10;
if (yb <= im->maxval) {
/* we have at least 2 y=10^x gridlines.
Make sure distance between them in pixels
are an integer by expanding im->maxval */
double y_pixel_delta = ytr(im, ya) - ytr(im, yb);
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_log10_range = factor * log10_range;
double new_ymax_log10 = log10(im->minval) + new_log10_range;
im->maxval = pow(10, new_ymax_log10);
ytr(im, DNAN); /* reset precalc */
log10_range = log10(im->maxval) - log10(im->minval);
}
/* make sure first y=10^x gridline is located on
integer pixel position by moving scale slightly
downwards (sub-pixel movement) */
ypix = ytr(im, ya) + im->ysize; /* add im->ysize so it always is positive */
ypixfrac = ypix - floor(ypix);
if (ypixfrac > 0 && ypixfrac < 1) {
double yfrac = ypixfrac / im->ysize;
im->minval = pow(10, log10(im->minval) - yfrac * log10_range);
im->maxval = pow(10, log10(im->maxval) - yfrac * log10_range);
ytr(im, DNAN); /* reset precalc */
}
} else {
/* Make sure we have an integer pixel distance between
each minor gridline */
double ypos1 = ytr(im, im->minval);
double ypos2 = ytr(im, im->minval + im->ygrid_scale.gridstep);
double y_pixel_delta = ypos1 - ypos2;
double factor = y_pixel_delta / floor(y_pixel_delta);
double new_range = factor * (im->maxval - im->minval);
double gridstep = im->ygrid_scale.gridstep;
double minor_y, minor_y_px, minor_y_px_frac;
if (im->maxval > 0.0)
im->maxval = im->minval + new_range;
else
im->minval = im->maxval - new_range;
ytr(im, DNAN); /* reset precalc */
/* make sure first minor gridline is on integer pixel y coord */
minor_y = gridstep * floor(im->minval / gridstep);
while (minor_y < im->minval)
minor_y += gridstep;
minor_y_px = ytr(im, minor_y) + im->ysize; /* ensure > 0 by adding ysize */
minor_y_px_frac = minor_y_px - floor(minor_y_px);
if (minor_y_px_frac > 0 && minor_y_px_frac < 1) {
double yfrac = minor_y_px_frac / im->ysize;
double range = im->maxval - im->minval;
im->minval = im->minval - yfrac * range;
im->maxval = im->maxval - yfrac * range;
ytr(im, DNAN); /* reset precalc */
}
calc_horizontal_grid(im); /* recalc with changed im->maxval */
}
}
/* reduce data reimplementation by Alex */
void reduce_data(
enum cf_en cf, /* which consolidation function ? */
unsigned long cur_step, /* step the data currently is in */
time_t *start, /* start, end and step as requested ... */
time_t *end, /* ... by the application will be ... */
unsigned long *step, /* ... adjusted to represent reality */
unsigned long *ds_cnt, /* number of data sources in file */
rrd_value_t **data)
{ /* two dimensional array containing the data */
int i, reduce_factor = ceil((double) (*step) / (double) cur_step);
unsigned long col, dst_row, row_cnt, start_offset, end_offset, skiprows =
0;
rrd_value_t *srcptr, *dstptr;
(*step) = cur_step * reduce_factor; /* set new step size for reduced data */
dstptr = *data;
srcptr = *data;
row_cnt = ((*end) - (*start)) / cur_step;
#ifdef DEBUG
#define DEBUG_REDUCE
#endif
#ifdef DEBUG_REDUCE
printf("Reducing %lu rows with factor %i time %lu to %lu, step %lu\n",
row_cnt, reduce_factor, *start, *end, cur_step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * cur_step);
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
/* We have to combine [reduce_factor] rows of the source
** into one row for the destination. Doing this we also
** need to take care to combine the correct rows. First
** alter the start and end time so that they are multiples
** of the new step time. We cannot reduce the amount of
** time so we have to move the end towards the future and
** the start towards the past.
*/
end_offset = (*end) % (*step);
start_offset = (*start) % (*step);
/* If there is a start offset (which cannot be more than
** one destination row), skip the appropriate number of
** source rows and one destination row. The appropriate
** number is what we do know (start_offset/cur_step) of
** the new interval (*step/cur_step aka reduce_factor).
*/
#ifdef DEBUG_REDUCE
printf("start_offset: %lu end_offset: %lu\n", start_offset, end_offset);
printf("row_cnt before: %lu\n", row_cnt);
#endif
if (start_offset) {
(*start) = (*start) - start_offset;
skiprows = reduce_factor - start_offset / cur_step;
srcptr += skiprows * *ds_cnt;
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt between: %lu\n", row_cnt);
#endif
/* At the end we have some rows that are not going to be
** used, the amount is end_offset/cur_step
*/
if (end_offset) {
(*end) = (*end) - end_offset + (*step);
skiprows = end_offset / cur_step;
row_cnt -= skiprows;
}
#ifdef DEBUG_REDUCE
printf("row_cnt after: %lu\n", row_cnt);
#endif
/* Sanity check: row_cnt should be multiple of reduce_factor */
/* if this gets triggered, something is REALLY WRONG ... we die immediately */
if (row_cnt % reduce_factor) {
printf("SANITY CHECK: %lu rows cannot be reduced by %i \n",
row_cnt, reduce_factor);
printf("BUG in reduce_data()\n");
exit(1);
}
/* Now combine reduce_factor intervals at a time
** into one interval for the destination.
*/
for (dst_row = 0; (long int) row_cnt >= reduce_factor; dst_row++) {
for (col = 0; col < (*ds_cnt); col++) {
rrd_value_t newval = DNAN;
unsigned long validval = 0;
for (i = 0; i < reduce_factor; i++) {
if (isnan(srcptr[i * (*ds_cnt) + col])) {
continue;
}
validval++;
if (isnan(newval))
newval = srcptr[i * (*ds_cnt) + col];
else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval += srcptr[i * (*ds_cnt) + col];
break;
case CF_MINIMUM:
newval = min(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_FAILURES:
/* an interval contains a failure if any subintervals contained a failure */
case CF_MAXIMUM:
newval = max(newval, srcptr[i * (*ds_cnt) + col]);
break;
case CF_LAST:
newval = srcptr[i * (*ds_cnt) + col];
break;
}
}
}
if (validval == 0) {
newval = DNAN;
} else {
switch (cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVSEASONAL:
case CF_DEVPREDICT:
case CF_SEASONAL:
case CF_AVERAGE:
newval /= validval;
break;
case CF_MINIMUM:
case CF_FAILURES:
case CF_MAXIMUM:
case CF_LAST:
break;
}
}
*dstptr++ = newval;
}
srcptr += (*ds_cnt) * reduce_factor;
row_cnt -= reduce_factor;
}
/* If we had to alter the endtime, we didn't have enough
** source rows to fill the last row. Fill it with NaN.
*/
if (end_offset)
for (col = 0; col < (*ds_cnt); col++)
*dstptr++ = DNAN;
#ifdef DEBUG_REDUCE
row_cnt = ((*end) - (*start)) / *step;
srcptr = *data;
printf("Done reducing. Currently %lu rows, time %lu to %lu, step %lu\n",
row_cnt, *start, *end, *step);
for (col = 0; col < row_cnt; col++) {
printf("time %10lu: ", *start + (col + 1) * (*step));
for (i = 0; i < *ds_cnt; i++)
printf(" %8.2e", srcptr[*ds_cnt * col + i]);
printf("\n");
}
#endif
}
/* get the data required for the graphs from the
relevant rrds ... */
int data_fetch(
image_desc_t *im)
{
int i, ii;
/* pull the data from the rrd files ... */
for (i = 0; i < (int) im->gdes_c; i++) {
/* only GF_DEF elements fetch data */
if (im->gdes[i].gf != GF_DEF)
continue;
/* do we have it already ? */
gpointer value;
char *key = gdes_fetch_key(im->gdes[i]);
gboolean ok = g_hash_table_lookup_extended(im->rrd_map,key,NULL,&value);
free(key);
if (ok){
ii = GPOINTER_TO_INT(value);
im->gdes[i].start = im->gdes[ii].start;
im->gdes[i].end = im->gdes[ii].end;
im->gdes[i].step = im->gdes[ii].step;
im->gdes[i].ds_cnt = im->gdes[ii].ds_cnt;
im->gdes[i].ds_namv = im->gdes[ii].ds_namv;
im->gdes[i].data = im->gdes[ii].data;
im->gdes[i].data_first = 0;
} else {
unsigned long ft_step = im->gdes[i].step; /* ft_step will record what we got from fetch */
const char *rrd_daemon;
int status;
if (im->gdes[i].daemon[0] != 0)
rrd_daemon = im->gdes[i].daemon;
else
rrd_daemon = im->daemon_addr;
/* "daemon" may be NULL. ENV_RRDCACHED_ADDRESS is evaluated in that
* case. If "daemon" holds the same value as in the previous
* iteration, no actual new connection is established - the
* existing connection is re-used. */
rrdc_connect (rrd_daemon);
/* If connecting was successfull, use the daemon to query the data.
* If there is no connection, for example because no daemon address
* was specified, (try to) use the local file directly. */
if (rrdc_is_connected (rrd_daemon))
{
status = rrdc_fetch (im->gdes[i].rrd,
cf_to_string (im->gdes[i].cf),
&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
&im->gdes[i].ds_namv,
&im->gdes[i].data);
if (status != 0) {
if (im->extra_flags & ALLOW_MISSING_DS) {
rrd_clear_error();
if (rrd_fetch_empty(&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
im->gdes[i].ds_nam,
&im->gdes[i].ds_namv,
&im->gdes[i].data) == -1)
return -1;
} else return (status);
}
}
else
{
if ((rrd_fetch_fn(im->gdes[i].rrd,
im->gdes[i].cf,
&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
&im->gdes[i].ds_namv,
&im->gdes[i].data)) == -1) {
if (im->extra_flags & ALLOW_MISSING_DS) {
/* Unable to fetch data, assume fake data */
rrd_clear_error();
if (rrd_fetch_empty(&im->gdes[i].start,
&im->gdes[i].end,
&ft_step,
&im->gdes[i].ds_cnt,
im->gdes[i].ds_nam,
&im->gdes[i].ds_namv,
&im->gdes[i].data) == -1)
return -1;
} else return -1;
}
}
im->gdes[i].data_first = 1;
/* must reduce to at least im->step
otherwhise we end up with more data than we can handle in the
chart and visibility of data will be random */
im->gdes[i].step = max(im->gdes[i].step,im->step);
if (ft_step < im->gdes[i].step) {
reduce_data(im->gdes[i].cf_reduce_set ? im->gdes[i].cf_reduce : im->gdes[i].cf,
ft_step,
&im->gdes[i].start,
&im->gdes[i].end,
&im->gdes[i].step,
&im->gdes[i].ds_cnt, &im->gdes[i].data);
} else {
im->gdes[i].step = ft_step;
}
}
/* lets see if the required data source is really there */
for (ii = 0; ii < (int) im->gdes[i].ds_cnt; ii++) {
if (strcmp(im->gdes[i].ds_namv[ii], im->gdes[i].ds_nam) == 0) {
im->gdes[i].ds = ii;
}
}
if (im->gdes[i].ds == -1) {
rrd_set_error("No DS called '%s' in '%s'",
im->gdes[i].ds_nam, im->gdes[i].rrd);
return -1;
}
// remember that we already got this one
g_hash_table_insert(im->rrd_map,gdes_fetch_key(im->gdes[i]),GINT_TO_POINTER(i));
}
return 0;
}
/* evaluate the expressions in the CDEF functions */
/*************************************************************
* CDEF stuff
*************************************************************/
/* find the greatest common divisor for all the numbers
in the 0 terminated num array */
long lcd(
long *num)
{
long rest;
int i;
for (i = 0; num[i + 1] != 0; i++) {
do {
rest = num[i] % num[i + 1];
num[i] = num[i + 1];
num[i + 1] = rest;
} while (rest != 0);
num[i + 1] = num[i];
}
/* return i==0?num[i]:num[i-1]; */
return num[i];
}
/* run the rpn calculator on all the VDEF and CDEF arguments */
int data_calc(
image_desc_t *im)
{
int gdi;
int dataidx;
long *steparray, rpi;
int stepcnt;
time_t now;
rpnstack_t rpnstack;
rpnp_t *rpnp;
rpnstack_init(&rpnstack);
for (gdi = 0; gdi < im->gdes_c; gdi++) {
/* Look for GF_VDEF and GF_CDEF in the same loop,
* so CDEFs can use VDEFs and vice versa
*/
switch (im->gdes[gdi].gf) {
case GF_XPORT:
break;
case GF_SHIFT:{
graph_desc_t *vdp = &im->gdes[im->gdes[gdi].vidx];
/* remove current shift */
vdp->start -= vdp->shift;
vdp->end -= vdp->shift;
/* vdef */
if (im->gdes[gdi].shidx >= 0)
vdp->shift = im->gdes[im->gdes[gdi].shidx].vf.val;
/* constant */
else
vdp->shift = im->gdes[gdi].shval;
/* normalize shift to multiple of consolidated step */
vdp->shift = (vdp->shift / (long) vdp->step) * (long) vdp->step;
/* apply shift */
vdp->start += vdp->shift;
vdp->end += vdp->shift;
break;
}
case GF_VDEF:
/* A VDEF has no DS. This also signals other parts
* of rrdtool that this is a VDEF value, not a CDEF.
*/
im->gdes[gdi].ds_cnt = 0;
if (vdef_calc(im, gdi)) {
rrd_set_error("Error processing VDEF '%s'",
im->gdes[gdi].vname);
rpnstack_free(&rpnstack);
return -1;
}
break;
case GF_CDEF:
im->gdes[gdi].ds_cnt = 1;
im->gdes[gdi].ds = 0;
im->gdes[gdi].data_first = 1;
im->gdes[gdi].start = 0;
im->gdes[gdi].end = 0;
steparray = NULL;
stepcnt = 0;
dataidx = -1;
rpnp = im->gdes[gdi].rpnp;
/* Find the variables in the expression.
* - VDEF variables are substituted by their values
* and the opcode is changed into OP_NUMBER.
* - CDEF variables are analized for their step size,
* the lowest common denominator of all the step
* sizes of the data sources involved is calculated
* and the resulting number is the step size for the
* resulting data source.
*/
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
if (im->gdes[ptr].ds_cnt == 0) { /* this is a VDEF data source */
#if 0
printf
("DEBUG: inside CDEF '%s' processing VDEF '%s'\n",
im->gdes[gdi].vname, im->gdes[ptr].vname);
printf("DEBUG: value from vdef is %f\n",
im->gdes[ptr].vf.val);
#endif
im->gdes[gdi].rpnp[rpi].val = im->gdes[ptr].vf.val;
im->gdes[gdi].rpnp[rpi].op = OP_NUMBER;
} else { /* normal variables and PREF(variables) */
/* add one entry to the array that keeps track of the step sizes of the
* data sources going into the CDEF. */
if ((steparray =
(long*)rrd_realloc(steparray,
(++stepcnt +
1) * sizeof(*steparray))) == NULL) {
rrd_set_error("realloc steparray");
rpnstack_free(&rpnstack);
return -1;
};
steparray[stepcnt - 1] = im->gdes[ptr].step;
/* adjust start and end of cdef (gdi) so
* that it runs from the latest start point
* to the earliest endpoint of any of the
* rras involved (ptr)
*/
if (im->gdes[gdi].start < im->gdes[ptr].start)
im->gdes[gdi].start = im->gdes[ptr].start;
if (im->gdes[gdi].end == 0 ||
im->gdes[gdi].end > im->gdes[ptr].end)
im->gdes[gdi].end = im->gdes[ptr].end;
/* store pointer to the first element of
* the rra providing data for variable,
* further save step size and data source
* count of this rra
*/
im->gdes[gdi].rpnp[rpi].data =
im->gdes[ptr].data + im->gdes[ptr].ds;
im->gdes[gdi].rpnp[rpi].step = im->gdes[ptr].step;
im->gdes[gdi].rpnp[rpi].ds_cnt = im->gdes[ptr].ds_cnt;
/* backoff the *.data ptr; this is done so
* rpncalc() function doesn't have to treat
* the first case differently
*/
} /* if ds_cnt != 0 */
} /* if OP_VARIABLE */
} /* loop through all rpi */
/* move the data pointers to the correct period */
for (rpi = 0; im->gdes[gdi].rpnp[rpi].op != OP_END; rpi++) {
if (im->gdes[gdi].rpnp[rpi].op == OP_VARIABLE ||
im->gdes[gdi].rpnp[rpi].op == OP_PREV_OTHER) {
long ptr = im->gdes[gdi].rpnp[rpi].ptr;
long diff =
im->gdes[gdi].start - im->gdes[ptr].start;
if (diff > 0)
im->gdes[gdi].rpnp[rpi].data +=
(diff / im->gdes[ptr].step) *
im->gdes[ptr].ds_cnt;
}
}
if (steparray == NULL) {
rrd_set_error("rpn expressions without DEF"
" or CDEF variables are not supported");
rpnstack_free(&rpnstack);
return -1;
}
steparray[stepcnt] = 0;
/* Now find the resulting step. All steps in all
* used RRAs have to be visited
*/
im->gdes[gdi].step = lcd(steparray);
free(steparray);
if ((im->gdes[gdi].data = (rrd_value_t*)malloc(((im->gdes[gdi].end -
im->gdes[gdi].start)
/ im->gdes[gdi].step)
* sizeof(double))) == NULL) {
rrd_set_error("malloc im->gdes[gdi].data");
rpnstack_free(&rpnstack);
return -1;
}
/* Step through the new cdef results array and
* calculate the values
*/
for (now = im->gdes[gdi].start + im->gdes[gdi].step;
now <= im->gdes[gdi].end; now += im->gdes[gdi].step) {
/* 3rd arg of rpn_calc is for OP_VARIABLE lookups;
* in this case we are advancing by timesteps;
* we use the fact that time_t is a synonym for long
*/
if (rpn_calc(rpnp, &rpnstack, (long) now,
im->gdes[gdi].data, ++dataidx) == -1) {
/* rpn_calc sets the error string */
rpnstack_free(&rpnstack);
rpnp_freeextra(rpnp);
return -1;
}
} /* enumerate over time steps within a CDEF */
rpnp_freeextra(rpnp);
break;
default:
continue;
}
} /* enumerate over CDEFs */
rpnstack_free(&rpnstack);
return 0;
}
/* from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm */
/* yes we are loosing precision by doing tos with floats instead of doubles
but it seems more stable this way. */
static int AlmostEqual2sComplement(
float A,
float B,
int maxUlps)
{
int aInt = *(int *) &A;
int bInt = *(int *) &B;
int intDiff;
/* Make sure maxUlps is non-negative and small enough that the
default NAN won't compare as equal to anything. */
/* assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024); */
/* Make aInt lexicographically ordered as a twos-complement int */
if (aInt < 0)
aInt = 0x80000000l - aInt;
/* Make bInt lexicographically ordered as a twos-complement int */
if (bInt < 0)
bInt = 0x80000000l - bInt;
intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return 1;
return 0;
}
/* massage data so, that we get one value for each x coordinate in the graph */
int data_proc(
image_desc_t *im)
{
long i, ii;
double pixstep = (double) (im->end - im->start)
/ (double) im->xsize; /* how much time
passes in one pixel */
double paintval;
double minval = DNAN, maxval = DNAN;
unsigned long gr_time;
/* memory for the processed data */
for (i = 0; i < im->gdes_c; i++) {
if ((im->gdes[i].gf == GF_LINE)
|| (im->gdes[i].gf == GF_AREA)
|| (im->gdes[i].gf == GF_TICK)
|| (im->gdes[i].gf == GF_GRAD)
) {
if ((im->gdes[i].p_data = (rrd_value_t*)malloc((im->xsize + 1)
* sizeof(rrd_value_t))) == NULL) {
rrd_set_error("malloc data_proc");
return -1;
}
}
}
for (i = 0; i < im->xsize; i++) { /* for each pixel */
long vidx;
gr_time = im->start + pixstep * i; /* time of the current step */
paintval = 0.0;
for (ii = 0; ii < im->gdes_c; ii++) {
double value;
switch (im->gdes[ii].gf) {
case GF_LINE:
case GF_AREA:
case GF_GRAD:
case GF_TICK:
if (!im->gdes[ii].stack)
paintval = 0.0;
value = im->gdes[ii].yrule;
if (isnan(value) || (im->gdes[ii].gf == GF_TICK)) {
/* The time of the data doesn't necessarily match
** the time of the graph. Beware.
*/
vidx = im->gdes[ii].vidx;
if (im->gdes[vidx].gf == GF_VDEF) {
value = im->gdes[vidx].vf.val;
} else
if (((long int) gr_time >=
(long int) im->gdes[vidx].start)
&& ((long int) gr_time <
(long int) im->gdes[vidx].end)) {
value = im->gdes[vidx].data[(unsigned long)
floor((double)
(gr_time -
im->gdes[vidx].
start)
/
im->gdes[vidx].step)
* im->gdes[vidx].ds_cnt +
im->gdes[vidx].ds];
} else {
value = DNAN;
}
};
if (!isnan(value)) {
paintval += value;
im->gdes[ii].p_data[i] = paintval;
/* GF_TICK: the data values are not
** relevant for min and max
*/
if (finite(paintval) && im->gdes[ii].gf != GF_TICK && !im->gdes[ii].skipscale) {
if ((isnan(minval) || paintval < minval) &&
!(im->logarithmic && paintval <= 0.0))
minval = paintval;
if (isnan(maxval) || paintval > maxval)
maxval = paintval;
}
} else {
im->gdes[ii].p_data[i] = DNAN;
}
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
default:
break;
}
}
}
/* if min or max have not been asigned a value this is because
there was no data in the graph ... this is not good ...
lets set these to dummy values then ... */
if (im->logarithmic) {
if (isnan(minval) || isnan(maxval) || maxval <= 0) {
minval = 0.0; /* catching this right away below */
maxval = 5.1;
}
/* in logarithm mode, where minval is smaller or equal
to 0 make the beast just way smaller than maxval */
if (minval <= 0) {
minval = maxval / 10e8;
}
} else {
if (isnan(minval) || isnan(maxval)) {
minval = 0.0;
maxval = 1.0;
}
}
/* adjust min and max values given by the user */
/* for logscale we add something on top */
if (isnan(im->minval)
|| ((!im->rigid) && im->minval > minval)
) {
if (im->logarithmic)
im->minval = minval / 2.0;
else
im->minval = minval;
}
if (isnan(im->maxval)
|| (!im->rigid && im->maxval < maxval)
) {
if (im->logarithmic)
im->maxval = maxval * 2.0;
else
im->maxval = maxval;
}
/* make sure min is smaller than max */
if (im->minval > im->maxval) {
if (im->minval > 0)
im->minval = 0.99 * im->maxval;
else
im->minval = 1.01 * im->maxval;
}
/* make sure min and max are not equal */
if (AlmostEqual2sComplement(im->minval, im->maxval, 4)) {
if (im->maxval > 0)
im->maxval *= 1.01;
else
im->maxval *= 0.99;
/* make sure min and max are not both zero */
if (AlmostEqual2sComplement(im->maxval, 0, 4)) {
im->maxval = 1.0;
}
}
return 0;
}
static int find_first_weekday(void){
static int first_weekday = -1;
if (first_weekday == -1){
#ifdef HAVE__NL_TIME_WEEK_1STDAY
/* according to http://sourceware.org/ml/libc-locales/2009-q1/msg00011.html */
/* See correct way here http://pasky.or.cz/dev/glibc/first_weekday.c */
first_weekday = nl_langinfo (_NL_TIME_FIRST_WEEKDAY)[0];
int week_1stday;
long week_1stday_l = (long) nl_langinfo (_NL_TIME_WEEK_1STDAY);
if (week_1stday_l == 19971130) week_1stday = 0; /* Sun */
else if (week_1stday_l == 19971201) week_1stday = 1; /* Mon */
else
{
first_weekday = 1;
return first_weekday; /* we go for a monday default */
}
first_weekday=(week_1stday + first_weekday - 1) % 7;
#else
first_weekday = 1;
#endif
}
return first_weekday;
}
/* identify the point where the first gridline, label ... gets placed */
time_t find_first_time(
time_t start, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
localtime_r(&start, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
switch (baseint) {
case TMT_SECOND:
tm. tm_sec -= tm.tm_sec % basestep;
break;
case TMT_MINUTE:
tm. tm_sec = 0;
tm. tm_min -= tm.tm_min % basestep;
break;
case TMT_HOUR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour -= tm.tm_hour % basestep;
break;
case TMT_DAY:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
break;
case TMT_WEEK:
/* we do NOT look at the basestep for this ... */
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday -= tm.tm_wday - find_first_weekday();
if (tm.tm_wday == 0 && find_first_weekday() > 0)
tm. tm_mday -= 7; /* we want the *previous* week */
break;
case TMT_MONTH:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon -= tm.tm_mon % basestep;
break;
case TMT_YEAR:
tm. tm_sec = 0;
tm. tm_min = 0;
tm. tm_hour = 0;
tm. tm_mday = 1;
tm. tm_mon = 0;
tm. tm_year -= (
tm.tm_year + 1900) %basestep;
}
return mktime(&tm);
}
/* identify the point where the next gridline, label ... gets placed */
time_t find_next_time(
time_t current, /* what is the initial time */
enum tmt_en baseint, /* what is the basic interval */
long basestep /* how many if these do we jump a time */
)
{
struct tm tm;
time_t madetime;
localtime_r(¤t, &tm);
/* let mktime figure this dst on its own */
tm.tm_isdst = -1;
int limit = 2;
switch (baseint) {
case TMT_SECOND: limit = 7200; break;
case TMT_MINUTE: limit = 120; break;
case TMT_HOUR: limit = 2; break;
default: limit = 2; break;
}
do {
switch (baseint) {
case TMT_SECOND:
tm. tm_sec += basestep;
break;
case TMT_MINUTE:
tm. tm_min += basestep;
break;
case TMT_HOUR:
tm. tm_hour += basestep;
break;
case TMT_DAY:
tm. tm_mday += basestep;
break;
case TMT_WEEK:
tm. tm_mday += 7 * basestep;
break;
case TMT_MONTH:
tm. tm_mon += basestep;
break;
case TMT_YEAR:
tm. tm_year += basestep;
}
madetime = mktime(&tm);
} while (madetime == -1 && limit-- >= 0); /* this is necessary to skip impossible times
like the daylight saving time skips */
return madetime;
}
/* calculate values required for PRINT and GPRINT functions */
int print_calc(
image_desc_t *im)
{
long i, ii, validsteps;
double printval;
struct tm tmvdef;
int graphelement = 0;
long vidx;
int max_ii;
double magfact = -1;
char *si_symb = "";
char *percent_s;
int prline_cnt = 0;
/* wow initializing tmvdef is quite a task :-) */
time_t now = time(NULL);
localtime_r(&now, &tmvdef);
for (i = 0; i < im->gdes_c; i++) {
vidx = im->gdes[i].vidx;
switch (im->gdes[i].gf) {
case GF_PRINT:
case GF_GPRINT:
/* PRINT and GPRINT can now print VDEF generated values.
* There's no need to do any calculations on them as these
* calculations were already made.
*/
if (im->gdes[vidx].gf == GF_VDEF) { /* simply use vals */
printval = im->gdes[vidx].vf.val;
localtime_r(&im->gdes[vidx].vf.when, &tmvdef);
} else { /* need to calculate max,min,avg etcetera */
max_ii = ((im->gdes[vidx].end - im->gdes[vidx].start)
/ im->gdes[vidx].step * im->gdes[vidx].ds_cnt);
printval = DNAN;
validsteps = 0;
for (ii = im->gdes[vidx].ds;
ii < max_ii; ii += im->gdes[vidx].ds_cnt) {
if (!finite(im->gdes[vidx].data[ii]))
continue;
if (isnan(printval)) {
printval = im->gdes[vidx].data[ii];
validsteps++;
continue;
}
switch (im->gdes[i].cf) {
case CF_HWPREDICT:
case CF_MHWPREDICT:
case CF_DEVPREDICT:
case CF_DEVSEASONAL:
case CF_SEASONAL:
case CF_AVERAGE:
validsteps++;
printval += im->gdes[vidx].data[ii];
break;
case CF_MINIMUM:
printval = min(printval, im->gdes[vidx].data[ii]);
break;
case CF_FAILURES:
case CF_MAXIMUM:
printval = max(printval, im->gdes[vidx].data[ii]);
break;
case CF_LAST:
printval = im->gdes[vidx].data[ii];
}
}
if (im->gdes[i].cf == CF_AVERAGE || im->gdes[i].cf > CF_LAST) {
if (validsteps > 1) {
printval = (printval / validsteps);
}
}
} /* prepare printval */
if (!im->gdes[i].strftm && (percent_s = strstr(im->gdes[i].format, "%S")) != NULL) {
/* Magfact is set to -1 upon entry to print_calc. If it
* is still less than 0, then we need to run auto_scale.
* Otherwise, put the value into the correct units. If
* the value is 0, then do not set the symbol or magnification
* so next the calculation will be performed again. */
if (magfact < 0.0) {
auto_scale(im, &printval, &si_symb, &magfact);
if (printval == 0.0)
magfact = -1.0;
} else {
printval /= magfact;
}
*(++percent_s) = 's';
} else if (!im->gdes[i].strftm && strstr(im->gdes[i].format, "%s") != NULL) {
auto_scale(im, &printval, &si_symb, &magfact);
}
if (im->gdes[i].gf == GF_PRINT) {
rrd_infoval_t prline;
if (im->gdes[i].strftm) {
prline.u_str = (char*)malloc((FMT_LEG_LEN + 2) * sizeof(char));
if (im->gdes[vidx].vf.never == 1) {
time_clean(prline.u_str, im->gdes[i].format);
} else {
strftime(prline.u_str,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
}
} else if (bad_format(im->gdes[i].format)) {
rrd_set_error
("bad format for PRINT in '%s'", im->gdes[i].format);
return -1;
} else {
prline.u_str =
sprintf_alloc(im->gdes[i].format, printval, si_symb);
}
grinfo_push(im,
sprintf_alloc
("print[%ld]", prline_cnt++), RD_I_STR, prline);
free(prline.u_str);
} else {
/* GF_GPRINT */
if (im->gdes[i].strftm) {
if (im->gdes[vidx].vf.never == 1) {
time_clean(im->gdes[i].legend, im->gdes[i].format);
} else {
strftime(im->gdes[i].legend,
FMT_LEG_LEN, im->gdes[i].format, &tmvdef);
}
} else {
if (bad_format(im->gdes[i].format)) {
rrd_set_error
("bad format for GPRINT in '%s'",
im->gdes[i].format);
return -1;
}
snprintf(im->gdes[i].legend,
FMT_LEG_LEN - 2,
im->gdes[i].format, printval, si_symb);
}
graphelement = 1;
}
break;
case GF_LINE:
case GF_AREA:
case GF_GRAD:
case GF_TICK:
graphelement = 1;
break;
case GF_HRULE:
if (isnan(im->gdes[i].yrule)) { /* we must set this here or the legend printer can not decide to print the legend */
im->gdes[i].yrule = im->gdes[vidx].vf.val;
};
graphelement = 1;
break;
case GF_VRULE:
if (im->gdes[i].xrule == 0) { /* again ... the legend printer needs it */
im->gdes[i].xrule = im->gdes[vidx].vf.when;
};
graphelement = 1;
break;
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_DEF:
case GF_CDEF:
case GF_VDEF:
#ifdef WITH_PIECHART
case GF_PART:
#endif
case GF_SHIFT:
case GF_XPORT:
break;
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
case GF_XAXIS:
case GF_YAXIS:
break;
}
}
return graphelement;
}
/* place legends with color spots */
int leg_place(
image_desc_t *im,
int calc_width)
{
/* graph labels */
int interleg = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int border = im->text_prop[TEXT_PROP_LEGEND].size * 2.0;
int fill = 0, fill_last;
double legendwidth; // = im->ximg - 2 * border;
int leg_c = 0;
double leg_x = border;
int leg_y = 0; //im->yimg;
int leg_cc;
double glue = 0;
int i, ii, mark = 0;
char default_txtalign = TXA_JUSTIFIED; /*default line orientation */
int *legspace;
char *tab;
char saved_legend[FMT_LEG_LEN + 5];
if(calc_width){
legendwidth = 0;
}
else{
legendwidth = im->legendwidth - 2 * border;
}
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
if ((legspace = (int*)malloc(im->gdes_c * sizeof(int))) == NULL) {
rrd_set_error("malloc for legspace");
return -1;
}
for (i = 0; i < im->gdes_c; i++) {
char prt_fctn; /*special printfunctions */
if(calc_width){
strncpy(saved_legend, im->gdes[i].legend, sizeof saved_legend);
}
fill_last = fill;
/* hide legends for rules which are not displayed */
if (im->gdes[i].gf == GF_TEXTALIGN) {
default_txtalign = im->gdes[i].txtalign;
}
if (!(im->extra_flags & FORCE_RULES_LEGEND)) {
if (im->gdes[i].gf == GF_HRULE
&& (im->gdes[i].yrule <
im->minval || im->gdes[i].yrule > im->maxval))
im->gdes[i].legend[0] = '\0';
if (im->gdes[i].gf == GF_VRULE
&& (im->gdes[i].xrule <
im->start || im->gdes[i].xrule > im->end))
im->gdes[i].legend[0] = '\0';
}
/* turn \\t into tab */
while ((tab = strstr(im->gdes[i].legend, "\\t"))) {
memmove(tab, tab + 1, strlen(tab));
tab[0] = (char) 9;
}
leg_cc = strlen(im->gdes[i].legend);
/* is there a controle code at the end of the legend string ? */
if (leg_cc >= 2 && im->gdes[i].legend[leg_cc - 2] == '\\') {
prt_fctn = im->gdes[i].legend[leg_cc - 1];
leg_cc -= 2;
im->gdes[i].legend[leg_cc] = '\0';
} else {
prt_fctn = '\0';
}
/* only valid control codes */
if (prt_fctn != 'l' && prt_fctn != 'n' && /* a synonym for l */
prt_fctn != 'r' &&
prt_fctn != 'j' &&
prt_fctn != 'c' &&
prt_fctn != 'u' &&
prt_fctn != '.' &&
prt_fctn != 's' && prt_fctn != '\0' && prt_fctn != 'g') {
free(legspace);
rrd_set_error
("Unknown control code at the end of '%s\\%c'",
im->gdes[i].legend, prt_fctn);
return -1;
}
/* \n -> \l */
if (prt_fctn == 'n') {
prt_fctn = 'l';
}
/* \. is a null operation to allow strings ending in \x */
if (prt_fctn == '.') {
prt_fctn = '\0';
}
/* remove exess space from the end of the legend for \g */
while (prt_fctn == 'g' &&
leg_cc > 0 && im->gdes[i].legend[leg_cc - 1] == ' ') {
leg_cc--;
im->gdes[i].legend[leg_cc] = '\0';
}
if (leg_cc != 0) {
/* no interleg space if string ends in \g */
legspace[i] = (prt_fctn == 'g' ? 0 : interleg);
if (fill > 0) {
fill += legspace[i];
}
fill +=
gfx_get_text_width(im,
fill + border,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[i].legend);
leg_c++;
} else {
legspace[i] = 0;
}
/* who said there was a special tag ... ? */
if (prt_fctn == 'g') {
prt_fctn = '\0';
}
if (prt_fctn == '\0') {
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
if (i == im->gdes_c - 1 || fill > legendwidth) {
/* just one legend item is left right or center */
switch (default_txtalign) {
case TXA_RIGHT:
prt_fctn = 'r';
break;
case TXA_CENTER:
prt_fctn = 'c';
break;
case TXA_JUSTIFIED:
prt_fctn = 'j';
break;
default:
prt_fctn = 'l';
break;
}
}
/* is it time to place the legends ? */
if (fill > legendwidth) {
if (leg_c > 1) {
/* go back one */
i--;
fill = fill_last;
leg_c--;
}
}
if (leg_c == 1 && prt_fctn == 'j') {
prt_fctn = 'l';
}
}
if (prt_fctn != '\0') {
leg_x = border;
if (leg_c >= 2 && prt_fctn == 'j') {
glue = (double)(legendwidth - fill) / (double)(leg_c - 1);
} else {
glue = 0;
}
if (prt_fctn == 'c')
leg_x = border + (double)(legendwidth - fill) / 2.0;
if (prt_fctn == 'r')
leg_x = legendwidth - fill + border;
for (ii = mark; ii <= i; ii++) {
if (im->gdes[ii].legend[0] == '\0')
continue; /* skip empty legends */
im->gdes[ii].leg_x = leg_x;
im->gdes[ii].leg_y = leg_y + border;
leg_x +=
(double)gfx_get_text_width(im, leg_x,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, im->gdes[ii].legend)
+(double)legspace[ii]
+ glue;
}
if (leg_x > border || prt_fctn == 's')
leg_y += im->text_prop[TEXT_PROP_LEGEND].size * 1.8;
if (prt_fctn == 's')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size;
if (prt_fctn == 'u')
leg_y -= im->text_prop[TEXT_PROP_LEGEND].size *1.8;
if(calc_width && (fill > legendwidth)){
legendwidth = fill;
}
fill = 0;
leg_c = 0;
mark = ii;
}
if(calc_width){
strncpy(im->gdes[i].legend, saved_legend, sizeof im->gdes[0].legend);
}
}
if(calc_width){
im->legendwidth = legendwidth + 2 * border;
}
else{
im->legendheight = leg_y + border * 0.6;
}
free(legspace);
}
return 0;
}
/* create a grid on the graph. it determines what to do
from the values of xsize, start and end */
/* the xaxis labels are determined from the number of seconds per pixel
in the requested graph */
int calc_horizontal_grid(
image_desc_t
*im)
{
double range;
double scaledrange;
int pixel, i;
int gridind = 0;
int decimals, fractionals;
im->ygrid_scale.labfact = 2;
range = im->maxval - im->minval;
scaledrange = range / im->magfact;
/* does the scale of this graph make it impossible to put lines
on it? If so, give up. */
if (isnan(scaledrange)) {
return 0;
}
/* find grid spaceing */
pixel = 1;
if (isnan(im->ygridstep)) {
if (im->extra_flags & ALTYGRID) {
/* find the value with max number of digits. Get number of digits */
decimals =
ceil(log10
(max(fabs(im->maxval), fabs(im->minval)) *
im->viewfactor / im->magfact));
if (decimals <= 0) /* everything is small. make place for zero */
decimals = 1;
im->ygrid_scale.gridstep =
pow((double) 10,
floor(log10(range * im->viewfactor / im->magfact))) /
im->viewfactor * im->magfact;
if (im->ygrid_scale.gridstep == 0) /* range is one -> 0.1 is reasonable scale */
im->ygrid_scale.gridstep = 0.1;
/* should have at least 5 lines but no more then 15 */
if (range / im->ygrid_scale.gridstep < 5
&& im->ygrid_scale.gridstep >= 30)
im->ygrid_scale.gridstep /= 10;
if (range / im->ygrid_scale.gridstep > 15)
im->ygrid_scale.gridstep *= 10;
if (range / im->ygrid_scale.gridstep > 5) {
im->ygrid_scale.labfact = 1;
if (range / im->ygrid_scale.gridstep > 8
|| im->ygrid_scale.gridstep <
1.8 * im->text_prop[TEXT_PROP_AXIS].size)
im->ygrid_scale.labfact = 2;
} else {
im->ygrid_scale.gridstep /= 5;
im->ygrid_scale.labfact = 5;
}
fractionals =
floor(log10
(im->ygrid_scale.gridstep *
(double) im->ygrid_scale.labfact * im->viewfactor /
im->magfact));
if (fractionals < 0) { /* small amplitude. */
int len = decimals - fractionals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
snprintf(im->ygrid_scale.labfmt, sizeof im->ygrid_scale.labfmt,
"%%%d.%df%s", len,
-fractionals, (im->symbol != ' ' ? " %c" : ""));
} else {
int len = decimals + 1;
if (im->unitslength < len + 2)
im->unitslength = len + 2;
snprintf(im->ygrid_scale.labfmt, sizeof im->ygrid_scale.labfmt,
"%%%d.0f%s", len, (im->symbol != ' ' ? " %c" : ""));
}
} else { /* classic rrd grid */
for (i = 0; ylab[i].grid > 0; i++) {
pixel = im->ysize / (scaledrange / ylab[i].grid);
gridind = i;
if (pixel >= 5)
break;
}
for (i = 0; i < 4; i++) {
if (pixel * ylab[gridind].lfac[i] >=
1.8 * im->text_prop[TEXT_PROP_AXIS].size) {
im->ygrid_scale.labfact = ylab[gridind].lfac[i];
break;
}
}
im->ygrid_scale.gridstep = ylab[gridind].grid * im->magfact;
}
} else {
im->ygrid_scale.gridstep = im->ygridstep;
im->ygrid_scale.labfact = im->ylabfact;
}
return 1;
}
int draw_horizontal_grid(
image_desc_t
*im)
{
int i;
double scaledstep;
char graph_label[100];
int nlabels = 0;
double X0 = im->xorigin;
double X1 = im->xorigin + im->xsize;
int sgrid = (int) (im->minval / im->ygrid_scale.gridstep - 1);
int egrid = (int) (im->maxval / im->ygrid_scale.gridstep + 1);
double MaxY;
double second_axis_magfact = 0;
char *second_axis_symb = "";
scaledstep =
im->ygrid_scale.gridstep /
(double) im->magfact * (double) im->viewfactor;
MaxY = scaledstep * (double) egrid;
for (i = sgrid; i <= egrid; i++) {
double Y0 = ytr(im,
im->ygrid_scale.gridstep * i);
double YN = ytr(im,
im->ygrid_scale.gridstep * (i + 1));
if (floor(Y0 + 0.5) >=
im->yorigin - im->ysize && floor(Y0 + 0.5) <= im->yorigin) {
/* Make sure at least 2 grid labels are shown, even if it doesn't agree
with the chosen settings. Add a label if required by settings, or if
there is only one label so far and the next grid line is out of bounds. */
if (i % im->ygrid_scale.labfact == 0
|| (nlabels == 1
&& (YN < im->yorigin - im->ysize || YN > im->yorigin))) {
if (im->symbol == ' ') {
if (im->primary_axis_format == NULL || im->primary_axis_format[0] == '\0') {
if (im->extra_flags & ALTYGRID) {
snprintf(graph_label, sizeof graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i);
} else {
if (MaxY < 10) {
snprintf(graph_label, sizeof graph_label, "%4.1f",
scaledstep * (double) i);
} else {
snprintf(graph_label, sizeof graph_label,"%4.0f",
scaledstep * (double) i);
}
}
} else {
snprintf(graph_label, sizeof graph_label, im->primary_axis_format,
scaledstep * (double) i);
}
} else {
char sisym = (i == 0 ? ' ' : im->symbol);
if (im->primary_axis_format == NULL || im->primary_axis_format[0] == '\0') {
if (im->extra_flags & ALTYGRID) {
snprintf(graph_label,sizeof graph_label,
im->ygrid_scale.labfmt,
scaledstep * (double) i, sisym);
} else {
if (MaxY < 10) {
snprintf(graph_label, sizeof graph_label,"%4.1f %c",
scaledstep * (double) i, sisym);
} else {
snprintf(graph_label, sizeof graph_label, "%4.0f %c",
scaledstep * (double) i, sisym);
}
}
} else {
sprintf(graph_label, im->primary_axis_format,
scaledstep * (double) i, sisym);
}
}
nlabels++;
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = im->ygrid_scale.gridstep*(double)i*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format == NULL || im->second_axis_format[0] == '\0') {
if (!second_axis_magfact){
double dummy = im->ygrid_scale.gridstep*(double)(sgrid+egrid)/2.0*im->second_axis_scale+im->second_axis_shift;
auto_scale(im,&dummy,&second_axis_symb,&second_axis_magfact);
}
sval /= second_axis_magfact;
if(MaxY < 10) {
snprintf(graph_label_right, sizeof graph_label_right, "%5.1f %s",sval,second_axis_symb);
} else {
snprintf(graph_label_right, sizeof graph_label_right, "%5.0f %s",sval,second_axis_symb);
}
}
else {
snprintf(graph_label_right, sizeof graph_label_right, im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
gfx_line(im, X0 - 2, Y0, X0, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID],
im->grid_dash_on, im->grid_dash_off);
} else if (!(im->extra_flags & NOMINOR)) {
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
}
return 1;
}
/* this is frexp for base 10 */
double frexp10(
double,
double *);
double frexp10(
double x,
double *e)
{
double mnt;
int iexp;
iexp = floor(log((double)fabs(x)) / log((double)10));
mnt = x / pow(10.0, iexp);
if (mnt >= 10.0) {
iexp++;
mnt = x / pow(10.0, iexp);
}
*e = iexp;
return mnt;
}
/* logaritmic horizontal grid */
int horizontal_log_grid(
image_desc_t
*im)
{
double yloglab[][10] = {
{
1.0, 10., 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 5.0, 10., 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 5.0, 7.0, 10., 0.0, 0.0,
0.0, 0.0, 0.0}, {
1.0, 2.0, 4.0,
6.0, 8.0, 10.,
0.0,
0.0, 0.0, 0.0}, {
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0} /* last line */
};
int i, j, val_exp, min_exp;
double nex; /* number of decades in data */
double logscale; /* scale in logarithmic space */
int exfrac = 1; /* decade spacing */
int mid = -1; /* row in yloglab for major grid */
double mspac; /* smallest major grid spacing (pixels) */
int flab; /* first value in yloglab to use */
double value, tmp, pre_value;
double X0, X1, Y0;
char graph_label[100];
nex = log10(im->maxval / im->minval);
logscale = im->ysize / nex;
/* major spacing for data with high dynamic range */
while (logscale * exfrac < 3 * im->text_prop[TEXT_PROP_LEGEND].size) {
if (exfrac == 1)
exfrac = 3;
else
exfrac += 3;
}
/* major spacing for less dynamic data */
do {
/* search best row in yloglab */
mid++;
for (i = 0; yloglab[mid][i + 1] < 10.0; i++);
mspac = logscale * log10(10.0 / yloglab[mid][i]);
}
while (mspac >
2 * im->text_prop[TEXT_PROP_LEGEND].size && yloglab[mid][0] > 0);
if (mid)
mid--;
/* find first value in yloglab */
for (flab = 0;
yloglab[mid][flab] < 10
&& frexp10(im->minval, &tmp) > yloglab[mid][flab]; flab++);
if (yloglab[mid][flab] == 10.0) {
tmp += 1.0;
flab = 0;
}
val_exp = tmp;
if (val_exp % exfrac)
val_exp += abs(-val_exp % exfrac);
X0 = im->xorigin;
X1 = im->xorigin + im->xsize;
/* draw grid */
pre_value = DNAN;
while (1) {
value = yloglab[mid][flab] * pow(10.0, val_exp);
if (AlmostEqual2sComplement(value, pre_value, 4))
break; /* it seems we are not converging */
pre_value = value;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* major grid line */
gfx_line(im,
X0 - 2, Y0, X0, Y0, MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0 - 2, Y0,
X1 + 2, Y0,
MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
/* label */
if (im->extra_flags & FORCE_UNITS_SI) {
int scale;
double pvalue;
char symbol;
scale = floor(val_exp / 3.0);
if (value >= 1.0)
pvalue = pow(10.0, val_exp % 3);
else
pvalue = pow(10.0, ((val_exp + 1) % 3) + 2);
pvalue *= yloglab[mid][flab];
if (((scale + si_symbcenter) < (int) sizeof(si_symbol))
&& ((scale + si_symbcenter) >= 0))
symbol = si_symbol[scale + si_symbcenter];
else
symbol = '?';
snprintf(graph_label, sizeof graph_label, "%3.0f %c", pvalue, symbol);
} else {
snprintf(graph_label, sizeof graph_label, "%3.0e", value);
}
if (im->second_axis_scale != 0){
char graph_label_right[100];
double sval = value*im->second_axis_scale+im->second_axis_shift;
if (im->second_axis_format == NULL || im->second_axis_format[0] == '\0') {
if (im->extra_flags & FORCE_UNITS_SI) {
double mfac = 1;
char *symb = "";
auto_scale(im,&sval,&symb,&mfac);
snprintf(graph_label_right, sizeof graph_label_right, "%4.0f %s", sval,symb);
}
else {
snprintf(graph_label_right, sizeof graph_label_right, "%3.0e", sval);
}
}
else {
snprintf(graph_label_right, sizeof graph_label_right, im->second_axis_format,sval,"");
}
gfx_text ( im,
X1+7, Y0,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth,0.0, GFX_H_LEFT, GFX_V_CENTER,
graph_label_right );
}
gfx_text(im,
X0 -
im->
text_prop[TEXT_PROP_AXIS].
size, Y0,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_RIGHT, GFX_V_CENTER, graph_label);
/* minor grid */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line behind current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
} else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0,
X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* next decade */
if (yloglab[mid][++flab] == 10.0) {
flab = 0;
val_exp += exfrac;
}
}
/* draw minor lines after highest major line */
if (mid < 4 && exfrac == 1) {
/* find first and last minor line below current major line
* i is the first line and j tha last */
if (flab == 0) {
min_exp = val_exp - 1;
for (i = 1; yloglab[mid][i] < 10.0; i++);
i = yloglab[mid][i - 1] + 1;
j = 10;
} else {
min_exp = val_exp;
i = yloglab[mid][flab - 1] + 1;
j = yloglab[mid][flab];
}
/* draw minor lines below current major line */
for (; i < j; i++) {
value = i * pow(10.0, min_exp);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* fancy minor gridlines */
else if (exfrac > 1) {
for (i = val_exp - exfrac / 3 * 2; i < val_exp; i += exfrac / 3) {
value = pow(10.0, i);
if (value < im->minval)
continue;
Y0 = ytr(im, value);
if (floor(Y0 + 0.5) <= im->yorigin - im->ysize)
break;
/* draw lines */
gfx_line(im,
X0 - 2, Y0, X0, Y0, GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X1, Y0, X1 + 2, Y0,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0 - 1, Y0,
X1 + 1, Y0,
GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
return 1;
}
void vertical_grid(
image_desc_t *im)
{
int xlab_sel; /* which sort of label and grid ? */
time_t ti, tilab, timajor;
long factor;
char graph_label[100];
double X0, Y0, Y1; /* points for filled graph and more */
struct tm tm;
/* the type of time grid is determined by finding
the number of seconds per pixel in the graph */
if (im->xlab_user.minsec == -1) {
factor = (im->end - im->start) / im->xsize;
xlab_sel = 0;
while (xlab[xlab_sel + 1].minsec !=
-1 && xlab[xlab_sel + 1].minsec <= factor) {
xlab_sel++;
} /* pick the last one */
while (xlab[xlab_sel - 1].minsec ==
xlab[xlab_sel].minsec
&& xlab[xlab_sel].length > (im->end - im->start)) {
xlab_sel--;
} /* go back to the smallest size */
im->xlab_user.gridtm = xlab[xlab_sel].gridtm;
im->xlab_user.gridst = xlab[xlab_sel].gridst;
im->xlab_user.mgridtm = xlab[xlab_sel].mgridtm;
im->xlab_user.mgridst = xlab[xlab_sel].mgridst;
im->xlab_user.labtm = xlab[xlab_sel].labtm;
im->xlab_user.labst = xlab[xlab_sel].labst;
im->xlab_user.precis = xlab[xlab_sel].precis;
im->xlab_user.stst = xlab[xlab_sel].stst;
}
/* y coords are the same for every line ... */
Y0 = im->yorigin;
Y1 = im->yorigin - im->ysize;
/* paint the minor grid */
if (!(im->extra_flags & NOMINOR)) {
for (ti = find_first_time(im->start,
im->
xlab_user.
gridtm,
im->
xlab_user.
gridst),
timajor =
find_first_time(im->start,
im->xlab_user.
mgridtm,
im->xlab_user.
mgridst);
ti < im->end && ti != -1;
ti =
find_next_time(ti, im->xlab_user.gridtm, im->xlab_user.gridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
while (timajor < ti && timajor != -1) {
timajor = find_next_time(timajor,
im->
xlab_user.
mgridtm, im->xlab_user.mgridst);
}
if (timajor == -1) break; /* fail in case of problems with time increments */
if (ti == timajor)
continue; /* skip as falls on major grid line */
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_line(im, X0, Y0, X0, Y0 + 2,
GRIDWIDTH, im->graph_col[GRC_GRID]);
gfx_dashed_line(im, X0, Y0 + 1, X0,
Y1 - 1, GRIDWIDTH,
im->
graph_col[GRC_GRID],
im->grid_dash_on, im->grid_dash_off);
}
}
/* paint the major grid */
for (ti = find_first_time(im->start,
im->
xlab_user.
mgridtm,
im->
xlab_user.
mgridst);
ti < im->end && ti != -1;
ti = find_next_time(ti, im->xlab_user.mgridtm, im->xlab_user.mgridst)
) {
/* are we inside the graph ? */
if (ti < im->start || ti > im->end)
continue;
X0 = xtr(im, ti);
gfx_line(im, X0, Y1 - 2, X0, Y1,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_line(im, X0, Y0, X0, Y0 + 3,
MGRIDWIDTH, im->graph_col[GRC_MGRID]);
gfx_dashed_line(im, X0, Y0 + 3, X0,
Y1 - 2, MGRIDWIDTH,
im->
graph_col
[GRC_MGRID], im->grid_dash_on, im->grid_dash_off);
}
/* paint the labels below the graph */
for (ti =
find_first_time(im->start -
im->xlab_user.
precis / 2,
im->xlab_user.
labtm,
im->xlab_user.
labst);
(ti <=
im->end -
im->xlab_user.precis / 2) && ti != -1;
ti = find_next_time(ti, im->xlab_user.labtm, im->xlab_user.labst)
) {
tilab = ti + im->xlab_user.precis / 2; /* correct time for the label */
/* are we inside the graph ? */
if (tilab < im->start || tilab > im->end)
continue;
#if HAVE_STRFTIME
localtime_r(&tilab, &tm);
strftime(graph_label, 99, im->xlab_user.stst, &tm);
#else
# error "your libc has no strftime I guess we'll abort the exercise here."
#endif
gfx_text(im,
xtr(im, tilab),
Y0 + 3,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_TOP, graph_label);
}
}
void axis_paint(
image_desc_t *im)
{
/* draw x and y axis */
/* gfx_line ( im->canvas, im->xorigin+im->xsize,im->yorigin,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line ( im->canvas, im->xorigin,im->yorigin-im->ysize,
im->xorigin+im->xsize,im->yorigin-im->ysize,
GRIDWIDTH, im->graph_col[GRC_AXIS]); */
gfx_line(im, im->xorigin - 4,
im->yorigin,
im->xorigin + im->xsize +
4, im->yorigin, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_line(im, im->xorigin,
im->yorigin + 4,
im->xorigin,
im->yorigin - im->ysize -
4, MGRIDWIDTH, im->graph_col[GRC_AXIS]);
/* arrow for X and Y axis direction */
gfx_new_area(im, im->xorigin + im->xsize + 2, im->yorigin - 3, im->xorigin + im->xsize + 2, im->yorigin + 3, im->xorigin + im->xsize + 7, im->yorigin, /* horyzontal */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
gfx_new_area(im, im->xorigin - 3, im->yorigin - im->ysize - 2, im->xorigin + 3, im->yorigin - im->ysize - 2, im->xorigin, im->yorigin - im->ysize - 7, /* vertical */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
if (im->second_axis_scale != 0){
gfx_line ( im, im->xorigin+im->xsize,im->yorigin+4,
im->xorigin+im->xsize,im->yorigin-im->ysize-4,
MGRIDWIDTH, im->graph_col[GRC_AXIS]);
gfx_new_area ( im,
im->xorigin+im->xsize-2, im->yorigin-im->ysize-2,
im->xorigin+im->xsize+3, im->yorigin-im->ysize-2,
im->xorigin+im->xsize, im->yorigin-im->ysize-7, /* LINEOFFSET */
im->graph_col[GRC_ARROW]);
gfx_close_path(im);
}
}
void grid_paint(
image_desc_t *im)
{
long i;
int res = 0;
double X0, Y0; /* points for filled graph and more */
struct gfx_color_t water_color;
if (im->draw_3d_border > 0) {
/* draw 3d border */
i = im->draw_3d_border;
gfx_new_area(im, 0, im->yimg,
i, im->yimg - i, i, i, im->graph_col[GRC_SHADEA]);
gfx_add_point(im, im->ximg - i, i);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, 0, 0);
gfx_close_path(im);
gfx_new_area(im, i, im->yimg - i,
im->ximg - i,
im->yimg - i, im->ximg - i, i, im->graph_col[GRC_SHADEB]);
gfx_add_point(im, im->ximg, 0);
gfx_add_point(im, im->ximg, im->yimg);
gfx_add_point(im, 0, im->yimg);
gfx_close_path(im);
}
if (im->draw_x_grid == 1)
vertical_grid(im);
if (im->draw_y_grid == 1) {
if (im->logarithmic) {
res = horizontal_log_grid(im);
} else {
res = draw_horizontal_grid(im);
}
/* dont draw horizontal grid if there is no min and max val */
if (!res) {
char *nodata = "No Data found";
gfx_text(im, im->ximg / 2,
(2 * im->yorigin -
im->ysize) / 2,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_AXIS].
font_desc,
im->tabwidth, 0.0,
GFX_H_CENTER, GFX_V_CENTER, nodata);
}
}
/* yaxis unit description */
if (im->ylegend && im->ylegend[0] != '\0') {
gfx_text(im,
im->xOriginLegendY+10,
im->yOriginLegendY,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_UNIT].
font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE, GFX_H_CENTER, GFX_V_CENTER, im->ylegend);
}
if (im->second_axis_legend && im->second_axis_legend[0] != '\0') {
gfx_text( im,
im->xOriginLegendY2+10,
im->yOriginLegendY2,
im->graph_col[GRC_FONT],
im->text_prop[TEXT_PROP_UNIT].font_desc,
im->tabwidth,
RRDGRAPH_YLEGEND_ANGLE,
GFX_H_CENTER, GFX_V_CENTER,
im->second_axis_legend);
}
/* graph title */
gfx_text(im,
im->xOriginTitle, im->yOriginTitle+6,
im->graph_col[GRC_FONT],
im->
text_prop[TEXT_PROP_TITLE].
font_desc,
im->tabwidth, 0.0, GFX_H_CENTER, GFX_V_TOP, im->title?im->title:"");
/* rrdtool 'logo' */
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
double xpos = im->legendposition == EAST ? im->xOriginLegendY : im->ximg - 4;
gfx_text(im, xpos, 5,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth,
-90, GFX_H_LEFT, GFX_V_TOP, "RRDTOOL / TOBI OETIKER");
}
/* graph watermark */
if (im->watermark && im->watermark[0] != '\0') {
water_color = im->graph_col[GRC_FONT];
water_color.alpha = 0.3;
gfx_text(im,
im->ximg / 2, im->yimg - 6,
water_color,
im->
text_prop[TEXT_PROP_WATERMARK].
font_desc, im->tabwidth, 0,
GFX_H_CENTER, GFX_V_BOTTOM, im->watermark);
}
/* graph labels */
if (!(im->extra_flags & NOLEGEND) && !(im->extra_flags & ONLY_GRAPH)) {
long first_noncomment = im->gdes_c, last_noncomment = 0;
/* get smallest and biggest leg_y values. Assumes
* im->gdes[i].leg_y is in order. */
double min = 0, max = 0;
int gotcha = 0;
for (i = 0; i < im->gdes_c; i++) {
if (im->gdes[i].legend[0] == '\0')
continue;
if (!gotcha) {
min = im->gdes[i].leg_y;
gotcha = 1;
}
if (im->gdes[i].gf != GF_COMMENT) {
if (im->legenddirection == BOTTOM_UP2)
min = im->gdes[i].leg_y;
first_noncomment = i;
break;
}
}
gotcha = 0;
for (i = im->gdes_c - 1; i >= 0; i--) {
if (im->gdes[i].legend[0] == '\0')
continue;
if (!gotcha) {
max = im->gdes[i].leg_y;
gotcha = 1;
}
if (im->gdes[i].gf != GF_COMMENT) {
if (im->legenddirection == BOTTOM_UP2)
max = im->gdes[i].leg_y;
last_noncomment = i;
break;
}
}
for (i = 0; i < im->gdes_c; i++) {
if (im->gdes[i].legend[0] == '\0')
continue;
/* im->gdes[i].leg_y is the bottom of the legend */
X0 = im->xOriginLegend + im->gdes[i].leg_x;
int reverse = 0;
switch (im->legenddirection) {
case TOP_DOWN:
reverse = 0;
break;
case BOTTOM_UP:
reverse = 1;
break;
case BOTTOM_UP2:
reverse = i >= first_noncomment && i <= last_noncomment;
break;
}
Y0 = reverse ?
im->yOriginLegend + max + min - im->gdes[i].leg_y :
im->yOriginLegend + im->gdes[i].leg_y;
gfx_text(im, X0, Y0,
im->graph_col[GRC_FONT],
im->
text_prop
[TEXT_PROP_LEGEND].font_desc,
im->tabwidth, 0.0,
GFX_H_LEFT, GFX_V_BOTTOM, im->gdes[i].legend);
/* The legend for GRAPH items starts with "M " to have
enough space for the box */
if (im->gdes[i].gf != GF_PRINT &&
im->gdes[i].gf != GF_GPRINT && im->gdes[i].gf != GF_COMMENT) {
double boxH, boxV;
double X1, Y1;
boxH = gfx_get_text_width(im, 0,
im->
text_prop
[TEXT_PROP_LEGEND].
font_desc,
im->tabwidth, "o") * 1.2;
boxV = boxH;
/* shift the box up a bit */
Y0 -= boxV * 0.4;
if (im->dynamic_labels && im->gdes[i].gf == GF_HRULE) { /* [-] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0, Y0 - boxV / 2,
X0 + boxH, Y0 - boxV / 2,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_VRULE) { /* [|] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
gfx_line(im,
X0 + boxH / 2, Y0,
X0 + boxH / 2, Y0 - boxV,
1.0, im->gdes[i].col);
gfx_close_path(im);
} else if (im->dynamic_labels && im->gdes[i].gf == GF_LINE) { /* [/] */
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
gfx_line(im,
X0, Y0,
X0 + boxH, Y0 - boxV,
im->gdes[i].linewidth, im->gdes[i].col);
gfx_close_path(im);
} else {
/* make sure transparent colors show up the same way as in the graph */
gfx_new_area(im,
X0, Y0 - boxV,
X0, Y0, X0 + boxH, Y0, im->graph_col[GRC_BACK]);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
gfx_new_area(im, X0, Y0 - boxV, X0,
Y0, X0 + boxH, Y0, im->gdes[i].col);
gfx_add_point(im, X0 + boxH, Y0 - boxV);
gfx_close_path(im);
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, 1.0);
X1 = X0 + boxH;
Y1 = Y0 - boxV;
gfx_line_fit(im, &X0, &Y0);
gfx_line_fit(im, &X1, &Y1);
cairo_move_to(im->cr, X0, Y0);
cairo_line_to(im->cr, X1, Y0);
cairo_line_to(im->cr, X1, Y1);
cairo_line_to(im->cr, X0, Y1);
cairo_close_path(im->cr);
cairo_set_source_rgba(im->cr,
im->graph_col[GRC_FRAME].red,
im->graph_col[GRC_FRAME].green,
im->graph_col[GRC_FRAME].blue,
im->graph_col[GRC_FRAME].alpha);
}
if (im->gdes[i].dash) {
/* make box borders in legend dashed if the graph is dashed */
double dashes[] = {
3.0
};
cairo_set_dash(im->cr, dashes, 1, 0.0);
}
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
}
}
}
/*****************************************************
* lazy check make sure we rely need to create this graph
*****************************************************/
int lazy_check(
image_desc_t *im)
{
FILE *fd = NULL;
int size = 1;
struct stat imgstat;
if (im->lazy == 0)
return 0; /* no lazy option */
if (strlen(im->graphfile) == 0)
return 0; /* inmemory option */
if (stat(im->graphfile, &imgstat) != 0)
return 0; /* can't stat */
/* one pixel in the existing graph is more then what we would
change here ... */
if (time(NULL) - imgstat.st_mtime > (im->end - im->start) / im->xsize)
return 0;
if ((fd = fopen(im->graphfile, "rb")) == NULL)
return 0; /* the file does not exist */
switch (im->imgformat) {
case IF_PNG:
size = PngSize(fd, &(im->ximg), &(im->yimg));
break;
default:
size = 1;
}
fclose(fd);
return size;
}
int graph_size_location(
image_desc_t
*im,
int elements)
{
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area. If the option
** --full-size-mode is selected the size defines the total
** image size and the size available for the graph is
** calculated.
*/
/** +---+-----------------------------------+
** | y |...............graph title.........|
** | +---+-------------------------------+
** | a | y | |
** | x | | |
** | i | a | |
** | s | x | main graph area |
** | | i | |
** | t | s | |
** | i | | |
** | t | l | |
** | l | b +-------------------------------+
** | e | l | x axis labels |
** +---+---+-------------------------------+
** |....................legends............|
** +---------------------------------------+
** | watermark |
** +---------------------------------------+
*/
int Xvertical = 0, Xvertical2 = 0, Ytitle =
0, Xylabel = 0, Xmain = 0, Ymain =
0, Yxlabel = 0, Xspacing = 15, Yspacing = 15, Ywatermark = 4;
// no legends and no the shall be plotted it's easy
if (im->extra_flags & ONLY_GRAPH) {
im->xorigin = 0;
im->ximg = im->xsize;
im->yimg = im->ysize;
im->yorigin = im->ysize;
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
if (im->watermark && im->watermark[0] != '\0') {
Ywatermark = im->text_prop[TEXT_PROP_WATERMARK].size * 2;
}
// calculate the width of the left vertical legend
if (im->ylegend && im->ylegend[0] != '\0') {
Xvertical = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
// calculate the width of the right vertical legend
if (im->second_axis_legend && im->second_axis_legend[0] != '\0') {
Xvertical2 = im->text_prop[TEXT_PROP_UNIT].size * 2;
}
else{
Xvertical2 = Xspacing;
}
if (im->title && im->title[0] != '\0') {
/* The title is placed "inbetween" two text lines so it
** automatically has some vertical spacing. The horizontal
** spacing is added here, on each side.
*/
/* if necessary, reduce the font size of the title until it fits the image width */
Ytitle = im->text_prop[TEXT_PROP_TITLE].size * 2.6 + 10;
}
else{
// we have no title; get a little clearing from the top
Ytitle = Yspacing;
}
if (elements) {
if (im->draw_x_grid) {
// calculate the height of the horizontal labelling
Yxlabel = im->text_prop[TEXT_PROP_AXIS].size * 2.5;
}
if (im->draw_y_grid || im->forceleftspace) {
// calculate the width of the vertical labelling
Xylabel =
gfx_get_text_width(im, 0,
im->text_prop[TEXT_PROP_AXIS].font_desc,
im->tabwidth, "0") * im->unitslength;
}
}
// add some space to the labelling
Xylabel += Xspacing;
/* If the legend is printed besides the graph the width has to be
** calculated first. Placing the legend north or south of the
** graph requires the width calculation first, so the legend is
** skipped for the moment.
*/
im->legendheight = 0;
im->legendwidth = 0;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 1) == -1){
return -1;
}
}
}
if (im->extra_flags & FULL_SIZE_MODE) {
/* The actual size of the image to draw has been determined by the user.
** The graph area is the space remaining after accounting for the legend,
** the watermark, the axis labels, and the title.
*/
im->ximg = im->xsize;
im->yimg = im->ysize;
Xmain = im->ximg;
Ymain = im->yimg;
/* Now calculate the total size. Insert some spacing where
desired. im->xorigin and im->yorigin need to correspond
with the lower left corner of the main graph area or, if
this one is not set, the imaginary box surrounding the
pie chart area. */
/* Initial size calculation for the main graph area */
Xmain -= Xylabel;// + Xspacing;
if((im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
Xmain -= im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
Xmain -= Xylabel;
}
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
Xmain -= Xspacing;
}
Xmain -= Xvertical + Xvertical2;
/* limit the remaining space to 0 */
if(Xmain < 1){
Xmain = 1;
}
im->xsize = Xmain;
/* Putting the legend north or south, the height can now be calculated */
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
Ymain -= Yxlabel + im->legendheight;
}
else{
Ymain -= Yxlabel;
}
/* reserve space for the title *or* some padding above the graph */
Ymain -= Ytitle;
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
Ymain -= 0.5*Yspacing;
}
if (im->watermark && im->watermark[0] != '\0') {
Ymain -= Ywatermark;
}
/* limit the remaining height to 0 */
if(Ymain < 1){
Ymain = 1;
}
im->ysize = Ymain;
} else { /* dimension options -width and -height refer to the dimensions of the main graph area */
/* The actual size of the image to draw is determined from
** several sources. The size given on the command line is
** the graph area but we need more as we have to draw labels
** and other things outside the graph area.
*/
if (elements) {
Xmain = im->xsize; // + Xspacing;
Ymain = im->ysize;
}
im->ximg = Xmain + Xylabel;
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->ximg += Xspacing;
}
if( (im->legendposition == WEST || im->legendposition == EAST) && !(im->extra_flags & NOLEGEND) ){
im->ximg += im->legendwidth;// + Xspacing;
}
if (im->second_axis_scale != 0){
im->ximg += Xylabel;
}
im->ximg += Xvertical + Xvertical2;
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == NORTH || im->legendposition == SOUTH){
im->legendwidth = im->ximg;
if (leg_place(im, 0) == -1){
return -1;
}
}
}
im->yimg = Ymain + Yxlabel;
if( (im->legendposition == NORTH || im->legendposition == SOUTH) && !(im->extra_flags & NOLEGEND) ){
im->yimg += im->legendheight;
}
/* reserve space for the title *or* some padding above the graph */
if (Ytitle) {
im->yimg += Ytitle;
} else {
im->yimg += 1.5 * Yspacing;
}
/* reserve space for padding below the graph */
if (im->extra_flags & NOLEGEND) {
im->yimg += 0.5*Yspacing;
}
if (im->watermark && im->watermark[0] != '\0') {
im->yimg += Ywatermark;
}
}
/* In case of putting the legend in west or east position the first
** legend calculation might lead to wrong positions if some items
** are not aligned on the left hand side (e.g. centered) as the
** legendwidth wight have been increased after the item was placed.
** In this case the positions have to be recalculated.
*/
if (!(im->extra_flags & NOLEGEND)) {
if(im->legendposition == WEST || im->legendposition == EAST){
if (leg_place(im, 0) == -1){
return -1;
}
}
}
/* After calculating all dimensions
** it is now possible to calculate
** all offsets.
*/
switch(im->legendposition){
case NORTH:
im->xOriginTitle = (im->ximg / 2);
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + im->legendheight + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + im->legendheight + (Ymain / 2) + Yxlabel;
break;
case WEST:
im->xOriginTitle = im->legendwidth + im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle;
im->xOriginLegendY = im->legendwidth;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = im->legendwidth + Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = im->legendwidth + Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case SOUTH:
im->xOriginTitle = im->ximg / 2;
im->yOriginTitle = 0;
im->xOriginLegend = 0;
im->yOriginLegend = Ytitle + Ymain + Yxlabel;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
break;
case EAST:
im->xOriginTitle = im->xsize / 2;
im->yOriginTitle = 0;
im->xOriginLegend = Xvertical + Xylabel + Xmain + Xvertical2;
if (im->second_axis_scale != 0){
im->xOriginLegend += Xylabel;
}
im->yOriginLegend = Ytitle;
im->xOriginLegendY = 0;
im->yOriginLegendY = Ytitle + (Ymain / 2);
im->xorigin = Xvertical + Xylabel;
im->yorigin = Ytitle + Ymain;
im->xOriginLegendY2 = Xvertical + Xylabel + Xmain;
if (im->second_axis_scale != 0){
im->xOriginLegendY2 += Xylabel;
}
im->yOriginLegendY2 = Ytitle + (Ymain / 2);
if (!(im->extra_flags & NO_RRDTOOL_TAG)){
im->xOriginTitle += Xspacing;
im->xOriginLegend += Xspacing;
im->xOriginLegendY += Xspacing;
im->xorigin += Xspacing;
im->xOriginLegendY2 += Xspacing;
}
break;
}
xtr(im, 0);
ytr(im, DNAN);
return 0;
}
static cairo_status_t cairo_output(
void *closure,
const unsigned char
*data,
unsigned int length)
{
image_desc_t *im = (image_desc_t*)closure;
im->rendered_image =
(unsigned char*)realloc(im->rendered_image, im->rendered_image_size + length);
if (im->rendered_image == NULL)
return CAIRO_STATUS_WRITE_ERROR;
memcpy(im->rendered_image + im->rendered_image_size, data, length);
im->rendered_image_size += length;
return CAIRO_STATUS_SUCCESS;
}
/* draw that picture thing ... */
int graph_paint(
image_desc_t *im)
{
int lazy = lazy_check(im);
int cnt;
/* imgformat XML or higher dispatch to xport
* output format there is selected via graph_type
*/
if (im->imgformat >= IF_XML) {
return rrd_graph_xport(im);
}
/* pull the data from the rrd files ... */
if (data_fetch(im) == -1)
return -1;
/* evaluate VDEF and CDEF operations ... */
if (data_calc(im) == -1)
return -1;
/* calculate and PRINT and GPRINT definitions. We have to do it at
* this point because it will affect the length of the legends
* if there are no graph elements (i==0) we stop here ...
* if we are lazy, try to quit ...
*/
cnt = print_calc(im);
if (cnt < 0)
return -1;
/* if we want and can be lazy ... quit now */
if (cnt == 0)
return 0;
/* otherwise call graph_paint_timestring */
switch (im->graph_type) {
case GTYPE_TIME:
return graph_paint_timestring(im,lazy,cnt);
break;
case GTYPE_XY:
return graph_paint_xy(im,lazy,cnt);
break;
}
/* final return with error*/
rrd_set_error("Graph type %i is not implemented",im->graph_type);
return -1;
}
int graph_paint_timestring(
image_desc_t *im, int lazy, int cnt)
{
int i,ii;
double areazero = 0.0;
graph_desc_t *lastgdes = NULL;
rrd_infoval_t info;
/**************************************************************
*** Calculating sizes and locations became a bit confusing ***
*** so I moved this into a separate function. ***
**************************************************************/
if (graph_size_location(im, cnt) == -1)
return -1;
info.u_cnt = im->xorigin;
grinfo_push(im, sprintf_alloc("graph_left"), RD_I_CNT, info);
info.u_cnt = im->yorigin - im->ysize;
grinfo_push(im, sprintf_alloc("graph_top"), RD_I_CNT, info);
info.u_cnt = im->xsize;
grinfo_push(im, sprintf_alloc("graph_width"), RD_I_CNT, info);
info.u_cnt = im->ysize;
grinfo_push(im, sprintf_alloc("graph_height"), RD_I_CNT, info);
info.u_cnt = im->ximg;
grinfo_push(im, sprintf_alloc("image_width"), RD_I_CNT, info);
info.u_cnt = im->yimg;
grinfo_push(im, sprintf_alloc("image_height"), RD_I_CNT, info);
info.u_cnt = im->start;
grinfo_push(im, sprintf_alloc("graph_start"), RD_I_CNT, info);
info.u_cnt = im->end;
grinfo_push(im, sprintf_alloc("graph_end"), RD_I_CNT, info);
/* if we want and can be lazy ... quit now */
if (lazy)
return 0;
/* get actual drawing data and find min and max values */
if (data_proc(im) == -1)
return -1;
if (!im->logarithmic) {
si_unit(im);
}
/* identify si magnitude Kilo, Mega Giga ? */
if (!im->rigid && !im->logarithmic)
expand_range(im); /* make sure the upper and lower limit are
sensible values */
info.u_val = im->minval;
grinfo_push(im, sprintf_alloc("value_min"), RD_I_VAL, info);
info.u_val = im->maxval;
grinfo_push(im, sprintf_alloc("value_max"), RD_I_VAL, info);
if (!calc_horizontal_grid(im))
return -1;
/* reset precalc */
ytr(im, DNAN);
/* if (im->gridfit)
apply_gridfit(im); */
/* set up cairo */
if (graph_cairo_setup(im)) { return -1; }
/* other stuff */
if (im->minval > 0.0)
areazero = im->minval;
if (im->maxval < 0.0)
areazero = im->maxval;
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_CDEF:
case GF_VDEF:
case GF_DEF:
case GF_PRINT:
case GF_GPRINT:
case GF_COMMENT:
case GF_TEXTALIGN:
case GF_HRULE:
case GF_VRULE:
case GF_XPORT:
case GF_SHIFT:
case GF_XAXIS:
case GF_YAXIS:
break;
case GF_TICK:
for (ii = 0; ii < im->xsize; ii++) {
if (!isnan(im->gdes[i].p_data[ii])
&& im->gdes[i].p_data[ii] != 0.0) {
if (im->gdes[i].yrule > 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin + 1.0,
im->xorigin + ii,
im->yorigin -
im->gdes[i].yrule *
im->ysize, 1.0, im->gdes[i].col);
} else if (im->gdes[i].yrule < 0) {
gfx_line(im,
im->xorigin + ii,
im->yorigin - im->ysize - 1.0,
im->xorigin + ii,
im->yorigin - im->ysize -
im->gdes[i].
yrule *
im->ysize, 1.0, im->gdes[i].col);
}
}
}
break;
case GF_LINE:
case GF_AREA:
case GF_GRAD: {
rrd_value_t diffval = im->maxval - im->minval;
rrd_value_t maxlimit = im->maxval + 9 * diffval;
rrd_value_t minlimit = im->minval - 9 * diffval;
for (ii = 0; ii < im->xsize; ii++) {
/* fix data points at oo and -oo */
if (isinf(im->gdes[i].p_data[ii])) {
if (im->gdes[i].p_data[ii] > 0) {
im->gdes[i].p_data[ii] = im->maxval;
} else {
im->gdes[i].p_data[ii] = im->minval;
}
}
/* some versions of cairo go unstable when trying
to draw way out of the canvas ... lets not even try */
if (im->gdes[i].p_data[ii] > maxlimit) {
im->gdes[i].p_data[ii] = maxlimit;
}
if (im->gdes[i].p_data[ii] < minlimit) {
im->gdes[i].p_data[ii] = minlimit;
}
} /* for */
/* *******************************************************
a ___. (a,t)
| | ___
____| | | |
| |___|
-------|--t-1--t--------------------------------
if we know the value at time t was a then
we draw a square from t-1 to t with the value a.
********************************************************* */
if (im->gdes[i].col.alpha != 0.0) {
/* GF_LINE and friend */
if (im->gdes[i].gf == GF_LINE) {
double last_y = 0.0;
int draw_on = 0;
cairo_save(im->cr);
cairo_new_path(im->cr);
cairo_set_line_width(im->cr, im->gdes[i].linewidth);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
for (ii = 1; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])
|| (im->slopemode == 1
&& isnan(im->gdes[i].p_data[ii - 1]))) {
draw_on = 0;
continue;
}
if (draw_on == 0) {
last_y = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0) {
double x = ii - 1 + im->xorigin;
double y = last_y;
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
} else {
double x = ii - 1 + im->xorigin;
double y =
ytr(im, im->gdes[i].p_data[ii - 1]);
gfx_line_fit(im, &x, &y);
cairo_move_to(im->cr, x, y);
x = ii + im->xorigin;
y = last_y;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
}
draw_on = 1;
} else {
double x1 = ii + im->xorigin;
double y1 = ytr(im, im->gdes[i].p_data[ii]);
if (im->slopemode == 0
&& !AlmostEqual2sComplement(y1, last_y, 4)) {
double x = ii - 1 + im->xorigin;
double y = y1;
gfx_line_fit(im, &x, &y);
cairo_line_to(im->cr, x, y);
};
last_y = y1;
gfx_line_fit(im, &x1, &y1);
cairo_line_to(im->cr, x1, y1);
};
}
cairo_set_source_rgba(im->cr,
im->gdes[i].
col.red,
im->gdes[i].
col.green,
im->gdes[i].
col.blue, im->gdes[i].col.alpha);
cairo_set_line_cap(im->cr, CAIRO_LINE_CAP_ROUND);
cairo_set_line_join(im->cr, CAIRO_LINE_JOIN_ROUND);
cairo_stroke(im->cr);
cairo_restore(im->cr);
} else {
double lastx=0;
double lasty=0;
int idxI = -1;
double *foreY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *foreX =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backY =
(double *) malloc(sizeof(double) * im->xsize * 2);
double *backX =
(double *) malloc(sizeof(double) * im->xsize * 2);
int drawem = 0;
for (ii = 0; ii <= im->xsize; ii++) {
double ybase, ytop;
if (idxI > 0 && (drawem != 0 || ii == im->xsize)) {
int cntI = 1;
int lastI = 0;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI + 1], 4)) {
cntI++;
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_new_area(im,
backX[0], backY[0],
foreX[0], foreY[0],
foreX[cntI],
foreY[cntI], im->gdes[i].col);
} else {
lastx = foreX[cntI];
lasty = foreY[cntI];
}
while (cntI < idxI) {
lastI = cntI;
cntI++;
while (cntI < idxI
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY[cntI], 4)
&&
AlmostEqual2sComplement(foreY
[lastI],
foreY
[cntI
+ 1], 4)) {
cntI++;
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_add_point(im, foreX[cntI], foreY[cntI]);
} else {
gfx_add_rect_fadey(im,
lastx, foreY[0],
foreX[cntI], foreY[cntI], lasty,
im->gdes[i].col,
im->gdes[i].col2,
im->gdes[i].gradheight
);
lastx = foreX[cntI];
lasty = foreY[cntI];
}
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_add_point(im, backX[idxI], backY[idxI]);
} else {
gfx_add_rect_fadey(im,
lastx, foreY[0],
backX[idxI], backY[idxI], lasty,
im->gdes[i].col,
im->gdes[i].col2,
im->gdes[i].gradheight);
lastx = backX[idxI];
lasty = backY[idxI];
}
while (idxI > 1) {
lastI = idxI;
idxI--;
while (idxI > 1
&&
AlmostEqual2sComplement(backY
[lastI],
backY[idxI], 4)
&&
AlmostEqual2sComplement(backY
[lastI],
backY
[idxI
- 1], 4)) {
idxI--;
}
if (im->gdes[i].gf != GF_GRAD) {
gfx_add_point(im, backX[idxI], backY[idxI]);
} else {
gfx_add_rect_fadey(im,
lastx, foreY[0],
backX[idxI], backY[idxI], lasty,
im->gdes[i].col,
im->gdes[i].col2,
im->gdes[i].gradheight);
lastx = backX[idxI];
lasty = backY[idxI];
}
}
idxI = -1;
drawem = 0;
if (im->gdes[i].gf != GF_GRAD)
gfx_close_path(im);
}
if (drawem != 0) {
drawem = 0;
idxI = -1;
}
if (ii == im->xsize)
break;
if (im->slopemode == 0 && ii == 0) {
continue;
}
if (isnan(im->gdes[i].p_data[ii])) {
drawem = 1;
continue;
}
ytop = ytr(im, im->gdes[i].p_data[ii]);
if (lastgdes && im->gdes[i].stack) {
ybase = ytr(im, lastgdes->p_data[ii]);
} else {
ybase = ytr(im, areazero);
}
if (ybase == ytop) {
drawem = 1;
continue;
}
if (ybase > ytop) {
double extra = ytop;
ytop = ybase;
ybase = extra;
}
if (im->slopemode == 0) {
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin - 1;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin - 1;
}
backY[++idxI] = ybase - 0.2;
backX[idxI] = ii + im->xorigin;
foreY[idxI] = ytop + 0.2;
foreX[idxI] = ii + im->xorigin;
}
/* close up any remaining area */
free(foreY);
free(foreX);
free(backY);
free(backX);
} /* else GF_LINE */
}
/* if color != 0x0 */
/* make sure we do not run into trouble when stacking on NaN */
for (ii = 0; ii < im->xsize; ii++) {
if (isnan(im->gdes[i].p_data[ii])) {
if (lastgdes && (im->gdes[i].stack)) {
im->gdes[i].p_data[ii] = lastgdes->p_data[ii];
} else {
im->gdes[i].p_data[ii] = areazero;
}
}
}
lastgdes = &(im->gdes[i]);
break;
} /* GF_AREA, GF_LINE, GF_GRAD */
case GF_STACK:
rrd_set_error
("STACK should already be turned into LINE or AREA here");
return -1;
break;
} /* switch */
}
cairo_reset_clip(im->cr);
/* grid_paint also does the text */
if (!(im->extra_flags & ONLY_GRAPH))
grid_paint(im);
if (!(im->extra_flags & ONLY_GRAPH))
axis_paint(im);
/* the RULES are the last thing to paint ... */
for (i = 0; i < im->gdes_c; i++) {
switch (im->gdes[i].gf) {
case GF_HRULE:
if (im->gdes[i].yrule >= im->minval
&& im->gdes[i].yrule <= im->maxval) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im, im->xorigin,
ytr(im, im->gdes[i].yrule),
im->xorigin + im->xsize,
ytr(im, im->gdes[i].yrule), 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
case GF_VRULE:
if (im->gdes[i].xrule >= im->start
&& im->gdes[i].xrule <= im->end) {
cairo_save(im->cr);
if (im->gdes[i].dash) {
cairo_set_dash(im->cr,
im->gdes[i].p_dashes,
im->gdes[i].ndash, im->gdes[i].offset);
}
gfx_line(im,
xtr(im, im->gdes[i].xrule),
im->yorigin, xtr(im,
im->
gdes[i].
xrule),
im->yorigin - im->ysize, 1.0, im->gdes[i].col);
cairo_stroke(im->cr);
cairo_restore(im->cr);
}
break;
default:
break;
}
}
/* close the graph via cairo*/
return graph_cairo_finish(im);
}
int graph_cairo_setup (image_desc_t *im)
{
/* the actual graph is created by going through the individual
graph elements and then drawing them */
cairo_surface_destroy(im->surface);
switch (im->imgformat) {
case IF_PNG:
im->surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
im->ximg * im->zoom,
im->yimg * im->zoom);
break;
case IF_PDF:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
? cairo_pdf_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_pdf_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_EPS:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_ps_surface_create(im->graphfile, im->ximg * im->zoom,
im->yimg * im->zoom)
: cairo_ps_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
break;
case IF_SVG:
im->gridfit = 0;
im->surface = strlen(im->graphfile)
?
cairo_svg_surface_create(im->
graphfile,
im->ximg * im->zoom, im->yimg * im->zoom)
: cairo_svg_surface_create_for_stream
(&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
cairo_svg_surface_restrict_to_version
(im->surface, CAIRO_SVG_VERSION_1_1);
break;
case IF_XML:
case IF_XMLENUM:
case IF_CSV:
case IF_TSV:
case IF_SSV:
case IF_JSON:
case IF_JSONTIME:
break;
};
cairo_destroy(im->cr);
im->cr = cairo_create(im->surface);
cairo_set_antialias(im->cr, im->graph_antialias);
cairo_scale(im->cr, im->zoom, im->zoom);
// pango_cairo_font_map_set_resolution(PANGO_CAIRO_FONT_MAP(font_map), 100);
gfx_new_area(im, 0, 0, 0, im->yimg,
im->ximg, im->yimg, im->graph_col[GRC_BACK]);
gfx_add_point(im, im->ximg, 0);
gfx_close_path(im);
gfx_new_area(im, im->xorigin,
im->yorigin,
im->xorigin +
im->xsize, im->yorigin,
im->xorigin +
im->xsize,
im->yorigin - im->ysize, im->graph_col[GRC_CANVAS]);
gfx_add_point(im, im->xorigin, im->yorigin - im->ysize);
gfx_close_path(im);
cairo_rectangle(im->cr, im->xorigin, im->yorigin - im->ysize - 1.0,
im->xsize, im->ysize + 2.0);
cairo_clip(im->cr);
return 0;
}
int graph_cairo_finish (image_desc_t *im)
{
switch (im->imgformat) {
case IF_PNG:
{
cairo_status_t status;
status = strlen(im->graphfile) ?
cairo_surface_write_to_png(im->surface, im->graphfile)
: cairo_surface_write_to_png_stream(im->surface, &cairo_output,
im);
if (status != CAIRO_STATUS_SUCCESS) {
rrd_set_error("Could not save png to '%s'", im->graphfile);
return 1;
}
break;
}
case IF_XML:
case IF_XMLENUM:
case IF_CSV:
case IF_TSV:
case IF_SSV:
case IF_JSON:
case IF_JSONTIME:
break;
default:
if (strlen(im->graphfile)) {
cairo_show_page(im->cr);
} else {
cairo_surface_finish(im->surface);
}
break;
}
return 0;
}
int graph_paint_xy(
image_desc_t UNUSED(*im), int UNUSED(lazy), int UNUSED(cnt))
{
rrd_set_error("XY diagramm not implemented");
return -1;
}
/*****************************************************
* graph stuff
*****************************************************/
int gdes_alloc(
image_desc_t *im)
{
im->gdes_c++;
if ((im->gdes = (graph_desc_t *)
rrd_realloc(im->gdes, (im->gdes_c)
* sizeof(graph_desc_t))) == NULL) {
rrd_set_error("realloc graph_descs");
return -1;
}
/* set to zero */
memset(&(im->gdes[im->gdes_c - 1]),0,sizeof(graph_desc_t));
im->gdes[im->gdes_c - 1].step = im->step;
im->gdes[im->gdes_c - 1].step_orig = im->step;
im->gdes[im->gdes_c - 1].stack = 0;
im->gdes[im->gdes_c - 1].skipscale = 0;
im->gdes[im->gdes_c - 1].linewidth = 0;
im->gdes[im->gdes_c - 1].debug = 0;
im->gdes[im->gdes_c - 1].start = im->start;
im->gdes[im->gdes_c - 1].start_orig = im->start;
im->gdes[im->gdes_c - 1].end = im->end;
im->gdes[im->gdes_c - 1].end_orig = im->end;
im->gdes[im->gdes_c - 1].vname[0] = '\0';
im->gdes[im->gdes_c - 1].data = NULL;
im->gdes[im->gdes_c - 1].ds_namv = NULL;
im->gdes[im->gdes_c - 1].data_first = 0;
im->gdes[im->gdes_c - 1].p_data = NULL;
im->gdes[im->gdes_c - 1].rpnp = NULL;
im->gdes[im->gdes_c - 1].p_dashes = NULL;
im->gdes[im->gdes_c - 1].shift = 0.0;
im->gdes[im->gdes_c - 1].dash = 0;
im->gdes[im->gdes_c - 1].ndash = 0;
im->gdes[im->gdes_c - 1].offset = 0;
im->gdes[im->gdes_c - 1].col.red = 0.0;
im->gdes[im->gdes_c - 1].col.green = 0.0;
im->gdes[im->gdes_c - 1].col.blue = 0.0;
im->gdes[im->gdes_c - 1].col.alpha = 0.0;
im->gdes[im->gdes_c - 1].col2.red = 0.0;
im->gdes[im->gdes_c - 1].col2.green = 0.0;
im->gdes[im->gdes_c - 1].col2.blue = 0.0;
im->gdes[im->gdes_c - 1].col2.alpha = 0.0;
im->gdes[im->gdes_c - 1].gradheight = 50.0;
im->gdes[im->gdes_c - 1].legend[0] = '\0';
im->gdes[im->gdes_c - 1].format[0] = '\0';
im->gdes[im->gdes_c - 1].strftm = 0;
im->gdes[im->gdes_c - 1].rrd[0] = '\0';
im->gdes[im->gdes_c - 1].ds = -1;
im->gdes[im->gdes_c - 1].cf_reduce = CF_AVERAGE;
im->gdes[im->gdes_c - 1].cf_reduce_set = 0;
im->gdes[im->gdes_c - 1].cf = CF_AVERAGE;
im->gdes[im->gdes_c - 1].yrule = DNAN;
im->gdes[im->gdes_c - 1].xrule = 0;
im->gdes[im->gdes_c - 1].daemon[0] = 0;
return 0;
}
/* copies input untill the first unescaped colon is found
or until input ends. backslashes have to be escaped as well */
int scan_for_col(
const char *const input,
int len,
char *const output)
{
int inp, outp = 0;
for (inp = 0; inp < len && input[inp] != ':' && input[inp] != '\0'; inp++) {
if (input[inp] == '\\'
&& input[inp + 1] != '\0'
&& (input[inp + 1] == '\\' || input[inp + 1] == ':')) {
output[outp++] = input[++inp];
} else {
output[outp++] = input[inp];
}
}
output[outp] = '\0';
return inp;
}
/* Now just a wrapper around rrd_graph_v */
int rrd_graph(
int argc,
char **argv,
char ***prdata,
int *xsize,
int *ysize,
FILE * stream,
double *ymin,
double *ymax)
{
int prlines = 0;
rrd_info_t *grinfo = NULL;
rrd_info_t *walker;
grinfo = rrd_graph_v(argc, argv);
if (grinfo == NULL)
return -1;
walker = grinfo;
(*prdata) = NULL;
while (walker) {
if (strcmp(walker->key, "image_info") == 0) {
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
/* imginfo goes to position 0 in the prdata array */
(*prdata)[prlines - 1] = strdup(walker->value.u_str);
(*prdata)[prlines] = NULL;
}
/* skip anything else */
walker = walker->next;
}
walker = grinfo;
*xsize = 0;
*ysize = 0;
*ymin = 0;
*ymax = 0;
while (walker) {
if (strcmp(walker->key, "image_width") == 0) {
*xsize = walker->value.u_cnt;
} else if (strcmp(walker->key, "image_height") == 0) {
*ysize = walker->value.u_cnt;
} else if (strcmp(walker->key, "value_min") == 0) {
*ymin = walker->value.u_val;
} else if (strcmp(walker->key, "value_max") == 0) {
*ymax = walker->value.u_val;
} else if (strncmp(walker->key, "print", 5) == 0) { /* keys are prdate[0..] */
prlines++;
if (((*prdata) =
(char**)rrd_realloc((*prdata),
(prlines + 1) * sizeof(char *))) == NULL) {
rrd_set_error("realloc prdata");
return 0;
}
(*prdata)[prlines - 1] = strdup(walker->value.u_str);
(*prdata)[prlines] = NULL;
} else if (strcmp(walker->key, "image") == 0) {
if ( fwrite(walker->value.u_blo.ptr, walker->value.u_blo.size, 1,
(stream ? stream : stdout)) == 0 && ferror(stream ? stream : stdout)){
rrd_set_error("writing image");
return 0;
}
}
/* skip anything else */
walker = walker->next;
}
rrd_info_free(grinfo);
return 0;
}
/* Some surgery done on this function, it became ridiculously big.
** Things moved:
** - initializing now in rrd_graph_init()
** - options parsing now in rrd_graph_options()
** - script parsing now in rrd_graph_script()
*/
rrd_info_t *rrd_graph_v(
int argc,
char **argv)
{
image_desc_t im;
rrd_info_t *grinfo;
rrd_graph_init(&im);
/* a dummy surface so that we can measure text sizes for placements */
rrd_graph_options(argc, argv, &im);
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
if (optind >= argc) {
rrd_info_free(im.grinfo);
im_free(&im);
rrd_set_error("missing filename");
return NULL;
}
if (strlen(argv[optind]) >= MAXPATH) {
rrd_set_error("filename (including path) too long");
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
strncpy(im.graphfile, argv[optind], MAXPATH - 1);
im.graphfile[MAXPATH - 1] = '\0';
if (strcmp(im.graphfile, "-") == 0) {
im.graphfile[0] = '\0';
}
rrd_graph_script(argc, argv, &im, 1);
if (rrd_test_error()) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* Everything is now read and the actual work can start */
if (graph_paint(&im) == -1) {
rrd_info_free(im.grinfo);
im_free(&im);
return NULL;
}
/* The image is generated and needs to be output.
** Also, if needed, print a line with information about the image.
*/
if (im.imginfo && *im.imginfo) {
rrd_infoval_t info;
char *path;
char *filename;
if (bad_format_imginfo(im.imginfo)) {
rrd_info_free(im.grinfo);
im_free(&im);
rrd_set_error("bad format for imginfo");
return NULL;
}
path = strdup(im.graphfile);
filename = basename(path);
info.u_str =
sprintf_alloc(im.imginfo,
filename,
(long) (im.zoom *
im.ximg), (long) (im.zoom * im.yimg));
grinfo_push(&im, sprintf_alloc("image_info"), RD_I_STR, info);
free(info.u_str);
free(path);
}
if (im.rendered_image) {
rrd_infoval_t img;
img.u_blo.size = im.rendered_image_size;
img.u_blo.ptr = im.rendered_image;
grinfo_push(&im, sprintf_alloc("image"), RD_I_BLO, img);
}
grinfo = im.grinfo;
im_free(&im);
return grinfo;
}
static void
rrd_set_font_desc (
image_desc_t *im,int prop,char *font, double size ){
if (font){
strncpy(im->text_prop[prop].font, font, sizeof(text_prop[prop].font) - 1);
im->text_prop[prop].font[sizeof(text_prop[prop].font) - 1] = '\0';
/* if we already got one, drop it first */
pango_font_description_free(im->text_prop[prop].font_desc);
im->text_prop[prop].font_desc = pango_font_description_from_string( font );
};
if (size > 0){
im->text_prop[prop].size = size;
};
if (im->text_prop[prop].font_desc && im->text_prop[prop].size ){
pango_font_description_set_size(im->text_prop[prop].font_desc, im->text_prop[prop].size * PANGO_SCALE);
};
}
void rrd_graph_init(
image_desc_t
*im)
{
unsigned int i;
char *deffont = getenv("RRD_DEFAULT_FONT");
static PangoFontMap *fontmap = NULL;
PangoContext *context;
/* zero the whole structure first */
memset(im,0,sizeof(image_desc_t));
#ifdef HAVE_TZSET
tzset();
#endif
im->gdef_map = g_hash_table_new_full(g_str_hash, g_str_equal,g_free,NULL);
//use of g_free() cause heap damage on windows. Key is allocated by malloc() in sprintf_alloc(), so free() must use
im->rrd_map = g_hash_table_new_full(g_str_hash, g_str_equal,free,NULL);
im->graph_type = GTYPE_TIME;
im->base = 1000;
im->daemon_addr = NULL;
im->draw_x_grid = 1;
im->draw_y_grid = 1;
im->draw_3d_border = 2;
im->dynamic_labels = 0;
im->extra_flags = 0;
im->font_options = cairo_font_options_create();
im->forceleftspace = 0;
im->gdes_c = 0;
im->gdes = NULL;
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
im->grid_dash_off = 1;
im->grid_dash_on = 1;
im->gridfit = 1;
im->grinfo = (rrd_info_t *) NULL;
im->grinfo_current = (rrd_info_t *) NULL;
im->imgformat = IF_PNG;
im->imginfo = NULL;
im->lazy = 0;
im->legenddirection = TOP_DOWN;
im->legendheight = 0;
im->legendposition = SOUTH;
im->legendwidth = 0;
im->logarithmic = 0;
im->maxval = DNAN;
im->minval = 0;
im->minval = DNAN;
im->magfact = 1;
im->prt_c = 0;
im->rigid = 0;
im->rendered_image_size = 0;
im->rendered_image = NULL;
im->slopemode = 0;
im->step = 0;
im->symbol = ' ';
im->tabwidth = 40.0;
im->title = NULL;
im->unitsexponent = 9999;
im->unitslength = 6;
im->viewfactor = 1.0;
im->watermark = NULL;
im->xlab_form = NULL;
im->with_markup = 0;
im->ximg = 0;
im->xlab_user.minsec = -1;
im->xorigin = 0;
im->xOriginLegend = 0;
im->xOriginLegendY = 0;
im->xOriginLegendY2 = 0;
im->xOriginTitle = 0;
im->xsize = 400;
im->ygridstep = DNAN;
im->yimg = 0;
im->ylegend = NULL;
im->second_axis_scale = 0; /* 0 disables it */
im->second_axis_shift = 0; /* no shift by default */
im->second_axis_legend = NULL;
im->second_axis_format = NULL;
im->primary_axis_format = NULL;
im->yorigin = 0;
im->yOriginLegend = 0;
im->yOriginLegendY = 0;
im->yOriginLegendY2 = 0;
im->yOriginTitle = 0;
im->ysize = 100;
im->zoom = 1;
im->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 10, 10);
im->cr = cairo_create(im->surface);
for (i = 0; i < DIM(text_prop); i++) {
im->text_prop[i].size = -1;
im->text_prop[i].font_desc = NULL;
rrd_set_font_desc(im,i, deffont ? deffont : text_prop[i].font,text_prop[i].size);
}
if (fontmap == NULL){
fontmap = pango_cairo_font_map_get_default();
}
context = pango_font_map_create_context(fontmap);
pango_cairo_context_set_resolution(context, 100);
pango_cairo_update_context(im->cr,context);
im->layout = pango_layout_new(context);
g_object_unref (context);
// im->layout = pango_cairo_create_layout(im->cr);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
cairo_font_options_set_hint_metrics
(im->font_options, CAIRO_HINT_METRICS_ON);
cairo_font_options_set_antialias(im->font_options, CAIRO_ANTIALIAS_GRAY);
for (i = 0; i < DIM(graph_col); i++)
im->graph_col[i] = graph_col[i];
}
void rrd_graph_options(
int argc,
char *argv[],
image_desc_t
*im)
{
int stroff;
char *parsetime_error = NULL;
char scan_gtm[12], scan_mtm[12], scan_ltm[12], col_nam[12];
char double_str[20], double_str2[20];
time_t start_tmp = 0, end_tmp = 0;
long long_tmp;
rrd_time_value_t start_tv, end_tv;
long unsigned int color;
/* defines for long options without a short equivalent. should be bytes,
and may not collide with (the ASCII value of) short options */
#define LONGOPT_UNITS_SI 255
/* *INDENT-OFF* */
struct option long_options[] = {
{ "alt-autoscale", no_argument, 0, 'A'},
{ "imgformat", required_argument, 0, 'a'},
{ "font-smoothing-threshold", required_argument, 0, 'B'},
{ "base", required_argument, 0, 'b'},
{ "color", required_argument, 0, 'c'},
{ "full-size-mode", no_argument, 0, 'D'},
{ "daemon", required_argument, 0, 'd'},
{ "slope-mode", no_argument, 0, 'E'},
{ "end", required_argument, 0, 'e'},
{ "force-rules-legend", no_argument, 0, 'F'},
{ "imginfo", required_argument, 0, 'f'},
{ "graph-render-mode", required_argument, 0, 'G'},
{ "no-legend", no_argument, 0, 'g'},
{ "height", required_argument, 0, 'h'},
{ "no-minor", no_argument, 0, 'I'},
{ "interlaced", no_argument, 0, 'i'},
{ "alt-autoscale-min", no_argument, 0, 'J'},
{ "only-graph", no_argument, 0, 'j'},
{ "units-length", required_argument, 0, 'L'},
{ "lower-limit", required_argument, 0, 'l'},
{ "alt-autoscale-max", no_argument, 0, 'M'},
{ "zoom", required_argument, 0, 'm'},
{ "no-gridfit", no_argument, 0, 'N'},
{ "font", required_argument, 0, 'n'},
{ "logarithmic", no_argument, 0, 'o'},
{ "pango-markup", no_argument, 0, 'P'},
{ "font-render-mode", required_argument, 0, 'R'},
{ "rigid", no_argument, 0, 'r'},
{ "step", required_argument, 0, 'S'},
{ "start", required_argument, 0, 's'},
{ "tabwidth", required_argument, 0, 'T'},
{ "title", required_argument, 0, 't'},
{ "upper-limit", required_argument, 0, 'u'},
{ "vertical-label", required_argument, 0, 'v'},
{ "watermark", required_argument, 0, 'W'},
{ "width", required_argument, 0, 'w'},
{ "units-exponent", required_argument, 0, 'X'},
{ "x-grid", required_argument, 0, 'x'},
{ "alt-y-grid", no_argument, 0, 'Y'},
{ "y-grid", required_argument, 0, 'y'},
{ "lazy", no_argument, 0, 'z'},
{ "use-nan-for-all-missing-data", no_argument, 0, 'Z'},
{ "units", required_argument, 0, LONGOPT_UNITS_SI},
{ "alt-y-mrtg", no_argument, 0, 1000}, /* this has no effect it is just here to save old apps from crashing when they use it */
{ "disable-rrdtool-tag",no_argument, 0, 1001},
{ "right-axis", required_argument, 0, 1002},
{ "right-axis-label", required_argument, 0, 1003},
{ "right-axis-format", required_argument, 0, 1004},
{ "legend-position", required_argument, 0, 1005},
{ "legend-direction", required_argument, 0, 1006},
{ "border", required_argument, 0, 1007},
{ "grid-dash", required_argument, 0, 1008},
{ "dynamic-labels", no_argument, 0, 1009},
{ "week-fmt", required_argument, 0, 1010},
{ "graph-type", required_argument, 0, 1011},
{ "left-axis-format", required_argument, 0, 1012},
{ 0, 0, 0, 0}
};
/* *INDENT-ON* */
optind = 0;
opterr = 0; /* initialize getopt */
rrd_parsetime("end-24h", &start_tv);
rrd_parsetime("now", &end_tv);
while (1) {
int option_index = 0;
int opt;
int col_start, col_end;
opt = getopt_long(argc, argv,
"Aa:B:b:c:Dd:Ee:Ff:G:gh:IiJjL:l:Mm:Nn:oPR:rS:s:T:t:u:v:W:w:X:x:Yy:Zz",
long_options, &option_index);
if (opt == EOF)
break;
switch (opt) {
case 'I':
im->extra_flags |= NOMINOR;
break;
case 'Y':
im->extra_flags |= ALTYGRID;
break;
case 'A':
im->extra_flags |= ALTAUTOSCALE;
break;
case 'J':
im->extra_flags |= ALTAUTOSCALE_MIN;
break;
case 'M':
im->extra_flags |= ALTAUTOSCALE_MAX;
break;
case 'j':
im->extra_flags |= ONLY_GRAPH;
break;
case 'g':
im->extra_flags |= NOLEGEND;
break;
case 'Z':
im->extra_flags |= ALLOW_MISSING_DS;
break;
case 1005:
if (strcmp(optarg, "north") == 0) {
im->legendposition = NORTH;
} else if (strcmp(optarg, "west") == 0) {
im->legendposition = WEST;
} else if (strcmp(optarg, "south") == 0) {
im->legendposition = SOUTH;
} else if (strcmp(optarg, "east") == 0) {
im->legendposition = EAST;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 1006:
if (strcmp(optarg, "topdown") == 0) {
im->legenddirection = TOP_DOWN;
} else if (strcmp(optarg, "bottomup") == 0) {
im->legenddirection = BOTTOM_UP;
} else if (strcmp(optarg, "bottomup2") == 0) {
im->legenddirection = BOTTOM_UP2;
} else {
rrd_set_error("unknown legend-position '%s'", optarg);
return;
}
break;
case 'F':
im->extra_flags |= FORCE_RULES_LEGEND;
break;
case 1001:
im->extra_flags |= NO_RRDTOOL_TAG;
break;
case LONGOPT_UNITS_SI:
if (im->extra_flags & FORCE_UNITS) {
rrd_set_error("--units can only be used once!");
return;
}
if (strcmp(optarg, "si") == 0)
im->extra_flags |= FORCE_UNITS_SI;
else {
rrd_set_error("invalid argument for --units: %s", optarg);
return;
}
break;
case 'X':
im->unitsexponent = atoi(optarg);
break;
case 'L':
im->unitslength = atoi(optarg);
im->forceleftspace = 1;
break;
case 'T':
if (rrd_strtodbl(optarg, 0, &(im->tabwidth), "option -T") != 2)
return;
break;
case 'S':
im->step = atoi(optarg);
break;
case 'N':
im->gridfit = 0;
break;
case 'P':
im->with_markup = 1;
break;
case 's':
if ((parsetime_error = rrd_parsetime(optarg, &start_tv))) {
rrd_set_error("start time: %s", parsetime_error);
return;
}
break;
case 'e':
if ((parsetime_error = rrd_parsetime(optarg, &end_tv))) {
rrd_set_error("end time: %s", parsetime_error);
return;
}
break;
case 'x':
if (strcmp(optarg, "none") == 0) {
im->draw_x_grid = 0;
break;
};
if (sscanf(optarg,
"%10[A-Z]:%ld:%10[A-Z]:%ld:%10[A-Z]:%ld:%ld:%n",
scan_gtm,
&im->xlab_user.gridst,
scan_mtm,
&im->xlab_user.mgridst,
scan_ltm,
&im->xlab_user.labst,
&im->xlab_user.precis, &stroff) == 7 && stroff != 0) {
im->xlab_form=strdup(optarg + stroff);
if (!im->xlab_form) {
rrd_set_error("cannot allocate memory for xlab_form");
return;
}
if ((int)
(im->xlab_user.gridtm = tmt_conv(scan_gtm)) == -1) {
rrd_set_error("unknown keyword %s", scan_gtm);
return;
} else if ((int)
(im->xlab_user.mgridtm = tmt_conv(scan_mtm))
== -1) {
rrd_set_error("unknown keyword %s", scan_mtm);
return;
} else if ((int)
(im->xlab_user.labtm = tmt_conv(scan_ltm)) == -1) {
rrd_set_error("unknown keyword %s", scan_ltm);
return;
}
im->xlab_user.minsec = 1;
im->xlab_user.stst = im->xlab_form ? im->xlab_form : "";
} else {
rrd_set_error("invalid x-grid format");
return;
}
break;
case 'y':
if (strcmp(optarg, "none") == 0) {
im->draw_y_grid = 0;
break;
};
if (sscanf(optarg, "%[-0-9.e+]:%d", double_str , &im->ylabfact) == 2) {
if (rrd_strtodbl( double_str, 0, &(im->ygridstep), "option -y") != 2){
return;
}
if (im->ygridstep <= 0) {
rrd_set_error("grid step must be > 0");
return;
} else if (im->ylabfact < 1) {
rrd_set_error("label factor must be > 0");
return;
}
} else {
rrd_set_error("invalid y-grid format");
return;
}
break;
case 1007:
im->draw_3d_border = atoi(optarg);
break;
case 1008: /* grid-dash */
if(sscanf(optarg,
"%[-0-9.e+]:%[-0-9.e+]",
double_str,
double_str2 ) != 2) {
if ( rrd_strtodbl( double_str, 0, &(im->grid_dash_on),NULL) !=2
|| rrd_strtodbl( double_str2, 0, &(im->grid_dash_off), NULL) != 2 ){
rrd_set_error("expected grid-dash format float:float");
return;
}
}
break;
case 1009: /* enable dynamic labels */
im->dynamic_labels = 1;
break;
case 1010:
strncpy(week_fmt,optarg,sizeof week_fmt);
week_fmt[(sizeof week_fmt)-1]='\0';
break;
case 1002: /* right y axis */
if(sscanf(optarg,
"%[-0-9.e+]:%[-0-9.e+]",
double_str,
double_str2 ) == 2
&& rrd_strtodbl( double_str, 0, &(im->second_axis_scale),NULL) == 2
&& rrd_strtodbl( double_str2, 0, &(im->second_axis_shift),NULL) == 2){
if(im->second_axis_scale==0){
rrd_set_error("the second_axis_scale must not be 0");
return;
}
} else {
rrd_set_error("invalid right-axis format expected scale:shift");
return;
}
break;
case 1003:
im->second_axis_legend=strdup(optarg);
if (!im->second_axis_legend) {
rrd_set_error("cannot allocate memory for second_axis_legend");
return;
}
break;
case 1004:
if (bad_format(optarg)){
rrd_set_error("use either %le or %lf formats");
return;
}
im->second_axis_format=strdup(optarg);
if (!im->second_axis_format) {
rrd_set_error("cannot allocate memory for second_axis_format");
return;
}
break;
case 1012:
if (bad_format(optarg)){
rrd_set_error("use either %le or %lf formats");
return;
}
im->primary_axis_format=strdup(optarg);
if (!im->primary_axis_format) {
rrd_set_error("cannot allocate memory for primary_axis_format");
return;
}
break;
case 'v':
im->ylegend=strdup(optarg);
if (!im->ylegend) {
rrd_set_error("cannot allocate memory for ylegend");
return;
}
break;
case 'u':
if (rrd_strtodbl(optarg, 0, &(im->maxval), "option -u") != 2){
return;
}
break;
case 'l':
if (rrd_strtodbl(optarg, 0, &(im->minval), "option -l") != 2){
return;
}
break;
case 'b':
im->base = atol(optarg);
if (im->base != 1024 && im->base != 1000) {
rrd_set_error
("the only sensible value for base apart from 1000 is 1024");
return;
}
break;
case 'w':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("width below 10 pixels");
return;
}
im->xsize = long_tmp;
break;
case 'h':
long_tmp = atol(optarg);
if (long_tmp < 10) {
rrd_set_error("height below 10 pixels");
return;
}
im->ysize = long_tmp;
break;
case 'D':
im->extra_flags |= FULL_SIZE_MODE;
break;
case 'i':
/* interlaced png not supported at the moment */
break;
case 'r':
im->rigid = 1;
break;
case 'f':
im->imginfo = optarg;
break;
case 'a':
if ((int)
(im->imgformat = if_conv(optarg)) == -1) {
rrd_set_error("unsupported graphics format '%s'", optarg);
return;
}
break;
case 1011:
if ((int)
(im->graph_type = type_conv(optarg)) == -1) {
rrd_set_error("unsupported graphics type '%s'", optarg);
return;
}
break;
case 'z':
im->lazy = 1;
break;
case 'E':
im->slopemode = 1;
break;
case 'o':
im->logarithmic = 1;
break;
case 'c':
if (sscanf(optarg,
"%10[A-Z]#%n%8lx%n",
col_nam, &col_start, &color, &col_end) == 2) {
int ci;
int col_len = col_end - col_start;
switch (col_len) {
case 3:
color =
(((color & 0xF00) * 0x110000) | ((color & 0x0F0) *
0x011000) |
((color & 0x00F)
* 0x001100)
| 0x000000FF);
break;
case 4:
color =
(((color & 0xF000) *
0x11000) | ((color & 0x0F00) *
0x01100) | ((color &
0x00F0) *
0x00110) |
((color & 0x000F) * 0x00011)
);
break;
case 6:
color = (color << 8) + 0xff /* shift left by 8 */ ;
break;
case 8:
break;
default:
rrd_set_error("the color format is #RRGGBB[AA]");
return;
}
if ((ci = grc_conv(col_nam)) != -1) {
im->graph_col[ci] = gfx_hex_to_col(color);
} else {
rrd_set_error("invalid color name '%s'", col_nam);
return;
}
} else {
rrd_set_error("invalid color def format");
return;
}
break;
case 'n':{
char prop[15];
double size = 1;
int end;
if (sscanf(optarg, "%10[A-Z]:%[-0-9.e+]%n", prop, double_str, &end) >= 2
&& rrd_strtodbl( double_str, 0, &size, NULL) == 2) {
int sindex, propidx;
if ((sindex = text_prop_conv(prop)) != -1) {
for (propidx = sindex;
propidx < TEXT_PROP_LAST; propidx++) {
if (size > 0) {
rrd_set_font_desc(im,propidx,NULL,size);
}
if ((int) strlen(optarg) > end+2) {
if (optarg[end] == ':') {
rrd_set_font_desc(im,propidx,optarg + end + 1,0);
} else {
rrd_set_error
("expected : after font size in '%s'",
optarg);
return;
}
}
/* only run the for loop for DEFAULT (0) for
all others, we break here. woodo programming */
if (propidx == sindex && sindex != 0)
break;
}
} else {
rrd_set_error("invalid fonttag '%s'", prop);
return;
}
} else {
rrd_set_error("invalid text property format");
return;
}
break;
}
case 'm':
if (rrd_strtodbl(optarg, 0, &(im->zoom), "option -m") != 2){
return;
}
if (im->zoom <= 0.0) {
rrd_set_error("zoom factor must be > 0");
return;
}
break;
case 't':
im->title=strdup(optarg);
if (!im->title) {
rrd_set_error("cannot allocate memory for title");
return;
}
break;
case 'R':
if (strcmp(optarg, "normal") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else if (strcmp(optarg, "light") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_SLIGHT);
} else if (strcmp(optarg, "mono") == 0) {
cairo_font_options_set_antialias
(im->font_options, CAIRO_ANTIALIAS_NONE);
cairo_font_options_set_hint_style
(im->font_options, CAIRO_HINT_STYLE_FULL);
} else {
rrd_set_error("unknown font-render-mode '%s'", optarg);
return;
}
break;
case 'G':
if (strcmp(optarg, "normal") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_GRAY;
else if (strcmp(optarg, "mono") == 0)
im->graph_antialias = CAIRO_ANTIALIAS_NONE;
else {
rrd_set_error("unknown graph-render-mode '%s'", optarg);
return;
}
break;
case 'B':
/* not supported curently */
break;
case 'W':
im->watermark=strdup(optarg);
if (!im->watermark) {
rrd_set_error("cannot allocate memory for watermark");
return;
}
break;
case 'd':
{
if (im->daemon_addr != NULL)
{
rrd_set_error ("You cannot specify --daemon "
"more than once.");
return;
}
im->daemon_addr = strdup(optarg);
if (im->daemon_addr == NULL)
{
rrd_set_error("strdup failed");
return;
}
break;
}
case '?':
if (optopt != 0)
rrd_set_error("unknown option '%c'", optopt);
else
rrd_set_error("unknown option '%s'", argv[optind - 1]);
return;
}
} /* while (1) */
pango_cairo_context_set_font_options(pango_layout_get_context(im->layout), im->font_options);
pango_layout_context_changed(im->layout);
if (im->logarithmic && im->minval <= 0) {
rrd_set_error
("for a logarithmic yaxis you must specify a lower-limit > 0");
return;
}
if (rrd_proc_start_end(&start_tv, &end_tv, &start_tmp, &end_tmp) == -1) {
/* error string is set in rrd_parsetime.c */
return;
}
if (start_tmp < 3600 * 24 * 365 * 10) {
rrd_set_error
("the first entry to fetch should be after 1980 (%ld)",
start_tmp);
return;
}
if (end_tmp < start_tmp) {
rrd_set_error
("start (%ld) should be less than end (%ld)", start_tmp, end_tmp);
return;
}
im->start = start_tmp;
im->end = end_tmp;
im->step = max((long) im->step, (im->end - im->start) / im->xsize);
}
int rrd_graph_color(
image_desc_t
*im,
char *var,
char *err,
int optional)
{
char *color;
graph_desc_t *gdp = &im->gdes[im->gdes_c - 1];
color = strstr(var, "#");
if (color == NULL) {
if (optional == 0) {
rrd_set_error("Found no color in %s", err);
return 0;
}
return 0;
} else {
int n = 0;
char *rest;
long unsigned int col;
rest = strstr(color, ":");
if (rest != NULL)
n = rest - color;
else
n = strlen(color);
switch (n) {
case 7:
sscanf(color, "#%6lx%n", &col, &n);
col = (col << 8) + 0xff /* shift left by 8 */ ;
if (n != 7)
rrd_set_error("Color problem in %s", err);
break;
case 9:
sscanf(color, "#%8lx%n", &col, &n);
if (n == 9)
break;
default:
rrd_set_error("Color problem in %s", err);
}
if (rrd_test_error())
return 0;
gdp->col = gfx_hex_to_col(col);
return n;
}
}
int bad_format(
char *fmt)
{
char *ptr;
int n = 0;
ptr = fmt;
while (*ptr != '\0')
if (*ptr++ == '%') {
/* line cannot end with percent char */
if (*ptr == '\0')
return 1;
/* '%s', '%S' and '%%' are allowed */
if (*ptr == 's' || *ptr == 'S' || *ptr == '%')
ptr++;
/* %c is allowed (but use only with vdef!) */
else if (*ptr == 'c') {
ptr++;
n = 1;
}
/* or else '% 6.2lf' and such are allowed */
else {
/* optional padding character */
if (*ptr == ' ' || *ptr == '+' || *ptr == '-')
ptr++;
/* This should take care of 'm.n' with all three optional */
while (*ptr >= '0' && *ptr <= '9')
ptr++;
if (*ptr == '.')
ptr++;
while (*ptr >= '0' && *ptr <= '9')
ptr++;
/* Either 'le', 'lf' or 'lg' must follow here */
if (*ptr++ != 'l')
return 1;
if (*ptr == 'e' || *ptr == 'f' || *ptr == 'g')
ptr++;
else
return 1;
n++;
}
}
return (n != 1);
}
int bad_format_imginfo(
char *fmt)
{
char *ptr;
int n = 0;
ptr = fmt;
while (*ptr != '\0')
if (*ptr++ == '%') {
/* line cannot end with percent char */
if (*ptr == '\0')
return 1;
/* '%%' is allowed */
if (*ptr == '%')
ptr++;
/* '%s', '%S' are allowed */
else if (*ptr == 's' || *ptr == 'S') {
n = 1;
ptr++;
}
/* or else '% 4lu' and such are allowed */
else {
/* optional padding character */
if (*ptr == ' ')
ptr++;
/* This should take care of 'm' */
while (*ptr >= '0' && *ptr <= '9')
ptr++;
/* 'lu' must follow here */
if (*ptr++ != 'l')
return 1;
if (*ptr == 'u')
ptr++;
else
return 1;
n++;
}
}
return (n != 3);
}
int vdef_parse(
struct graph_desc_t
*gdes,
const char *const str)
{
/* A VDEF currently is either "func" or "param,func"
* so the parsing is rather simple. Change if needed.
*/
double param;
char func[30], double_str[21];
int n;
n = 0;
sscanf(str, "%20[-0-9.e+],%29[A-Z]%n", double_str, func, &n);
if ( rrd_strtodbl( double_str, NULL, ¶m, NULL) != 2 ){
n = 0;
sscanf(str, "%29[A-Z]%n", func, &n);
if (n == (int) strlen(str)) { /* matched */
param = DNAN;
} else {
rrd_set_error
("Unknown function string '%s' in VDEF '%s'",
str, gdes->vname);
return -1;
}
}
if (!strcmp("PERCENT", func))
gdes->vf.op = VDEF_PERCENT;
else if (!strcmp("PERCENTNAN", func))
gdes->vf.op = VDEF_PERCENTNAN;
else if (!strcmp("MAXIMUM", func))
gdes->vf.op = VDEF_MAXIMUM;
else if (!strcmp("AVERAGE", func))
gdes->vf.op = VDEF_AVERAGE;
else if (!strcmp("STDEV", func))
gdes->vf.op = VDEF_STDEV;
else if (!strcmp("MINIMUM", func))
gdes->vf.op = VDEF_MINIMUM;
else if (!strcmp("TOTAL", func))
gdes->vf.op = VDEF_TOTAL;
else if (!strcmp("FIRST", func))
gdes->vf.op = VDEF_FIRST;
else if (!strcmp("LAST", func))
gdes->vf.op = VDEF_LAST;
else if (!strcmp("LSLSLOPE", func))
gdes->vf.op = VDEF_LSLSLOPE;
else if (!strcmp("LSLINT", func))
gdes->vf.op = VDEF_LSLINT;
else if (!strcmp("LSLCORREL", func))
gdes->vf.op = VDEF_LSLCORREL;
else {
rrd_set_error
("Unknown function '%s' in VDEF '%s'\n", func, gdes->vname);
return -1;
};
switch (gdes->vf.op) {
case VDEF_PERCENT:
case VDEF_PERCENTNAN:
if (isnan(param)) { /* no parameter given */
rrd_set_error
("Function '%s' needs parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
if (param >= 0.0 && param <= 100.0) {
gdes->vf.param = param;
gdes->vf.val = DNAN; /* undefined */
gdes->vf.when = 0; /* undefined */
gdes->vf.never = 1;
} else {
rrd_set_error
("Parameter '%f' out of range in VDEF '%s'\n",
param, gdes->vname);
return -1;
};
break;
case VDEF_MAXIMUM:
case VDEF_AVERAGE:
case VDEF_STDEV:
case VDEF_MINIMUM:
case VDEF_TOTAL:
case VDEF_FIRST:
case VDEF_LAST:
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:
if (isnan(param)) {
gdes->vf.param = DNAN;
gdes->vf.val = DNAN;
gdes->vf.when = 0;
gdes->vf.never = 1;
} else {
rrd_set_error
("Function '%s' needs no parameter in VDEF '%s'\n",
func, gdes->vname);
return -1;
};
break;
};
return 0;
}
int vdef_calc(
image_desc_t *im,
int gdi)
{
graph_desc_t *src, *dst;
rrd_value_t *data;
long step, steps;
dst = &im->gdes[gdi];
src = &im->gdes[dst->vidx];
data = src->data + src->ds;
steps = (src->end - src->start) / src->step;
#if 0
printf
("DEBUG: start == %lu, end == %lu, %lu steps\n",
src->start, src->end, steps);
#endif
switch (dst->vf.op) {
case VDEF_PERCENT:{
rrd_value_t *array;
int field;
if ((array = (rrd_value_t*)malloc(steps * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
for (step = 0; step < steps; step++) {
array[step] = data[step * src->ds_cnt];
}
qsort(array, step, sizeof(double), vdef_percent_compar);
field = round((dst->vf.param * (double)(steps - 1)) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
free(array);
#if 0
for (step = 0; step < steps; step++)
printf("DEBUG: %3li:%10.2f %c\n",
step, array[step], step == field ? '*' : ' ');
#endif
}
break;
case VDEF_PERCENTNAN:{
rrd_value_t *array;
int field;
/* count number of "valid" values */
int nancount=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) { nancount++; }
}
/* and allocate it */
if ((array = (rrd_value_t*)malloc(nancount * sizeof(double))) == NULL) {
rrd_set_error("malloc VDEV_PERCENT");
return -1;
}
/* and fill it in */
field=0;
for (step = 0; step < steps; step++) {
if (!isnan(data[step * src->ds_cnt])) {
array[field] = data[step * src->ds_cnt];
field++;
}
}
qsort(array, nancount, sizeof(double), vdef_percent_compar);
field = round( dst->vf.param * (double)(nancount - 1) / 100.0);
dst->vf.val = array[field];
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
free(array);
}
break;
case VDEF_MAXIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] > dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
}
step++;
}
break;
case VDEF_TOTAL:
case VDEF_STDEV:
case VDEF_AVERAGE:{
int cnt = 0;
double sum = 0.0;
double average = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += data[step * src->ds_cnt];
cnt++;
};
}
if (cnt) {
if (dst->vf.op == VDEF_TOTAL) {
dst->vf.val = sum * src->step;
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
} else if (dst->vf.op == VDEF_AVERAGE) {
dst->vf.val = sum / cnt;
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
} else {
average = sum / cnt;
sum = 0.0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
sum += pow((data[step * src->ds_cnt] - average), 2.0);
};
}
dst->vf.val = pow(sum / cnt, 0.5);
dst->vf.when = 0; /* no time component */
dst->vf.never = 1;
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
}
}
break;
case VDEF_MINIMUM:
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
while (step != steps) {
if (finite(data[step * src->ds_cnt])) {
if (data[step * src->ds_cnt] < dst->vf.val) {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
}
step++;
}
break;
case VDEF_FIRST:
/* The time value returned here is one step before the
* actual time value. This is the start of the first
* non-NaN interval.
*/
step = 0;
while (step != steps && isnan(data[step * src->ds_cnt]))
step++;
if (step == steps) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + step * src->step;
dst->vf.never = 0;
}
break;
case VDEF_LAST:
/* The time value returned here is the
* actual time value. This is the end of the last
* non-NaN interval.
*/
step = steps - 1;
while (step >= 0 && isnan(data[step * src->ds_cnt]))
step--;
if (step < 0) { /* all entries were NaN */
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
} else {
dst->vf.val = data[step * src->ds_cnt];
dst->vf.when = src->start + (step + 1) * src->step;
dst->vf.never = 0;
}
break;
case VDEF_LSLSLOPE:
case VDEF_LSLINT:
case VDEF_LSLCORREL:{
/* Bestfit line by linear least squares method */
int cnt = 0;
double SUMx, SUMy, SUMxy, SUMxx, SUMyy, slope, y_intercept, correl;
SUMx = 0;
SUMy = 0;
SUMxy = 0;
SUMxx = 0;
SUMyy = 0;
for (step = 0; step < steps; step++) {
if (finite(data[step * src->ds_cnt])) {
cnt++;
SUMx += step;
SUMxx += step * step;
SUMxy += step * data[step * src->ds_cnt];
SUMy += data[step * src->ds_cnt];
SUMyy += data[step * src->ds_cnt] * data[step * src->ds_cnt];
};
}
slope = (SUMx * SUMy - cnt * SUMxy) / (SUMx * SUMx - cnt * SUMxx);
y_intercept = (SUMy - slope * SUMx) / cnt;
correl =
(SUMxy -
(SUMx * SUMy) / cnt) /
sqrt((SUMxx -
(SUMx * SUMx) / cnt) * (SUMyy - (SUMy * SUMy) / cnt));
if (cnt) {
if (dst->vf.op == VDEF_LSLSLOPE) {
dst->vf.val = slope;
dst->vf.when = 0;
dst->vf.never = 1;
} else if (dst->vf.op == VDEF_LSLINT) {
dst->vf.val = y_intercept;
dst->vf.when = 0;
dst->vf.never = 1;
} else if (dst->vf.op == VDEF_LSLCORREL) {
dst->vf.val = correl;
dst->vf.when = 0;
dst->vf.never = 1;
};
} else {
dst->vf.val = DNAN;
dst->vf.when = 0;
dst->vf.never = 1;
}
}
break;
}
return 0;
}
/* NaN < -INF < finite_values < INF */
int vdef_percent_compar(
const void
*a,
const void
*b)
{
/* Equality is not returned; this doesn't hurt except
* (maybe) for a little performance.
*/
/* First catch NaN values. They are smallest */
if (isnan(*(double *) a))
return -1;
if (isnan(*(double *) b))
return 1;
/* NaN doesn't reach this part so INF and -INF are extremes.
* The sign from isinf() is compatible with the sign we return
*/
if (isinf(*(double *) a))
return isinf(*(double *) a);
if (isinf(*(double *) b))
return isinf(*(double *) b);
/* If we reach this, both values must be finite */
if (*(double *) a < *(double *) b)
return -1;
else
return 1;
}
void grinfo_push(
image_desc_t *im,
char *key,
rrd_info_type_t type,
rrd_infoval_t value)
{
im->grinfo_current = rrd_info_push(im->grinfo_current, key, type, value);
if (im->grinfo == NULL) {
im->grinfo = im->grinfo_current;
}
}
void time_clean(
char *result,
char *format)
{
int j, jj;
/* Handling based on
- ANSI C99 Specifications http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
- Single UNIX Specification version 2 http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html
- POSIX:2001/Single UNIX Specification version 3 http://www.opengroup.org/onlinepubs/009695399/functions/strftime.html
- POSIX:2008 Specifications http://www.opengroup.org/onlinepubs/9699919799/functions/strftime.html
Specifications tells
"If a conversion specifier is not one of the above, the behavior is undefined."
C99 tells
"A conversion specifier consists of a % character, possibly followed by an E or O modifier character (described below), followed by a character that determines the behavior of the conversion specifier.
POSIX:2001 tells
"A conversion specification consists of a '%' character, possibly followed by an E or O modifier, and a terminating conversion specifier character that determines the conversion specification's behavior."
POSIX:2008 introduce more complexe behavior that are not handled here.
According to this, this code will replace:
- % followed by @ by a %@
- % followed by by a %SPACE
- % followed by . by a %.
- % followed by % by a %
- % followed by t by a TAB
- % followed by E then anything by '-'
- % followed by O then anything by '-'
- % followed by anything else by at least one '-'. More characters may be added to better fit expected output length
*/
jj = 0;
for(j = 0; (j < FMT_LEG_LEN - 1) && (jj < FMT_LEG_LEN); j++) { /* we don't need to parse the last char */
if (format[j] == '%') {
if ((format[j+1] == 'E') || (format[j+1] == 'O')) {
result[jj++] = '-';
j+=2; /* We skip next 2 following char */
} else if ((format[j+1] == 'C') || (format[j+1] == 'd') ||
(format[j+1] == 'g') || (format[j+1] == 'H') ||
(format[j+1] == 'I') || (format[j+1] == 'm') ||
(format[j+1] == 'M') || (format[j+1] == 'S') ||
(format[j+1] == 'U') || (format[j+1] == 'V') ||
(format[j+1] == 'W') || (format[j+1] == 'y')) {
result[jj++] = '-';
if (jj < FMT_LEG_LEN) {
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'j') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if ((format[j+1] == 'G') || (format[j+1] == 'Y')) {
/* Assuming Year on 4 digit */
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 2) {
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'R') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 3) {
result[jj++] = '-';
result[jj++] = ':';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'T') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 6) {
result[jj++] = '-';
result[jj++] = ':';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = ':';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'F') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 8) {
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'D') {
result[jj++] = '-';
if (jj < FMT_LEG_LEN - 6) {
result[jj++] = '-';
result[jj++] = '/';
result[jj++] = '-';
result[jj++] = '-';
result[jj++] = '/';
result[jj++] = '-';
result[jj++] = '-';
}
j++; /* We skip the following char */
} else if (format[j+1] == 'n') {
result[jj++] = '\r';
result[jj++] = '\n';
j++; /* We skip the following char */
} else if (format[j+1] == 't') {
result[jj++] = '\t';
j++; /* We skip the following char */
} else if (format[j+1] == '%') {
result[jj++] = '%';
j++; /* We skip the following char */
} else if (format[j+1] == ' ') {
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '%';
result[jj++] = ' ';
}
j++; /* We skip the following char */
} else if (format[j+1] == '.') {
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '%';
result[jj++] = '.';
}
j++; /* We skip the following char */
} else if (format[j+1] == '@') {
if (jj < FMT_LEG_LEN - 1) {
result[jj++] = '%';
result[jj++] = '@';
}
j++; /* We skip the following char */
} else {
result[jj++] = '-';
j++; /* We skip the following char */
}
} else {
result[jj++] = format[j];
}
}
result[jj] = '\0'; /* We must force the end of the string */
}
| ./CrossVul/dataset_final_sorted/CWE-134/c/bad_2265_0 |
crossvul-cpp_data_good_1792_0 | /*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) 1998-2015 Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@zend.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
| Dmitry Stogov <dmitry@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include <signal.h>
#include "zend.h"
#include "zend_compile.h"
#include "zend_execute.h"
#include "zend_API.h"
#include "zend_stack.h"
#include "zend_constants.h"
#include "zend_extensions.h"
#include "zend_exceptions.h"
#include "zend_closures.h"
#include "zend_generators.h"
#include "zend_vm.h"
#include "zend_float.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
ZEND_API void (*zend_execute_ex)(zend_execute_data *execute_data);
ZEND_API void (*zend_execute_internal)(zend_execute_data *execute_data, zval *return_value);
/* true globals */
ZEND_API const zend_fcall_info empty_fcall_info = { 0, NULL, {{0}, {{0}}, {0}}, NULL, NULL, NULL, NULL, 0, 0 };
ZEND_API const zend_fcall_info_cache empty_fcall_info_cache = { 0, NULL, NULL, NULL, NULL };
#ifdef ZEND_WIN32
ZEND_TLS HANDLE tq_timer = NULL;
#endif
#if 0&&ZEND_DEBUG
static void (*original_sigsegv_handler)(int);
static void zend_handle_sigsegv(int dummy) /* {{{ */
{
fflush(stdout);
fflush(stderr);
if (original_sigsegv_handler == zend_handle_sigsegv) {
signal(SIGSEGV, original_sigsegv_handler);
} else {
signal(SIGSEGV, SIG_DFL);
}
{
fprintf(stderr, "SIGSEGV caught on opcode %d on opline %d of %s() at %s:%d\n\n",
active_opline->opcode,
active_opline-EG(active_op_array)->opcodes,
get_active_function_name(),
zend_get_executed_filename(),
zend_get_executed_lineno());
/* See http://support.microsoft.com/kb/190351 */
#ifdef ZEND_WIN32
fflush(stderr);
#endif
}
if (original_sigsegv_handler!=zend_handle_sigsegv) {
original_sigsegv_handler(dummy);
}
}
/* }}} */
#endif
static void zend_extension_activator(zend_extension *extension) /* {{{ */
{
if (extension->activate) {
extension->activate();
}
}
/* }}} */
static void zend_extension_deactivator(zend_extension *extension) /* {{{ */
{
if (extension->deactivate) {
extension->deactivate();
}
}
/* }}} */
static int clean_non_persistent_function(zval *zv) /* {{{ */
{
zend_function *function = Z_PTR_P(zv);
return (function->type == ZEND_INTERNAL_FUNCTION) ? ZEND_HASH_APPLY_STOP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
ZEND_API int clean_non_persistent_function_full(zval *zv) /* {{{ */
{
zend_function *function = Z_PTR_P(zv);
return (function->type == ZEND_INTERNAL_FUNCTION) ? ZEND_HASH_APPLY_KEEP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
static int clean_non_persistent_class(zval *zv) /* {{{ */
{
zend_class_entry *ce = Z_PTR_P(zv);
return (ce->type == ZEND_INTERNAL_CLASS) ? ZEND_HASH_APPLY_STOP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
ZEND_API int clean_non_persistent_class_full(zval *zv) /* {{{ */
{
zend_class_entry *ce = Z_PTR_P(zv);
return (ce->type == ZEND_INTERNAL_CLASS) ? ZEND_HASH_APPLY_KEEP : ZEND_HASH_APPLY_REMOVE;
}
/* }}} */
void init_executor(void) /* {{{ */
{
zend_init_fpu();
ZVAL_NULL(&EG(uninitialized_zval));
ZVAL_NULL(&EG(error_zval));
/* destroys stack frame, therefore makes core dumps worthless */
#if 0&&ZEND_DEBUG
original_sigsegv_handler = signal(SIGSEGV, zend_handle_sigsegv);
#endif
EG(symtable_cache_ptr) = EG(symtable_cache) - 1;
EG(symtable_cache_limit) = EG(symtable_cache) + SYMTABLE_CACHE_SIZE - 1;
EG(no_extensions) = 0;
EG(function_table) = CG(function_table);
EG(class_table) = CG(class_table);
EG(in_autoload) = NULL;
EG(autoload_func) = NULL;
EG(error_handling) = EH_NORMAL;
zend_vm_stack_init();
zend_hash_init(&EG(symbol_table), 64, NULL, ZVAL_PTR_DTOR, 0);
EG(valid_symbol_table) = 1;
zend_llist_apply(&zend_extensions, (llist_apply_func_t) zend_extension_activator);
zend_hash_init(&EG(included_files), 8, NULL, NULL, 0);
EG(ticks_count) = 0;
ZVAL_UNDEF(&EG(user_error_handler));
EG(current_execute_data) = NULL;
zend_stack_init(&EG(user_error_handlers_error_reporting), sizeof(int));
zend_stack_init(&EG(user_error_handlers), sizeof(zval));
zend_stack_init(&EG(user_exception_handlers), sizeof(zval));
zend_objects_store_init(&EG(objects_store), 1024);
EG(full_tables_cleanup) = 0;
#ifdef ZEND_WIN32
EG(timed_out) = 0;
#endif
EG(exception) = NULL;
EG(prev_exception) = NULL;
EG(scope) = NULL;
EG(ht_iterators_count) = sizeof(EG(ht_iterators_slots)) / sizeof(HashTableIterator);
EG(ht_iterators_used) = 0;
EG(ht_iterators) = EG(ht_iterators_slots);
memset(EG(ht_iterators), 0, sizeof(EG(ht_iterators_slots)));
EG(active) = 1;
}
/* }}} */
static int zval_call_destructor(zval *zv) /* {{{ */
{
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zv = Z_INDIRECT_P(zv);
}
if (Z_TYPE_P(zv) == IS_OBJECT && Z_REFCOUNT_P(zv) == 1) {
return ZEND_HASH_APPLY_REMOVE;
} else {
return ZEND_HASH_APPLY_KEEP;
}
}
/* }}} */
static void zend_unclean_zval_ptr_dtor(zval *zv) /* {{{ */
{
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zv = Z_INDIRECT_P(zv);
}
i_zval_ptr_dtor(zv ZEND_FILE_LINE_CC);
}
/* }}} */
static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */
{
va_list va;
char *message = NULL;
va_start(va, format);
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
zend_throw_error(exception_ce, "%s", message);
} else {
zend_error(E_ERROR, "%s", message);
}
efree(message);
va_end(va);
}
/* }}} */
void shutdown_destructors(void) /* {{{ */
{
if (CG(unclean_shutdown)) {
EG(symbol_table).pDestructor = zend_unclean_zval_ptr_dtor;
}
zend_try {
uint32_t symbols;
do {
symbols = zend_hash_num_elements(&EG(symbol_table));
zend_hash_reverse_apply(&EG(symbol_table), (apply_func_t) zval_call_destructor);
} while (symbols != zend_hash_num_elements(&EG(symbol_table)));
zend_objects_store_call_destructors(&EG(objects_store));
} zend_catch {
/* if we couldn't destruct cleanly, mark all objects as destructed anyway */
zend_objects_store_mark_destructed(&EG(objects_store));
} zend_end_try();
}
/* }}} */
void shutdown_executor(void) /* {{{ */
{
zend_function *func;
zend_class_entry *ce;
zend_try {
/* Removed because this can not be safely done, e.g. in this situation:
Object 1 creates object 2
Object 3 holds reference to object 2.
Now when 1 and 2 are destroyed, 3 can still access 2 in its destructor, with
very problematic results */
/* zend_objects_store_call_destructors(&EG(objects_store)); */
/* Moved after symbol table cleaners, because some of the cleaners can call
destructors, which would use EG(symtable_cache_ptr) and thus leave leaks */
/* while (EG(symtable_cache_ptr)>=EG(symtable_cache)) {
zend_hash_destroy(*EG(symtable_cache_ptr));
efree(*EG(symtable_cache_ptr));
EG(symtable_cache_ptr)--;
}
*/
zend_llist_apply(&zend_extensions, (llist_apply_func_t) zend_extension_deactivator);
if (CG(unclean_shutdown)) {
EG(symbol_table).pDestructor = zend_unclean_zval_ptr_dtor;
}
zend_hash_graceful_reverse_destroy(&EG(symbol_table));
} zend_end_try();
EG(valid_symbol_table) = 0;
zend_try {
zval *zeh;
/* remove error handlers before destroying classes and functions,
* so that if handler used some class, crash would not happen */
if (Z_TYPE(EG(user_error_handler)) != IS_UNDEF) {
zeh = &EG(user_error_handler);
zval_ptr_dtor(zeh);
ZVAL_UNDEF(&EG(user_error_handler));
}
if (Z_TYPE(EG(user_exception_handler)) != IS_UNDEF) {
zeh = &EG(user_exception_handler);
zval_ptr_dtor(zeh);
ZVAL_UNDEF(&EG(user_exception_handler));
}
zend_stack_clean(&EG(user_error_handlers_error_reporting), NULL, 1);
zend_stack_clean(&EG(user_error_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1);
zend_stack_clean(&EG(user_exception_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1);
} zend_end_try();
zend_try {
/* Cleanup static data for functions and arrays.
* We need a separate cleanup stage because of the following problem:
* Suppose we destroy class X, which destroys the class's function table,
* and in the function table we have function foo() that has static $bar.
* Now if an object of class X is assigned to $bar, its destructor will be
* called and will fail since X's function table is in mid-destruction.
* So we want first of all to clean up all data and then move to tables destruction.
* Note that only run-time accessed data need to be cleaned up, pre-defined data can
* not contain objects and thus are not probelmatic */
if (EG(full_tables_cleanup)) {
ZEND_HASH_FOREACH_PTR(EG(function_table), func) {
if (func->type == ZEND_USER_FUNCTION) {
zend_cleanup_op_array_data((zend_op_array *) func);
}
} ZEND_HASH_FOREACH_END();
ZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) {
if (ce->type == ZEND_USER_CLASS) {
zend_cleanup_user_class_data(ce);
} else {
zend_cleanup_internal_class_data(ce);
}
} ZEND_HASH_FOREACH_END();
} else {
ZEND_HASH_REVERSE_FOREACH_PTR(EG(function_table), func) {
if (func->type != ZEND_USER_FUNCTION) {
break;
}
zend_cleanup_op_array_data((zend_op_array *) func);
} ZEND_HASH_FOREACH_END();
ZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) {
if (ce->type != ZEND_USER_CLASS) {
break;
}
zend_cleanup_user_class_data(ce);
} ZEND_HASH_FOREACH_END();
zend_cleanup_internal_classes();
}
} zend_end_try();
zend_try {
zend_llist_destroy(&CG(open_files));
} zend_end_try();
zend_try {
zend_close_rsrc_list(&EG(regular_list));
} zend_end_try();
#if ZEND_DEBUG
if (GC_G(gc_enabled) && !CG(unclean_shutdown)) {
gc_collect_cycles();
}
#endif
zend_try {
zend_objects_store_free_object_storage(&EG(objects_store));
zend_vm_stack_destroy();
/* Destroy all op arrays */
if (EG(full_tables_cleanup)) {
zend_hash_reverse_apply(EG(function_table), clean_non_persistent_function_full);
zend_hash_reverse_apply(EG(class_table), clean_non_persistent_class_full);
} else {
zend_hash_reverse_apply(EG(function_table), clean_non_persistent_function);
zend_hash_reverse_apply(EG(class_table), clean_non_persistent_class);
}
while (EG(symtable_cache_ptr)>=EG(symtable_cache)) {
zend_hash_destroy(*EG(symtable_cache_ptr));
FREE_HASHTABLE(*EG(symtable_cache_ptr));
EG(symtable_cache_ptr)--;
}
} zend_end_try();
zend_try {
clean_non_persistent_constants();
} zend_end_try();
zend_try {
#if 0&&ZEND_DEBUG
signal(SIGSEGV, original_sigsegv_handler);
#endif
zend_hash_destroy(&EG(included_files));
zend_stack_destroy(&EG(user_error_handlers_error_reporting));
zend_stack_destroy(&EG(user_error_handlers));
zend_stack_destroy(&EG(user_exception_handlers));
zend_objects_store_destroy(&EG(objects_store));
if (EG(in_autoload)) {
zend_hash_destroy(EG(in_autoload));
FREE_HASHTABLE(EG(in_autoload));
}
} zend_end_try();
zend_shutdown_fpu();
EG(ht_iterators_used) = 0;
if (EG(ht_iterators) != EG(ht_iterators_slots)) {
efree(EG(ht_iterators));
}
EG(active) = 0;
}
/* }}} */
/* return class name and "::" or "". */
ZEND_API const char *get_active_class_name(const char **space) /* {{{ */
{
zend_function *func;
if (!zend_is_executing()) {
if (space) {
*space = "";
}
return "";
}
func = EG(current_execute_data)->func;
switch (func->type) {
case ZEND_USER_FUNCTION:
case ZEND_INTERNAL_FUNCTION:
{
zend_class_entry *ce = func->common.scope;
if (space) {
*space = ce ? "::" : "";
}
return ce ? ZSTR_VAL(ce->name) : "";
}
default:
if (space) {
*space = "";
}
return "";
}
}
/* }}} */
ZEND_API const char *get_active_function_name(void) /* {{{ */
{
zend_function *func;
if (!zend_is_executing()) {
return NULL;
}
func = EG(current_execute_data)->func;
switch (func->type) {
case ZEND_USER_FUNCTION: {
zend_string *function_name = func->common.function_name;
if (function_name) {
return ZSTR_VAL(function_name);
} else {
return "main";
}
}
break;
case ZEND_INTERNAL_FUNCTION:
return ZSTR_VAL(func->common.function_name);
break;
default:
return NULL;
}
}
/* }}} */
ZEND_API const char *zend_get_executed_filename(void) /* {{{ */
{
zend_execute_data *ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
ex = ex->prev_execute_data;
}
if (ex) {
return ZSTR_VAL(ex->func->op_array.filename);
} else {
return "[no active file]";
}
}
/* }}} */
ZEND_API zend_string *zend_get_executed_filename_ex(void) /* {{{ */
{
zend_execute_data *ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
ex = ex->prev_execute_data;
}
if (ex) {
return ex->func->op_array.filename;
} else {
return NULL;
}
}
/* }}} */
ZEND_API uint zend_get_executed_lineno(void) /* {{{ */
{
zend_execute_data *ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
ex = ex->prev_execute_data;
}
if (ex) {
if (EG(exception) && ex->opline->opcode == ZEND_HANDLE_EXCEPTION &&
ex->opline->lineno == 0 && EG(opline_before_exception)) {
return EG(opline_before_exception)->lineno;
}
return ex->opline->lineno;
} else {
return 0;
}
}
/* }}} */
ZEND_API zend_bool zend_is_executing(void) /* {{{ */
{
return EG(current_execute_data) != 0;
}
/* }}} */
ZEND_API void _zval_ptr_dtor(zval *zval_ptr ZEND_FILE_LINE_DC) /* {{{ */
{
i_zval_ptr_dtor(zval_ptr ZEND_FILE_LINE_RELAY_CC);
}
/* }}} */
ZEND_API void _zval_internal_ptr_dtor(zval *zval_ptr ZEND_FILE_LINE_DC) /* {{{ */
{
if (Z_REFCOUNTED_P(zval_ptr)) {
Z_DELREF_P(zval_ptr);
if (Z_REFCOUNT_P(zval_ptr) == 0) {
_zval_internal_dtor_for_ptr(zval_ptr ZEND_FILE_LINE_CC);
}
}
}
/* }}} */
#define IS_VISITED_CONSTANT 0x80
#define IS_CONSTANT_VISITED(p) (Z_TYPE_P(p) & IS_VISITED_CONSTANT)
#define MARK_CONSTANT_VISITED(p) Z_TYPE_INFO_P(p) |= IS_VISITED_CONSTANT
#define RESET_CONSTANT_VISITED(p) Z_TYPE_INFO_P(p) &= ~IS_VISITED_CONSTANT
ZEND_API int zval_update_constant_ex(zval *p, zend_bool inline_change, zend_class_entry *scope) /* {{{ */
{
zval *const_value;
char *colon;
if (IS_CONSTANT_VISITED(p)) {
zend_throw_error(NULL, "Cannot declare self-referencing constant '%s'", Z_STRVAL_P(p));
return FAILURE;
} else if (Z_TYPE_P(p) == IS_CONSTANT) {
SEPARATE_ZVAL_NOREF(p);
MARK_CONSTANT_VISITED(p);
if (Z_CONST_FLAGS_P(p) & IS_CONSTANT_CLASS) {
ZEND_ASSERT(EG(current_execute_data));
if (inline_change) {
zend_string_release(Z_STR_P(p));
}
if (EG(scope) && EG(scope)->name) {
ZVAL_STR_COPY(p, EG(scope)->name);
} else {
ZVAL_EMPTY_STRING(p);
}
} else if (UNEXPECTED((const_value = zend_get_constant_ex(Z_STR_P(p), scope, Z_CONST_FLAGS_P(p))) == NULL)) {
char *actual = Z_STRVAL_P(p);
if (UNEXPECTED(EG(exception))) {
RESET_CONSTANT_VISITED(p);
return FAILURE;
} else if ((colon = (char*)zend_memrchr(Z_STRVAL_P(p), ':', Z_STRLEN_P(p)))) {
zend_throw_error(NULL, "Undefined class constant '%s'", Z_STRVAL_P(p));
RESET_CONSTANT_VISITED(p);
return FAILURE;
} else {
zend_string *save = Z_STR_P(p);
char *slash;
size_t actual_len = Z_STRLEN_P(p);
if ((Z_CONST_FLAGS_P(p) & IS_CONSTANT_UNQUALIFIED) && (slash = (char *)zend_memrchr(actual, '\\', actual_len))) {
actual = slash + 1;
actual_len -= (actual - Z_STRVAL_P(p));
if (inline_change) {
zend_string *s = zend_string_init(actual, actual_len, 0);
Z_STR_P(p) = s;
Z_TYPE_FLAGS_P(p) = IS_TYPE_REFCOUNTED | IS_TYPE_COPYABLE;
}
}
if (actual[0] == '\\') {
if (inline_change) {
memmove(Z_STRVAL_P(p), Z_STRVAL_P(p)+1, Z_STRLEN_P(p));
--Z_STRLEN_P(p);
} else {
++actual;
}
--actual_len;
}
if ((Z_CONST_FLAGS_P(p) & IS_CONSTANT_UNQUALIFIED) == 0) {
if (ZSTR_VAL(save)[0] == '\\') {
zend_throw_error(NULL, "Undefined constant '%s'", ZSTR_VAL(save) + 1);
} else {
zend_throw_error(NULL, "Undefined constant '%s'", ZSTR_VAL(save));
}
if (inline_change) {
zend_string_release(save);
}
RESET_CONSTANT_VISITED(p);
return FAILURE;
} else {
zend_error(E_NOTICE, "Use of undefined constant %s - assumed '%s'", actual, actual);
if (!inline_change) {
ZVAL_STRINGL(p, actual, actual_len);
} else {
Z_TYPE_INFO_P(p) = Z_REFCOUNTED_P(p) ?
IS_STRING_EX : IS_INTERNED_STRING_EX;
if (save && ZSTR_VAL(save) != actual) {
zend_string_release(save);
}
}
}
}
} else {
if (inline_change) {
zend_string_release(Z_STR_P(p));
}
ZVAL_COPY_VALUE(p, const_value);
if (Z_OPT_CONSTANT_P(p)) {
if (UNEXPECTED(zval_update_constant_ex(p, 1, NULL) != SUCCESS)) {
RESET_CONSTANT_VISITED(p);
return FAILURE;
}
}
zval_opt_copy_ctor(p);
}
} else if (Z_TYPE_P(p) == IS_CONSTANT_AST) {
zval tmp;
if (UNEXPECTED(zend_ast_evaluate(&tmp, Z_ASTVAL_P(p), scope) != SUCCESS)) {
return FAILURE;
}
if (inline_change) {
zval_ptr_dtor(p);
}
ZVAL_COPY_VALUE(p, &tmp);
}
return SUCCESS;
}
/* }}} */
ZEND_API int zval_update_constant(zval *pp, zend_bool inline_change) /* {{{ */
{
return zval_update_constant_ex(pp, inline_change, NULL);
}
/* }}} */
int call_user_function(HashTable *function_table, zval *object, zval *function_name, zval *retval_ptr, uint32_t param_count, zval params[]) /* {{{ */
{
return call_user_function_ex(function_table, object, function_name, retval_ptr, param_count, params, 1, NULL);
}
/* }}} */
int call_user_function_ex(HashTable *function_table, zval *object, zval *function_name, zval *retval_ptr, uint32_t param_count, zval params[], int no_separation, zend_array *symbol_table) /* {{{ */
{
zend_fcall_info fci;
fci.size = sizeof(fci);
fci.function_table = function_table;
fci.object = object ? Z_OBJ_P(object) : NULL;
ZVAL_COPY_VALUE(&fci.function_name, function_name);
fci.retval = retval_ptr;
fci.param_count = param_count;
fci.params = params;
fci.no_separation = (zend_bool) no_separation;
fci.symbol_table = symbol_table;
return zend_call_function(&fci, NULL);
}
/* }}} */
int zend_call_function(zend_fcall_info *fci, zend_fcall_info_cache *fci_cache) /* {{{ */
{
uint32_t i;
zend_class_entry *calling_scope = NULL;
zend_execute_data *call, dummy_execute_data;
zend_fcall_info_cache fci_cache_local;
zend_function *func;
zend_class_entry *orig_scope;
ZVAL_UNDEF(fci->retval);
if (!EG(active)) {
return FAILURE; /* executor is already inactive */
}
if (EG(exception)) {
return FAILURE; /* we would result in an instable executor otherwise */
}
switch (fci->size) {
case sizeof(zend_fcall_info):
break; /* nothing to do currently */
default:
zend_error_noreturn(E_CORE_ERROR, "Corrupted fcall_info provided to zend_call_function()");
break;
}
orig_scope = EG(scope);
/* Initialize execute_data */
if (!EG(current_execute_data)) {
/* This only happens when we're called outside any execute()'s
* It shouldn't be strictly necessary to NULL execute_data out,
* but it may make bugs easier to spot
*/
memset(&dummy_execute_data, 0, sizeof(zend_execute_data));
EG(current_execute_data) = &dummy_execute_data;
} else if (EG(current_execute_data)->func &&
ZEND_USER_CODE(EG(current_execute_data)->func->common.type) &&
EG(current_execute_data)->opline->opcode != ZEND_DO_FCALL &&
EG(current_execute_data)->opline->opcode != ZEND_DO_ICALL &&
EG(current_execute_data)->opline->opcode != ZEND_DO_UCALL &&
EG(current_execute_data)->opline->opcode != ZEND_DO_FCALL_BY_NAME) {
/* Insert fake frame in case of include or magic calls */
dummy_execute_data = *EG(current_execute_data);
dummy_execute_data.prev_execute_data = EG(current_execute_data);
dummy_execute_data.call = NULL;
dummy_execute_data.opline = NULL;
dummy_execute_data.func = NULL;
EG(current_execute_data) = &dummy_execute_data;
}
if (!fci_cache || !fci_cache->initialized) {
zend_string *callable_name;
char *error = NULL;
if (!fci_cache) {
fci_cache = &fci_cache_local;
}
if (!zend_is_callable_ex(&fci->function_name, fci->object, IS_CALLABLE_CHECK_SILENT, &callable_name, fci_cache, &error)) {
if (error) {
zend_error(E_WARNING, "Invalid callback %s, %s", ZSTR_VAL(callable_name), error);
efree(error);
}
if (callable_name) {
zend_string_release(callable_name);
}
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
return FAILURE;
} else if (error) {
/* Capitalize the first latter of the error message */
if (error[0] >= 'a' && error[0] <= 'z') {
error[0] += ('A' - 'a');
}
zend_error(E_DEPRECATED, "%s", error);
efree(error);
}
zend_string_release(callable_name);
}
func = fci_cache->function_handler;
call = zend_vm_stack_push_call_frame(ZEND_CALL_TOP_FUNCTION,
func, fci->param_count, fci_cache->called_scope, fci_cache->object);
calling_scope = fci_cache->calling_scope;
fci->object = fci_cache->object;
if (fci->object &&
(!EG(objects_store).object_buckets ||
!IS_OBJ_VALID(EG(objects_store).object_buckets[fci->object->handle]))) {
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
return FAILURE;
}
if (func->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_DEPRECATED)) {
if (func->common.fn_flags & ZEND_ACC_ABSTRACT) {
zend_throw_error(NULL, "Cannot call abstract method %s::%s()", ZSTR_VAL(func->common.scope->name), ZSTR_VAL(func->common.function_name));
return FAILURE;
}
if (func->common.fn_flags & ZEND_ACC_DEPRECATED) {
zend_error(E_DEPRECATED, "Function %s%s%s() is deprecated",
func->common.scope ? ZSTR_VAL(func->common.scope->name) : "",
func->common.scope ? "::" : "",
ZSTR_VAL(func->common.function_name));
}
}
for (i=0; i<fci->param_count; i++) {
zval *param;
zval *arg = &fci->params[i];
if (ARG_SHOULD_BE_SENT_BY_REF(func, i + 1)) {
if (UNEXPECTED(!Z_ISREF_P(arg))) {
if (fci->no_separation &&
!ARG_MAY_BE_SENT_BY_REF(func, i + 1)) {
if (i) {
/* hack to clean up the stack */
ZEND_CALL_NUM_ARGS(call) = i;
zend_vm_stack_free_args(call);
}
zend_vm_stack_free_call_frame(call);
zend_error(E_WARNING, "Parameter %d to %s%s%s() expected to be a reference, value given",
i+1,
func->common.scope ? ZSTR_VAL(func->common.scope->name) : "",
func->common.scope ? "::" : "",
ZSTR_VAL(func->common.function_name));
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
return FAILURE;
}
ZVAL_NEW_REF(arg, arg);
}
Z_ADDREF_P(arg);
} else {
if (Z_ISREF_P(arg) &&
!(func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) {
/* don't separate references for __call */
arg = Z_REFVAL_P(arg);
}
if (Z_OPT_REFCOUNTED_P(arg)) {
Z_ADDREF_P(arg);
}
}
param = ZEND_CALL_ARG(call, i+1);
ZVAL_COPY_VALUE(param, arg);
}
EG(scope) = calling_scope;
if (func->common.fn_flags & ZEND_ACC_STATIC) {
fci->object = NULL;
}
Z_OBJ(call->This) = fci->object;
if (UNEXPECTED(func->op_array.fn_flags & ZEND_ACC_CLOSURE)) {
ZEND_ASSERT(GC_TYPE((zend_object*)func->op_array.prototype) == IS_OBJECT);
GC_REFCOUNT((zend_object*)func->op_array.prototype)++;
ZEND_ADD_CALL_FLAG(call, ZEND_CALL_CLOSURE);
}
if (func->type == ZEND_USER_FUNCTION) {
int call_via_handler = (func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) != 0;
EG(scope) = func->common.scope;
call->symbol_table = fci->symbol_table;
if (EXPECTED((func->op_array.fn_flags & ZEND_ACC_GENERATOR) == 0)) {
zend_init_execute_data(call, &func->op_array, fci->retval);
zend_execute_ex(call);
} else {
zend_generator_create_zval(call, &func->op_array, fci->retval);
}
if (call_via_handler) {
/* We must re-initialize function again */
fci_cache->initialized = 0;
}
} else if (func->type == ZEND_INTERNAL_FUNCTION) {
int call_via_handler = (func->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) != 0;
ZVAL_NULL(fci->retval);
if (func->common.scope) {
EG(scope) = func->common.scope;
}
call->prev_execute_data = EG(current_execute_data);
call->return_value = NULL; /* this is not a constructor call */
EG(current_execute_data) = call;
if (EXPECTED(zend_execute_internal == NULL)) {
/* saves one function call if zend_execute_internal is not used */
func->internal_function.handler(call, fci->retval);
} else {
zend_execute_internal(call, fci->retval);
}
EG(current_execute_data) = call->prev_execute_data;
zend_vm_stack_free_args(call);
/* We shouldn't fix bad extensions here,
because it can break proper ones (Bug #34045)
if (!EX(function_state).function->common.return_reference)
{
INIT_PZVAL(f->retval);
}*/
if (EG(exception)) {
zval_ptr_dtor(fci->retval);
ZVAL_UNDEF(fci->retval);
}
if (call_via_handler) {
/* We must re-initialize function again */
fci_cache->initialized = 0;
}
} else { /* ZEND_OVERLOADED_FUNCTION */
ZVAL_NULL(fci->retval);
/* Not sure what should be done here if it's a static method */
if (fci->object) {
call->prev_execute_data = EG(current_execute_data);
EG(current_execute_data) = call;
fci->object->handlers->call_method(func->common.function_name, fci->object, call, fci->retval);
EG(current_execute_data) = call->prev_execute_data;
} else {
zend_throw_error(NULL, "Cannot call overloaded function for non-object");
}
zend_vm_stack_free_args(call);
if (func->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY) {
zend_string_release(func->common.function_name);
}
efree(func);
if (EG(exception)) {
zval_ptr_dtor(fci->retval);
ZVAL_UNDEF(fci->retval);
}
}
EG(scope) = orig_scope;
zend_vm_stack_free_call_frame(call);
if (EG(current_execute_data) == &dummy_execute_data) {
EG(current_execute_data) = dummy_execute_data.prev_execute_data;
}
if (EG(exception)) {
zend_throw_exception_internal(NULL);
}
return SUCCESS;
}
/* }}} */
ZEND_API zend_class_entry *zend_lookup_class_ex(zend_string *name, const zval *key, int use_autoload) /* {{{ */
{
zend_class_entry *ce = NULL;
zval args[1];
zval local_retval;
int retval;
zend_string *lc_name;
zend_fcall_info fcall_info;
zend_fcall_info_cache fcall_cache;
if (key) {
lc_name = Z_STR_P(key);
} else {
if (name == NULL || !ZSTR_LEN(name)) {
return NULL;
}
if (ZSTR_VAL(name)[0] == '\\') {
lc_name = zend_string_alloc(ZSTR_LEN(name) - 1, 0);
zend_str_tolower_copy(ZSTR_VAL(lc_name), ZSTR_VAL(name) + 1, ZSTR_LEN(name) - 1);
} else {
lc_name = zend_string_tolower(name);
}
}
ce = zend_hash_find_ptr(EG(class_table), lc_name);
if (ce) {
if (!key) {
zend_string_release(lc_name);
}
return ce;
}
/* The compiler is not-reentrant. Make sure we __autoload() only during run-time
* (doesn't impact functionality of __autoload()
*/
if (!use_autoload || zend_is_compiling()) {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
if (!EG(autoload_func)) {
zend_function *func = zend_hash_str_find_ptr(EG(function_table), ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1);
if (func) {
EG(autoload_func) = func;
} else {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
}
/* Verify class name before passing it to __autoload() */
if (strspn(ZSTR_VAL(name), "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\") != ZSTR_LEN(name)) {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
if (EG(in_autoload) == NULL) {
ALLOC_HASHTABLE(EG(in_autoload));
zend_hash_init(EG(in_autoload), 8, NULL, NULL, 0);
}
if (zend_hash_add_empty_element(EG(in_autoload), lc_name) == NULL) {
if (!key) {
zend_string_release(lc_name);
}
return NULL;
}
ZVAL_UNDEF(&local_retval);
if (ZSTR_VAL(name)[0] == '\\') {
ZVAL_STRINGL(&args[0], ZSTR_VAL(name) + 1, ZSTR_LEN(name) - 1);
} else {
ZVAL_STR_COPY(&args[0], name);
}
fcall_info.size = sizeof(fcall_info);
fcall_info.function_table = EG(function_table);
ZVAL_STR_COPY(&fcall_info.function_name, EG(autoload_func)->common.function_name);
fcall_info.symbol_table = NULL;
fcall_info.retval = &local_retval;
fcall_info.param_count = 1;
fcall_info.params = args;
fcall_info.object = NULL;
fcall_info.no_separation = 1;
fcall_cache.initialized = 1;
fcall_cache.function_handler = EG(autoload_func);
fcall_cache.calling_scope = NULL;
fcall_cache.called_scope = NULL;
fcall_cache.object = NULL;
zend_exception_save();
retval = zend_call_function(&fcall_info, &fcall_cache);
zend_exception_restore();
zval_ptr_dtor(&args[0]);
zval_dtor(&fcall_info.function_name);
zend_hash_del(EG(in_autoload), lc_name);
zval_ptr_dtor(&local_retval);
if (retval == SUCCESS) {
ce = zend_hash_find_ptr(EG(class_table), lc_name);
}
if (!key) {
zend_string_release(lc_name);
}
return ce;
}
/* }}} */
ZEND_API zend_class_entry *zend_lookup_class(zend_string *name) /* {{{ */
{
return zend_lookup_class_ex(name, NULL, 1);
}
/* }}} */
ZEND_API zend_class_entry *zend_get_called_scope(zend_execute_data *ex) /* {{{ */
{
while (ex) {
if (ex->called_scope) {
return ex->called_scope;
} else if (ex->func) {
if (ex->func->type != ZEND_INTERNAL_FUNCTION || ex->func->common.scope) {
return ex->called_scope;
}
}
ex = ex->prev_execute_data;
}
return NULL;
}
/* }}} */
ZEND_API zend_object *zend_get_this_object(zend_execute_data *ex) /* {{{ */
{
while (ex) {
if (Z_OBJ(ex->This)) {
return Z_OBJ(ex->This);
} else if (ex->func) {
if (ex->func->type != ZEND_INTERNAL_FUNCTION || ex->func->common.scope) {
return Z_OBJ(ex->This);
}
}
ex = ex->prev_execute_data;
}
return NULL;
}
/* }}} */
ZEND_API int zend_eval_stringl(char *str, size_t str_len, zval *retval_ptr, char *string_name) /* {{{ */
{
zval pv;
zend_op_array *new_op_array;
uint32_t original_compiler_options;
int retval;
if (retval_ptr) {
ZVAL_NEW_STR(&pv, zend_string_alloc(str_len + sizeof("return ;")-1, 1));
memcpy(Z_STRVAL(pv), "return ", sizeof("return ") - 1);
memcpy(Z_STRVAL(pv) + sizeof("return ") - 1, str, str_len);
Z_STRVAL(pv)[Z_STRLEN(pv) - 1] = ';';
Z_STRVAL(pv)[Z_STRLEN(pv)] = '\0';
} else {
ZVAL_STRINGL(&pv, str, str_len);
}
/*printf("Evaluating '%s'\n", pv.value.str.val);*/
original_compiler_options = CG(compiler_options);
CG(compiler_options) = ZEND_COMPILE_DEFAULT_FOR_EVAL;
new_op_array = zend_compile_string(&pv, string_name);
CG(compiler_options) = original_compiler_options;
if (new_op_array) {
zval local_retval;
EG(no_extensions)=1;
zend_try {
ZVAL_UNDEF(&local_retval);
zend_execute(new_op_array, &local_retval);
} zend_catch {
destroy_op_array(new_op_array);
efree_size(new_op_array, sizeof(zend_op_array));
zend_bailout();
} zend_end_try();
if (Z_TYPE(local_retval) != IS_UNDEF) {
if (retval_ptr) {
ZVAL_COPY_VALUE(retval_ptr, &local_retval);
} else {
zval_ptr_dtor(&local_retval);
}
} else {
if (retval_ptr) {
ZVAL_NULL(retval_ptr);
}
}
EG(no_extensions)=0;
destroy_op_array(new_op_array);
efree_size(new_op_array, sizeof(zend_op_array));
retval = SUCCESS;
} else {
retval = FAILURE;
}
zval_dtor(&pv);
return retval;
}
/* }}} */
ZEND_API int zend_eval_string(char *str, zval *retval_ptr, char *string_name) /* {{{ */
{
return zend_eval_stringl(str, strlen(str), retval_ptr, string_name);
}
/* }}} */
ZEND_API int zend_eval_stringl_ex(char *str, size_t str_len, zval *retval_ptr, char *string_name, int handle_exceptions) /* {{{ */
{
int result;
result = zend_eval_stringl(str, str_len, retval_ptr, string_name);
if (handle_exceptions && EG(exception)) {
zend_exception_error(EG(exception), E_ERROR);
result = FAILURE;
}
return result;
}
/* }}} */
ZEND_API int zend_eval_string_ex(char *str, zval *retval_ptr, char *string_name, int handle_exceptions) /* {{{ */
{
return zend_eval_stringl_ex(str, strlen(str), retval_ptr, string_name, handle_exceptions);
}
/* }}} */
ZEND_API void zend_timeout(int dummy) /* {{{ */
{
if (zend_on_timeout) {
#ifdef ZEND_SIGNALS
/*
We got here because we got a timeout signal, so we are in a signal handler
at this point. However, we want to be able to timeout any user-supplied
shutdown functions, so pretend we are not in a signal handler while we are
calling these
*/
SIGG(running) = 0;
#endif
zend_on_timeout(EG(timeout_seconds));
}
zend_error_noreturn(E_ERROR, "Maximum execution time of %pd second%s exceeded", EG(timeout_seconds), EG(timeout_seconds) == 1 ? "" : "s");
}
/* }}} */
#ifdef ZEND_WIN32
VOID CALLBACK tq_timer_cb(PVOID arg, BOOLEAN timed_out)
{
zend_bool *php_timed_out;
/* The doc states it'll be always true, however it theoretically
could be FALSE when the thread was signaled. */
if (!timed_out) {
return;
}
php_timed_out = (zend_bool *)arg;
*php_timed_out = 1;
}
#endif
/* This one doesn't exists on QNX */
#ifndef SIGPROF
#define SIGPROF 27
#endif
void zend_set_timeout(zend_long seconds, int reset_signals) /* {{{ */
{
EG(timeout_seconds) = seconds;
#ifdef ZEND_WIN32
if(!seconds) {
return;
}
/* Don't use ChangeTimerQueueTimer() as it will not restart an expired
timer, so we could end up with just an ignored timeout. Instead
delete and recreate. */
if (NULL != tq_timer) {
if (!DeleteTimerQueueTimer(NULL, tq_timer, NULL)) {
EG(timed_out) = 0;
tq_timer = NULL;
zend_error_noreturn(E_ERROR, "Could not delete queued timer");
return;
}
tq_timer = NULL;
}
/* XXX passing NULL means the default timer queue provided by the system is used */
if (!CreateTimerQueueTimer(&tq_timer, NULL, (WAITORTIMERCALLBACK)tq_timer_cb, (VOID*)&EG(timed_out), seconds*1000, 0, WT_EXECUTEONLYONCE)) {
EG(timed_out) = 0;
tq_timer = NULL;
zend_error_noreturn(E_ERROR, "Could not queue new timer");
return;
}
EG(timed_out) = 0;
#else
# ifdef HAVE_SETITIMER
{
struct itimerval t_r; /* timeout requested */
int signo;
if(seconds) {
t_r.it_value.tv_sec = seconds;
t_r.it_value.tv_usec = t_r.it_interval.tv_sec = t_r.it_interval.tv_usec = 0;
# ifdef __CYGWIN__
setitimer(ITIMER_REAL, &t_r, NULL);
}
signo = SIGALRM;
# else
setitimer(ITIMER_PROF, &t_r, NULL);
}
signo = SIGPROF;
# endif
if (reset_signals) {
# ifdef ZEND_SIGNALS
zend_signal(signo, zend_timeout);
# else
sigset_t sigset;
signal(signo, zend_timeout);
sigemptyset(&sigset);
sigaddset(&sigset, signo);
sigprocmask(SIG_UNBLOCK, &sigset, NULL);
# endif
}
}
# endif /* HAVE_SETITIMER */
#endif
}
/* }}} */
void zend_unset_timeout(void) /* {{{ */
{
#ifdef ZEND_WIN32
if (NULL != tq_timer) {
if (!DeleteTimerQueueTimer(NULL, tq_timer, NULL)) {
EG(timed_out) = 0;
tq_timer = NULL;
zend_error_noreturn(E_ERROR, "Could not delete queued timer");
return;
}
tq_timer = NULL;
}
EG(timed_out) = 0;
#else
# ifdef HAVE_SETITIMER
if (EG(timeout_seconds)) {
struct itimerval no_timeout;
no_timeout.it_value.tv_sec = no_timeout.it_value.tv_usec = no_timeout.it_interval.tv_sec = no_timeout.it_interval.tv_usec = 0;
#ifdef __CYGWIN__
setitimer(ITIMER_REAL, &no_timeout, NULL);
#else
setitimer(ITIMER_PROF, &no_timeout, NULL);
#endif
}
# endif
#endif
}
/* }}} */
zend_class_entry *zend_fetch_class(zend_string *class_name, int fetch_type) /* {{{ */
{
zend_class_entry *ce;
int fetch_sub_type = fetch_type & ZEND_FETCH_CLASS_MASK;
check_fetch_type:
switch (fetch_sub_type) {
case ZEND_FETCH_CLASS_SELF:
if (UNEXPECTED(!EG(scope))) {
zend_throw_or_error(fetch_type, NULL, "Cannot access self:: when no class scope is active");
}
return EG(scope);
case ZEND_FETCH_CLASS_PARENT:
if (UNEXPECTED(!EG(scope))) {
zend_throw_or_error(fetch_type, NULL, "Cannot access parent:: when no class scope is active");
return NULL;
}
if (UNEXPECTED(!EG(scope)->parent)) {
zend_throw_or_error(fetch_type, NULL, "Cannot access parent:: when current class scope has no parent");
}
return EG(scope)->parent;
case ZEND_FETCH_CLASS_STATIC:
ce = zend_get_called_scope(EG(current_execute_data));
if (UNEXPECTED(!ce)) {
zend_throw_or_error(fetch_type, NULL, "Cannot access static:: when no class scope is active");
return NULL;
}
return ce;
case ZEND_FETCH_CLASS_AUTO: {
fetch_sub_type = zend_get_class_fetch_type(class_name);
if (UNEXPECTED(fetch_sub_type != ZEND_FETCH_CLASS_DEFAULT)) {
goto check_fetch_type;
}
}
break;
}
if (fetch_type & ZEND_FETCH_CLASS_NO_AUTOLOAD) {
return zend_lookup_class_ex(class_name, NULL, 0);
} else if ((ce = zend_lookup_class_ex(class_name, NULL, 1)) == NULL) {
if (!(fetch_type & ZEND_FETCH_CLASS_SILENT) && !EG(exception)) {
if (fetch_sub_type == ZEND_FETCH_CLASS_INTERFACE) {
zend_throw_or_error(fetch_type, NULL, "Interface '%s' not found", ZSTR_VAL(class_name));
} else if (fetch_sub_type == ZEND_FETCH_CLASS_TRAIT) {
zend_throw_or_error(fetch_type, NULL, "Trait '%s' not found", ZSTR_VAL(class_name));
} else {
zend_throw_or_error(fetch_type, NULL, "Class '%s' not found", ZSTR_VAL(class_name));
}
}
return NULL;
}
return ce;
}
/* }}} */
zend_class_entry *zend_fetch_class_by_name(zend_string *class_name, const zval *key, int fetch_type) /* {{{ */
{
zend_class_entry *ce;
if (fetch_type & ZEND_FETCH_CLASS_NO_AUTOLOAD) {
return zend_lookup_class_ex(class_name, key, 0);
} else if ((ce = zend_lookup_class_ex(class_name, key, 1)) == NULL) {
if ((fetch_type & ZEND_FETCH_CLASS_SILENT) == 0 && !EG(exception)) {
if ((fetch_type & ZEND_FETCH_CLASS_MASK) == ZEND_FETCH_CLASS_INTERFACE) {
zend_throw_or_error(fetch_type, NULL, "Interface '%s' not found", ZSTR_VAL(class_name));
} else if ((fetch_type & ZEND_FETCH_CLASS_MASK) == ZEND_FETCH_CLASS_TRAIT) {
zend_throw_or_error(fetch_type, NULL, "Trait '%s' not found", ZSTR_VAL(class_name));
} else {
zend_throw_or_error(fetch_type, NULL, "Class '%s' not found", ZSTR_VAL(class_name));
}
}
return NULL;
}
return ce;
}
/* }}} */
#define MAX_ABSTRACT_INFO_CNT 3
#define MAX_ABSTRACT_INFO_FMT "%s%s%s%s"
#define DISPLAY_ABSTRACT_FN(idx) \
ai.afn[idx] ? ZEND_FN_SCOPE_NAME(ai.afn[idx]) : "", \
ai.afn[idx] ? "::" : "", \
ai.afn[idx] ? ZSTR_VAL(ai.afn[idx]->common.function_name) : "", \
ai.afn[idx] && ai.afn[idx + 1] ? ", " : (ai.afn[idx] && ai.cnt > MAX_ABSTRACT_INFO_CNT ? ", ..." : "")
typedef struct _zend_abstract_info {
zend_function *afn[MAX_ABSTRACT_INFO_CNT + 1];
int cnt;
int ctor;
} zend_abstract_info;
static void zend_verify_abstract_class_function(zend_function *fn, zend_abstract_info *ai) /* {{{ */
{
if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) {
if (ai->cnt < MAX_ABSTRACT_INFO_CNT) {
ai->afn[ai->cnt] = fn;
}
if (fn->common.fn_flags & ZEND_ACC_CTOR) {
if (!ai->ctor) {
ai->cnt++;
ai->ctor = 1;
} else {
ai->afn[ai->cnt] = NULL;
}
} else {
ai->cnt++;
}
}
}
/* }}} */
void zend_verify_abstract_class(zend_class_entry *ce) /* {{{ */
{
zend_function *func;
zend_abstract_info ai;
if ((ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) && !(ce->ce_flags & (ZEND_ACC_TRAIT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) {
memset(&ai, 0, sizeof(ai));
ZEND_HASH_FOREACH_PTR(&ce->function_table, func) {
zend_verify_abstract_class_function(func, &ai);
} ZEND_HASH_FOREACH_END();
if (ai.cnt) {
zend_error_noreturn(E_ERROR, "Class %s contains %d abstract method%s and must therefore be declared abstract or implement the remaining methods (" MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT MAX_ABSTRACT_INFO_FMT ")",
ZSTR_VAL(ce->name), ai.cnt,
ai.cnt > 1 ? "s" : "",
DISPLAY_ABSTRACT_FN(0),
DISPLAY_ABSTRACT_FN(1),
DISPLAY_ABSTRACT_FN(2)
);
}
}
}
/* }}} */
ZEND_API int zend_delete_global_variable(zend_string *name) /* {{{ */
{
return zend_hash_del_ind(&EG(symbol_table), name);
}
/* }}} */
ZEND_API zend_array *zend_rebuild_symbol_table(void) /* {{{ */
{
zend_execute_data *ex;
zend_array *symbol_table;
/* Search for last called user function */
ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->common.type))) {
ex = ex->prev_execute_data;
}
if (!ex) {
return NULL;
}
if (ex->symbol_table) {
return ex->symbol_table;
}
if (EG(symtable_cache_ptr) >= EG(symtable_cache)) {
/*printf("Cache hit! Reusing %x\n", symtable_cache[symtable_cache_ptr]);*/
symbol_table = ex->symbol_table = *(EG(symtable_cache_ptr)--);
if (!ex->func->op_array.last_var) {
return symbol_table;
}
zend_hash_extend(symbol_table, ex->func->op_array.last_var, 0);
} else {
symbol_table = ex->symbol_table = emalloc(sizeof(zend_array));
zend_hash_init(symbol_table, ex->func->op_array.last_var, NULL, ZVAL_PTR_DTOR, 0);
if (!ex->func->op_array.last_var) {
return symbol_table;
}
zend_hash_real_init(symbol_table, 0);
/*printf("Cache miss! Initialized %x\n", EG(active_symbol_table));*/
}
if (EXPECTED(ex->func->op_array.last_var)) {
zend_string **str = ex->func->op_array.vars;
zend_string **end = str + ex->func->op_array.last_var;
zval *var = ZEND_CALL_VAR_NUM(ex, 0);
do {
_zend_hash_append_ind(symbol_table, *str, var);
str++;
var++;
} while (str != end);
}
return symbol_table;
}
/* }}} */
ZEND_API void zend_attach_symbol_table(zend_execute_data *execute_data) /* {{{ */
{
zend_op_array *op_array = &execute_data->func->op_array;
HashTable *ht = execute_data->symbol_table;
/* copy real values from symbol table into CV slots and create
INDIRECT references to CV in symbol table */
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
zval *var = EX_VAR_NUM(0);
do {
zval *zv = zend_hash_find(ht, *str);
if (zv) {
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zval *val = Z_INDIRECT_P(zv);
ZVAL_COPY_VALUE(var, val);
} else {
ZVAL_COPY_VALUE(var, zv);
}
} else {
ZVAL_UNDEF(var);
zv = zend_hash_add_new(ht, *str, var);
}
ZVAL_INDIRECT(zv, var);
str++;
var++;
} while (str != end);
}
}
/* }}} */
ZEND_API void zend_detach_symbol_table(zend_execute_data *execute_data) /* {{{ */
{
zend_op_array *op_array = &execute_data->func->op_array;
HashTable *ht = execute_data->symbol_table;
/* copy real values from CV slots into symbol table */
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
zval *var = EX_VAR_NUM(0);
do {
if (Z_TYPE_P(var) == IS_UNDEF) {
zend_hash_del(ht, *str);
} else {
zend_hash_update(ht, *str, var);
ZVAL_UNDEF(var);
}
str++;
var++;
} while (str != end);
}
}
/* }}} */
ZEND_API int zend_set_local_var(zend_string *name, zval *value, int force) /* {{{ */
{
zend_execute_data *execute_data = EG(current_execute_data);
while (execute_data && (!execute_data->func || !ZEND_USER_CODE(execute_data->func->common.type))) {
execute_data = execute_data->prev_execute_data;
}
if (execute_data) {
if (!execute_data->symbol_table) {
zend_ulong h = zend_string_hash_val(name);
zend_op_array *op_array = &execute_data->func->op_array;
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
do {
if (ZSTR_H(*str) == h &&
ZSTR_LEN(*str) == ZSTR_LEN(name) &&
memcmp(ZSTR_VAL(*str), ZSTR_VAL(name), ZSTR_LEN(name)) == 0) {
zval *var = EX_VAR_NUM(str - op_array->vars);
ZVAL_COPY_VALUE(var, value);
return SUCCESS;
}
str++;
} while (str != end);
}
if (force) {
zend_array *symbol_table = zend_rebuild_symbol_table();
if (symbol_table) {
return zend_hash_update(symbol_table, name, value) ? SUCCESS : FAILURE;;
}
}
} else {
return (zend_hash_update_ind(execute_data->symbol_table, name, value) != NULL) ? SUCCESS : FAILURE;
}
}
return FAILURE;
}
/* }}} */
ZEND_API int zend_set_local_var_str(const char *name, size_t len, zval *value, int force) /* {{{ */
{
zend_execute_data *execute_data = EG(current_execute_data);
while (execute_data && (!execute_data->func || !ZEND_USER_CODE(execute_data->func->common.type))) {
execute_data = execute_data->prev_execute_data;
}
if (execute_data) {
if (!execute_data->symbol_table) {
zend_ulong h = zend_hash_func(name, len);
zend_op_array *op_array = &execute_data->func->op_array;
if (EXPECTED(op_array->last_var)) {
zend_string **str = op_array->vars;
zend_string **end = str + op_array->last_var;
do {
if (ZSTR_H(*str) == h &&
ZSTR_LEN(*str) == len &&
memcmp(ZSTR_VAL(*str), name, len) == 0) {
zval *var = EX_VAR_NUM(str - op_array->vars);
zval_ptr_dtor(var);
ZVAL_COPY_VALUE(var, value);
return SUCCESS;
}
str++;
} while (str != end);
}
if (force) {
zend_array *symbol_table = zend_rebuild_symbol_table();
if (symbol_table) {
return zend_hash_str_update(symbol_table, name, len, value) ? SUCCESS : FAILURE;;
}
}
} else {
return (zend_hash_str_update_ind(execute_data->symbol_table, name, len, value) != NULL) ? SUCCESS : FAILURE;
}
}
return FAILURE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: t
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-134/c/good_1792_0 |
crossvul-cpp_data_bad_1377_6 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-770/cpp/bad_1377_6 |
crossvul-cpp_data_bad_1378_3 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/gen-cpp2/ProtocolTruncatedData_types.h>
using namespace apache::thrift;
using namespace thrift::test;
template <class Serializer, class T>
void testPartialDataHandling(const T& val, size_t bytesToPassTheCheck) {
auto buf = Serializer::template serialize<folly::IOBufQueue>(val).move();
buf->coalesce();
// Check that deserializing doesn't throw.
EXPECT_NO_THROW(Serializer::template deserialize<T>(buf.get()));
// Trim the buffer to the point that is *just enough* to pass the check for
// minimum required bytes.
buf->trimEnd(buf->length() - bytesToPassTheCheck);
// We'll hit underflow exception when pulling yet another element.
EXPECT_THROW(
Serializer::template deserialize<T>(buf.get()), std::out_of_range);
// Trim one more byte.
buf->trimEnd(1);
// We'll fail the deserialization straight when we read the length.
EXPECT_THROW(
Serializer::template deserialize<T>(buf.get()),
apache::thrift::protocol::TProtocolException);
}
TEST(ProtocolTruncatedDataTest, TruncatedList) {
TestStruct s;
s.i64_list_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i64_list_ref()->emplace_back((1ull << i));
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 /* 1b / element */);
}
TEST(ProtocolTruncatedDataTest, TruncatedSet) {
TestStruct s;
s.i32_set_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i32_set_ref()->emplace((1ull << i));
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 /* 1b / element */);
}
TEST(ProtocolTruncatedDataTest, TruncatedMap) {
TestStruct s;
s.i32_i16_map_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i32_i16_map_ref()->emplace((1ull << i), i);
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 * 2 /* 2b / kv pair */);
}
| ./CrossVul/dataset_final_sorted/CWE-770/cpp/bad_1378_3 |
crossvul-cpp_data_bad_1377_0 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/protocol/TProtocolException.h>
#include <fmt/core.h>
namespace apache {
namespace thrift {
namespace protocol {
[[noreturn]] void TProtocolException::throwUnionMissingStop() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"missing stop marker to terminate a union");
}
[[noreturn]] void TProtocolException::throwReportedTypeMismatch() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"The reported type of thrift element does not match the serialized type");
}
[[noreturn]] void TProtocolException::throwNegativeSize() {
throw TProtocolException(TProtocolException::NEGATIVE_SIZE);
}
[[noreturn]] void TProtocolException::throwExceededSizeLimit() {
throw TProtocolException(TProtocolException::SIZE_LIMIT);
}
[[noreturn]] void TProtocolException::throwMissingRequiredField(
folly::StringPiece field,
folly::StringPiece type) {
throw TProtocolException(
TProtocolException::MISSING_REQUIRED_FIELD,
fmt::format(
"Required field '{}' was not found in serialized data! Struct: {}",
field,
type));
}
[[noreturn]] void TProtocolException::throwBoolValueOutOfRange(uint8_t value) {
throw TProtocolException(
TProtocolException::INVALID_DATA,
fmt::format(
"Attempt to interpret value {} as bool, probably the data is "
"corrupted",
value));
}
[[noreturn]] void TProtocolException::throwInvalidSkipType(TType type) {
throw TProtocolException(
TProtocolException::INVALID_DATA,
fmt::format(
"Encountered invalid field/element type ({}) during skipping",
static_cast<uint8_t>(type)));
}
[[noreturn]] void TProtocolException::throwInvalidFieldData() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"The field stream contains corrupted data");
}
} // namespace protocol
} // namespace thrift
} // namespace apache
| ./CrossVul/dataset_final_sorted/CWE-770/cpp/bad_1377_0 |
crossvul-cpp_data_good_1377_0 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/protocol/TProtocolException.h>
#include <fmt/core.h>
namespace apache {
namespace thrift {
namespace protocol {
[[noreturn]] void TProtocolException::throwUnionMissingStop() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"missing stop marker to terminate a union");
}
[[noreturn]] void TProtocolException::throwReportedTypeMismatch() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"The reported type of thrift element does not match the serialized type");
}
[[noreturn]] void TProtocolException::throwNegativeSize() {
throw TProtocolException(TProtocolException::NEGATIVE_SIZE);
}
[[noreturn]] void TProtocolException::throwExceededSizeLimit() {
throw TProtocolException(TProtocolException::SIZE_LIMIT);
}
[[noreturn]] void TProtocolException::throwMissingRequiredField(
folly::StringPiece field,
folly::StringPiece type) {
throw TProtocolException(
TProtocolException::MISSING_REQUIRED_FIELD,
fmt::format(
"Required field '{}' was not found in serialized data! Struct: {}",
field,
type));
}
[[noreturn]] void TProtocolException::throwBoolValueOutOfRange(uint8_t value) {
throw TProtocolException(
TProtocolException::INVALID_DATA,
fmt::format(
"Attempt to interpret value {} as bool, probably the data is "
"corrupted",
value));
}
[[noreturn]] void TProtocolException::throwInvalidSkipType(TType type) {
throw TProtocolException(
TProtocolException::INVALID_DATA,
fmt::format(
"Encountered invalid field/element type ({}) during skipping",
static_cast<uint8_t>(type)));
}
[[noreturn]] void TProtocolException::throwInvalidFieldData() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"The field stream contains corrupted data");
}
[[noreturn]] void TProtocolException::throwTruncatedData() {
throw TProtocolException(
TProtocolException::INVALID_DATA,
"Not enough bytes to read the entire message, the data appears to be "
"truncated");
}
} // namespace protocol
} // namespace thrift
} // namespace apache
| ./CrossVul/dataset_final_sorted/CWE-770/cpp/good_1377_0 |
crossvul-cpp_data_good_1378_3 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/gen-cpp2/ProtocolTruncatedData_types.h>
using namespace apache::thrift;
using namespace thrift::test;
template <class Serializer, class T>
void testPartialDataHandling(const T& val, size_t bytesToPassTheCheck) {
auto buf = Serializer::template serialize<folly::IOBufQueue>(val).move();
buf->coalesce();
// Check that deserializing doesn't throw.
EXPECT_NO_THROW(Serializer::template deserialize<T>(buf.get()));
// Trim the buffer to the point that is *just enough* to pass the check for
// minimum required bytes.
buf->trimEnd(buf->length() - bytesToPassTheCheck);
// We'll hit underflow exception when pulling yet another element.
EXPECT_THROW(
Serializer::template deserialize<T>(buf.get()), std::out_of_range);
// Trim one more byte.
buf->trimEnd(1);
// We'll fail the deserialization straight when we read the length.
EXPECT_THROW(
Serializer::template deserialize<T>(buf.get()),
apache::thrift::protocol::TProtocolException);
}
TEST(ProtocolTruncatedDataTest, TruncatedList) {
TestStruct s;
s.i64_list_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i64_list_ref()->emplace_back((1ull << i));
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 /* 1b / element */);
}
TEST(ProtocolTruncatedDataTest, TruncatedSet) {
TestStruct s;
s.i32_set_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i32_set_ref()->emplace((1ull << i));
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 /* 1b / element */);
}
TEST(ProtocolTruncatedDataTest, TruncatedMap) {
TestStruct s;
s.i32_i16_map_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i32_i16_map_ref()->emplace((1ull << i), i);
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 * 2 /* 2b / kv pair */);
}
TEST(ProtocolTruncatedDataTest, TuncatedString_Compact) {
TestStruct s;
s.a_string_ref() = "foobarbazstring";
testPartialDataHandling<CompactSerializer>(
s, 2 /* field & length header */ + s.a_string_ref()->size());
}
TEST(ProtocolTruncatedDataTest, TuncatedString_Binary) {
TestStruct s;
s.a_string_ref() = "foobarbazstring";
testPartialDataHandling<BinarySerializer>(
s, 7 /* field & length header */ + s.a_string_ref()->size());
}
| ./CrossVul/dataset_final_sorted/CWE-770/cpp/good_1378_3 |
crossvul-cpp_data_good_1377_6 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/gen-cpp2/ProtocolTruncatedData_types.h>
using namespace apache::thrift;
using namespace thrift::test;
template <class Serializer, class T>
void testPartialDataHandling(const T& val, size_t bytesToPassTheCheck) {
auto buf = Serializer::template serialize<folly::IOBufQueue>(val).move();
buf->coalesce();
// Check that deserializing doesn't throw.
EXPECT_NO_THROW(Serializer::template deserialize<T>(buf.get()));
// Trim the buffer to the point that is *just enough* to pass the check for
// minimum required bytes.
buf->trimEnd(buf->length() - bytesToPassTheCheck);
// We'll hit underflow exception when pulling yet another element.
EXPECT_THROW(
Serializer::template deserialize<T>(buf.get()), std::out_of_range);
// Trim one more byte.
buf->trimEnd(1);
// We'll fail the deserialization straight when we read the length.
EXPECT_THROW(
Serializer::template deserialize<T>(buf.get()),
apache::thrift::protocol::TProtocolException);
}
TEST(ProtocolTruncatedDataTest, TruncatedList) {
TestStruct s;
s.i64_list_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i64_list_ref()->emplace_back((1ull << i));
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 /* 1b / element */);
}
TEST(ProtocolTruncatedDataTest, TruncatedSet) {
TestStruct s;
s.i32_set_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i32_set_ref()->emplace((1ull << i));
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 /* 1b / element */);
}
TEST(ProtocolTruncatedDataTest, TruncatedMap) {
TestStruct s;
s.i32_i16_map_ref() = {};
for (size_t i = 0; i < 30; ++i) {
s.i32_i16_map_ref()->emplace((1ull << i), i);
}
testPartialDataHandling<CompactSerializer>(
s, 3 /* headers */ + 30 * 2 /* 2b / kv pair */);
}
| ./CrossVul/dataset_final_sorted/CWE-770/cpp/good_1377_6 |
crossvul-cpp_data_bad_4064_0 | /*
* Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved.
* Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
/*
* rfbproto.c - functions to deal with client side of RFB protocol.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#define _XOPEN_SOURCE 600
#endif
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#endif
#include <errno.h>
#include <rfb/rfbclient.h>
#ifdef WIN32
#undef socklen_t
#endif
#ifdef LIBVNCSERVER_HAVE_LIBZ
#include <zlib.h>
#ifdef __CHECKER__
#undef Z_NULL
#define Z_NULL NULL
#endif
#endif
#ifndef _MSC_VER
/* Strings.h is not available in MSVC */
#include <strings.h>
#endif
#include <stdarg.h>
#include <time.h>
#include "crypto.h"
#include "sasl.h"
#ifdef LIBVNCSERVER_HAVE_LZO
#include <lzo/lzo1x.h>
#else
#include "minilzo.h"
#endif
#include "tls.h"
/*
* rfbClientLog prints a time-stamped message to the log file (stderr).
*/
rfbBool rfbEnableClientLogging=TRUE;
static void
rfbDefaultClientLog(const char *format, ...)
{
va_list args;
char buf[256];
time_t log_clock;
if(!rfbEnableClientLogging)
return;
va_start(args, format);
time(&log_clock);
strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock));
fprintf(stderr, "%s", buf);
vfprintf(stderr, format, args);
fflush(stderr);
va_end(args);
}
rfbClientLogProc rfbClientLog=rfbDefaultClientLog;
rfbClientLogProc rfbClientErr=rfbDefaultClientLog;
/* extensions */
rfbClientProtocolExtension* rfbClientExtensions = NULL;
void rfbClientRegisterExtension(rfbClientProtocolExtension* e)
{
e->next = rfbClientExtensions;
rfbClientExtensions = e;
}
/* client data */
void rfbClientSetClientData(rfbClient* client, void* tag, void* data)
{
rfbClientData* clientData = client->clientData;
while(clientData && clientData->tag != tag)
clientData = clientData->next;
if(clientData == NULL) {
clientData = calloc(sizeof(rfbClientData), 1);
clientData->next = client->clientData;
client->clientData = clientData;
clientData->tag = tag;
}
clientData->data = data;
}
void* rfbClientGetClientData(rfbClient* client, void* tag)
{
rfbClientData* clientData = client->clientData;
while(clientData) {
if(clientData->tag == tag)
return clientData->data;
clientData = clientData->next;
}
return NULL;
}
static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBZ
static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh);
static long ReadCompactLen (rfbClient* client);
#endif
static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#endif
/*
* Server Capability Functions
*/
rfbBool
SupportsClient2Server(rfbClient* client, int messageType)
{
return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
rfbBool
SupportsServer2Client(rfbClient* client, int messageType)
{
return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
void
SetClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
SetServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
ClearClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= ~(1<<(messageType % 8));
}
void
ClearServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= ~(1<<(messageType % 8));
}
void
DefaultSupportedMessages(rfbClient* client)
{
memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages));
/* Default client supported messages (universal RFB 3.3 protocol) */
SetClient2Server(client, rfbSetPixelFormat);
/* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */
SetClient2Server(client, rfbSetEncodings);
SetClient2Server(client, rfbFramebufferUpdateRequest);
SetClient2Server(client, rfbKeyEvent);
SetClient2Server(client, rfbPointerEvent);
SetClient2Server(client, rfbClientCutText);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbFramebufferUpdate);
SetServer2Client(client, rfbSetColourMapEntries);
SetServer2Client(client, rfbBell);
SetServer2Client(client, rfbServerCutText);
}
void
DefaultSupportedMessagesUltraVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetScale);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
SetClient2Server(client, rfbTextChat);
SetClient2Server(client, rfbPalmVNCSetScaleFactor);
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbResizeFrameBuffer);
SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer);
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
void
DefaultSupportedMessagesTightVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
/* SetClient2Server(client, rfbTextChat); */
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
#ifndef WIN32
static rfbBool
IsUnixSocket(const char *name)
{
struct stat sb;
if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK)
return TRUE;
return FALSE;
}
#endif
/*
* ConnectToRFBServer.
*/
rfbBool
ConnectToRFBServer(rfbClient* client,const char *hostname, int port)
{
if (client->serverPort==-1) {
/* serverHost is a file recorded by vncrec. */
const char* magic="vncLog0.0";
char buffer[10];
rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec));
client->vncRec = rec;
rec->file = fopen(client->serverHost,"rb");
rec->tv.tv_sec = 0;
rec->readTimestamp = FALSE;
rec->doNotSleep = FALSE;
if (!rec->file) {
rfbClientLog("Could not open %s.\n",client->serverHost);
return FALSE;
}
setbuf(rec->file,NULL);
if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) {
rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost);
fclose(rec->file);
return FALSE;
}
client->sock = RFB_INVALID_SOCKET;
return TRUE;
}
#ifndef WIN32
if(IsUnixSocket(hostname))
/* serverHost is a UNIX socket. */
client->sock = ConnectClientToUnixSockWithTimeout(hostname, client->connectTimeout);
else
#endif
{
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6WithTimeout(hostname, port, client->connectTimeout);
#else
unsigned int host;
/* serverHost is a hostname */
if (!StringToIPAddr(hostname, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", hostname);
return FALSE;
}
client->sock = ConnectClientToTcpAddrWithTimeout(host, port, client->connectTimeout);
#endif
}
if (client->sock == RFB_INVALID_SOCKET) {
rfbClientLog("Unable to connect to VNC server\n");
return FALSE;
}
if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP))
return FALSE;
return TRUE;
}
/*
* ConnectToRFBRepeater.
*/
rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort)
{
rfbProtocolVersionMsg pv;
int major,minor;
char tmphost[250];
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6WithTimeout(repeaterHost, repeaterPort, client->connectTimeout);
#else
unsigned int host;
if (!StringToIPAddr(repeaterHost, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost);
return FALSE;
}
client->sock = ConnectClientToTcpAddrWithTimeout(host, repeaterPort, client->connectTimeout);
#endif
if (client->sock == RFB_INVALID_SOCKET) {
rfbClientLog("Unable to connect to VNC repeater\n");
return FALSE;
}
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg))
return FALSE;
pv[sz_rfbProtocolVersionMsg] = 0;
/* UltraVNC repeater always report version 000.000 to identify itself */
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) {
rfbClientLog("Not a valid VNC repeater (%s)\n",pv);
return FALSE;
}
rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor);
memset(tmphost, 0, sizeof(tmphost));
if(snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort) >= (int)sizeof(tmphost))
return FALSE; /* output truncated */
if (!WriteToRFBServer(client, tmphost, sizeof(tmphost)))
return FALSE;
return TRUE;
}
extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd);
extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key);
static void
ReadReason(rfbClient* client)
{
uint32_t reasonLen;
char *reason;
if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return;
reasonLen = rfbClientSwap32IfLE(reasonLen);
if(reasonLen > 1<<20) {
rfbClientLog("VNC connection failed, but sent reason length of %u exceeds limit of 1MB",(unsigned int)reasonLen);
return;
}
reason = malloc(reasonLen+1);
if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; }
reason[reasonLen]=0;
rfbClientLog("VNC connection failed: %s\n",reason);
free(reason);
}
rfbBool
rfbHandleAuthResult(rfbClient* client)
{
uint32_t authResult=0;
if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;
authResult = rfbClientSwap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
rfbClientLog("VNC authentication succeeded\n");
return TRUE;
break;
case rfbVncAuthFailed:
if (client->major==3 && client->minor>7)
{
/* we have an error following */
ReadReason(client);
return FALSE;
}
rfbClientLog("VNC authentication failed\n");
return FALSE;
case rfbVncAuthTooMany:
rfbClientLog("VNC authentication failed - too many tries\n");
return FALSE;
}
rfbClientLog("Unknown VNC authentication result: %d\n",
(int)authResult);
return FALSE;
}
static rfbBool
ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth)
{
uint8_t count=0;
uint8_t loop=0;
uint8_t flag=0;
rfbBool extAuthHandler;
uint8_t tAuth[256];
char buf1[500],buf2[10];
uint32_t authScheme;
rfbClientProtocolExtension* e;
if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE;
if (count==0)
{
rfbClientLog("List of security types is ZERO, expecting an error to follow\n");
ReadReason(client);
return FALSE;
}
rfbClientLog("We have %d security types to read\n", count);
authScheme=0;
/* now, we have a list of available security types to read ( uint8_t[] ) */
for (loop=0;loop<count;loop++)
{
if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]);
if (flag) continue;
extAuthHandler=FALSE;
for (e = rfbClientExtensions; e; e = e->next) {
if (!e->handleAuthentication) continue;
uint32_t const* secType;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (tAuth[loop]==*secType) {
extAuthHandler=TRUE;
}
}
}
if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth ||
extAuthHandler ||
#if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL)
tAuth[loop]==rfbVeNCrypt ||
#endif
#ifdef LIBVNCSERVER_HAVE_SASL
tAuth[loop]==rfbSASL ||
#endif /* LIBVNCSERVER_HAVE_SASL */
(tAuth[loop]==rfbARD && client->GetCredential) ||
(!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential))))
{
if (!subAuth && client->clientAuthSchemes)
{
int i;
for (i=0;client->clientAuthSchemes[i];i++)
{
if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop])
{
flag++;
authScheme=tAuth[loop];
break;
}
}
}
else
{
flag++;
authScheme=tAuth[loop];
}
if (flag)
{
rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count);
/* send back a single byte indicating which security type to use */
if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
}
}
}
if (authScheme==0)
{
memset(buf1, 0, sizeof(buf1));
for (loop=0;loop<count;loop++)
{
if (strlen(buf1)>=sizeof(buf1)-1) break;
snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]);
strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1);
}
rfbClientLog("Unknown authentication scheme from VNC server: %s\n",
buf1);
return FALSE;
}
*result = authScheme;
return TRUE;
}
static rfbBool
HandleVncAuth(rfbClient *client)
{
uint8_t challenge[CHALLENGESIZE];
char *passwd=NULL;
int i;
if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
if (client->serverPort!=-1) { /* if not playing a vncrec file */
if (client->GetPassword)
passwd = client->GetPassword(client);
if ((!passwd) || (strlen(passwd) == 0)) {
rfbClientLog("Reading password failed\n");
return FALSE;
}
if (strlen(passwd) > 8) {
passwd[8] = '\0';
}
rfbClientEncryptBytes(challenge, passwd);
/* Lose the password from memory */
for (i = strlen(passwd); i >= 0; i--) {
passwd[i] = '\0';
}
free(passwd);
if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
}
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
static void
FreeUserCredential(rfbCredential *cred)
{
if (cred->userCredential.username) free(cred->userCredential.username);
if (cred->userCredential.password) free(cred->userCredential.password);
free(cred);
}
static rfbBool
HandlePlainAuth(rfbClient *client)
{
uint32_t ulen, ulensw;
uint32_t plen, plensw;
rfbCredential *cred;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0);
ulensw = rfbClientSwap32IfLE(ulen);
plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0);
plensw = rfbClientSwap32IfLE(plen);
if (!WriteToRFBServer(client, (char *)&ulensw, 4) ||
!WriteToRFBServer(client, (char *)&plensw, 4))
{
FreeUserCredential(cred);
return FALSE;
}
if (ulen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.username, ulen))
{
FreeUserCredential(cred);
return FALSE;
}
}
if (plen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.password, plen))
{
FreeUserCredential(cred);
return FALSE;
}
}
FreeUserCredential(cred);
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
/* Simple 64bit big integer arithmetic implementation */
/* (x + y) % m, works even if (x + y) > 64bit */
#define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0))
/* (x * y) % m */
static uint64_t
rfbMulM64(uint64_t x, uint64_t y, uint64_t m)
{
uint64_t r;
for(r=0;x>0;x>>=1)
{
if (x&1) r=rfbAddM64(r,y,m);
y=rfbAddM64(y,y,m);
}
return r;
}
/* (x ^ y) % m */
static uint64_t
rfbPowM64(uint64_t b, uint64_t e, uint64_t m)
{
uint64_t r;
for(r=1;e>0;e>>=1)
{
if(e&1) r=rfbMulM64(r,b,m);
b=rfbMulM64(b,b,m);
}
return r;
}
static rfbBool
HandleMSLogonAuth(rfbClient *client)
{
uint64_t gen, mod, resp, priv, pub, key;
uint8_t username[256], password[64];
rfbCredential *cred;
if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE;
gen = rfbClientSwap64IfLE(gen);
mod = rfbClientSwap64IfLE(mod);
resp = rfbClientSwap64IfLE(resp);
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\
"Use it only with SSH tunnel or trusted network.\n");
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
memset(username, 0, sizeof(username));
strncpy((char *)username, cred->userCredential.username, sizeof(username)-1);
memset(password, 0, sizeof(password));
strncpy((char *)password, cred->userCredential.password, sizeof(password)-1);
FreeUserCredential(cred);
srand(time(NULL));
priv = ((uint64_t)rand())<<32;
priv |= (uint64_t)rand();
pub = rfbPowM64(gen, priv, mod);
key = rfbPowM64(resp, priv, mod);
pub = rfbClientSwap64IfLE(pub);
key = rfbClientSwap64IfLE(key);
rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key);
rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key);
if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE;
if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE;
if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
static rfbBool
HandleARDAuth(rfbClient *client)
{
uint8_t gen[2], len[2];
size_t keylen;
uint8_t *mod = NULL, *resp = NULL, *priv = NULL, *pub = NULL, *key = NULL, *shared = NULL;
uint8_t userpass[128], ciphertext[128];
int ciphertext_len;
int passwordLen, usernameLen;
rfbCredential *cred = NULL;
rfbBool result = FALSE;
/* Step 1: Read the authentication material from the socket.
A two-byte generator value, a two-byte key length value. */
if (!ReadFromRFBServer(client, (char *)gen, 2)) {
rfbClientErr("HandleARDAuth: reading generator value failed\n");
goto out;
}
if (!ReadFromRFBServer(client, (char *)len, 2)) {
rfbClientErr("HandleARDAuth: reading key length failed\n");
goto out;
}
keylen = 256*len[0]+len[1]; /* convert from char[] to int */
mod = (uint8_t*)malloc(keylen*5); /* the block actually contains mod, resp, pub, priv and key */
if (!mod)
goto out;
resp = mod+keylen;
pub = resp+keylen;
priv = pub+keylen;
key = priv+keylen;
/* Step 1: Read the authentication material from the socket.
The prime modulus (keylen bytes) and the peer's generated public key (keylen bytes). */
if (!ReadFromRFBServer(client, (char *)mod, keylen)) {
rfbClientErr("HandleARDAuth: reading prime modulus failed\n");
goto out;
}
if (!ReadFromRFBServer(client, (char *)resp, keylen)) {
rfbClientErr("HandleARDAuth: reading peer's generated public key failed\n");
goto out;
}
/* Step 2: Generate own Diffie-Hellman public-private key pair. */
if(!dh_generate_keypair(priv, pub, gen, 2, mod, keylen)) {
rfbClientErr("HandleARDAuth: generating keypair failed\n");
goto out;
}
/* Step 3: Perform Diffie-Hellman key agreement, using the generator (gen),
prime (mod), and the peer's public key. The output will be a shared
secret known to both us and the peer. */
if(!dh_compute_shared_key(key, priv, resp, mod, keylen)) {
rfbClientErr("HandleARDAuth: creating shared key failed\n");
goto out;
}
/* Step 4: Perform an MD5 hash of the shared secret.
This 128-bit (16-byte) value will be used as the AES key. */
shared = malloc(MD5_HASH_SIZE);
if(!hash_md5(shared, key, keylen)) {
rfbClientErr("HandleARDAuth: hashing shared key failed\n");
goto out;
}
/* Step 5: Pack the username and password into a 128-byte
plaintext "userpass" structure: { username[64], password[64] }.
Null-terminate each. Fill the unused bytes with random characters
so that the encryption output is less predictable. */
if(!client->GetCredential) {
rfbClientErr("HandleARDAuth: GetCredential callback is not set\n");
goto out;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if(!cred) {
rfbClientErr("HandleARDAuth: reading credential failed\n");
goto out;
}
passwordLen = strlen(cred->userCredential.password)+1;
usernameLen = strlen(cred->userCredential.username)+1;
if (passwordLen > sizeof(userpass)/2)
passwordLen = sizeof(userpass)/2;
if (usernameLen > sizeof(userpass)/2)
usernameLen = sizeof(userpass)/2;
random_bytes(userpass, sizeof(userpass));
memcpy(userpass, cred->userCredential.username, usernameLen);
memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen);
/* Step 6: Encrypt the plaintext credentials with the 128-bit MD5 hash
from step 4, using the AES 128-bit symmetric cipher in electronic
codebook (ECB) mode. Use no further padding for this block cipher. */
if(!encrypt_aes128ecb(ciphertext, &ciphertext_len, shared, userpass, sizeof(userpass))) {
rfbClientErr("HandleARDAuth: encrypting credentials failed\n");
goto out;
}
/* Step 7: Write the ciphertext from step 6 to the stream.
Write the generated DH public key to the stream. */
if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext)))
goto out;
if (!WriteToRFBServer(client, (char *)pub, keylen))
goto out;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client))
goto out;
result = TRUE;
out:
if (cred)
FreeUserCredential(cred);
free(mod);
free(shared);
return result;
}
/*
* SetClientAuthSchemes.
*/
void
SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size)
{
int i;
if (client->clientAuthSchemes)
{
free(client->clientAuthSchemes);
client->clientAuthSchemes = NULL;
}
if (authSchemes)
{
if (size<0)
{
/* If size<0 we assume the passed-in list is also 0-terminate, so we
* calculate the size here */
for (size=0;authSchemes[size];size++) ;
}
client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1));
for (i=0;i<size;i++)
client->clientAuthSchemes[i] = authSchemes[i];
client->clientAuthSchemes[size] = 0;
}
}
/*
* InitialiseRFBConnection.
*/
rfbBool
InitialiseRFBConnection(rfbClient* client)
{
rfbProtocolVersionMsg pv;
int major,minor;
uint32_t authScheme;
uint32_t subAuthScheme;
rfbClientInitMsg ci;
/* if the connection is immediately closed, don't report anything, so
that pmw's monitor can make test connections */
if (client->listenSpecified)
errorMessageOnReadFailure = FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
pv[sz_rfbProtocolVersionMsg]=0;
errorMessageOnReadFailure = TRUE;
pv[sz_rfbProtocolVersionMsg] = 0;
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) {
rfbClientLog("Not a valid VNC server (%s)\n",pv);
return FALSE;
}
DefaultSupportedMessages(client);
client->major = major;
client->minor = minor;
/* fall back to viewer supported version */
if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion))
client->minor = rfbProtocolMinorVersion;
/* UltraVNC uses minor codes 4 and 6 for the server */
if (major==3 && (minor==4 || minor==6)) {
rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* UltraVNC Single Click uses minor codes 14 and 16 for the server */
if (major==3 && (minor==14 || minor==16)) {
minor = minor - 10;
client->minor = minor;
rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* TightVNC uses minor codes 5 for the server */
if (major==3 && minor==5) {
rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv);
DefaultSupportedMessagesTightVNC(client);
}
/* we do not support > RFB3.8 */
if ((major==3 && minor>8) || major>3)
{
client->major=3;
client->minor=8;
}
rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n",
major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion);
sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor);
if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
/* 3.7 and onwards sends a # of security types first */
if (client->major==3 && client->minor > 6)
{
if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE;
}
else
{
if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE;
authScheme = rfbClientSwap32IfLE(authScheme);
}
rfbClientLog("Selected Security Scheme %d\n", authScheme);
client->authScheme = authScheme;
switch (authScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
case rfbMSLogon:
if (!HandleMSLogonAuth(client)) return FALSE;
break;
case rfbARD:
if (!HandleARDAuth(client)) return FALSE;
break;
case rfbTLS:
if (!HandleAnonTLSAuth(client)) return FALSE;
/* After the TLS session is established, sub auth types are expected.
* Note that all following reading/writing are through the TLS session from here.
*/
if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE;
client->subAuthScheme = subAuthScheme;
switch (subAuthScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No sub authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
(int)subAuthScheme);
return FALSE;
}
break;
case rfbVeNCrypt:
if (!HandleVeNCryptAuth(client)) return FALSE;
switch (client->subAuthScheme) {
case rfbVeNCryptTLSNone:
case rfbVeNCryptX509None:
rfbClientLog("No sub authentication needed\n");
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVeNCryptTLSVNC:
case rfbVeNCryptX509VNC:
if (!HandleVncAuth(client)) return FALSE;
break;
case rfbVeNCryptTLSPlain:
case rfbVeNCryptX509Plain:
if (!HandlePlainAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbVeNCryptX509SASL:
case rfbVeNCryptTLSSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
client->subAuthScheme);
return FALSE;
}
break;
default:
{
rfbBool authHandled=FALSE;
rfbClientProtocolExtension* e;
for (e = rfbClientExtensions; e; e = e->next) {
uint32_t const* secType;
if (!e->handleAuthentication) continue;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (authScheme==*secType) {
if (!e->handleAuthentication(client, authScheme)) return FALSE;
if (!rfbHandleAuthResult(client)) return FALSE;
authHandled=TRUE;
}
}
}
if (authHandled) break;
}
rfbClientLog("Unknown authentication scheme from VNC server: %d\n",
(int)authScheme);
return FALSE;
}
ci.shared = (client->appData.shareDesktop ? 1 : 0);
if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE;
client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth);
client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight);
client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax);
client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax);
client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax);
client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength);
if (client->si.nameLength > 1<<20) {
rfbClientErr("Too big desktop name length sent by server: %u B > 1 MB\n", (unsigned int)client->si.nameLength);
return FALSE;
}
client->desktopName = malloc(client->si.nameLength + 1);
if (!client->desktopName) {
rfbClientLog("Error allocating memory for desktop name, %lu bytes\n",
(unsigned long)client->si.nameLength);
return FALSE;
}
if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE;
client->desktopName[client->si.nameLength] = 0;
rfbClientLog("Desktop name \"%s\"\n",client->desktopName);
rfbClientLog("Connected to VNC server, using protocol version %d.%d\n",
client->major, client->minor);
rfbClientLog("VNC server default format:\n");
PrintPixelFormat(&client->si.format);
return TRUE;
}
/*
* SetFormatAndEncodings.
*/
rfbBool
SetFormatAndEncodings(rfbClient* client)
{
rfbSetPixelFormatMsg spf;
char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4];
rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf;
uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]);
int len = 0;
rfbBool requestCompressLevel = FALSE;
rfbBool requestQualityLevel = FALSE;
rfbBool requestLastRectEncoding = FALSE;
rfbClientProtocolExtension* e;
if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE;
spf.type = rfbSetPixelFormat;
spf.pad1 = 0;
spf.pad2 = 0;
spf.format = client->format;
spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax);
spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax);
spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax);
if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg))
return FALSE;
if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE;
se->type = rfbSetEncodings;
se->pad = 0;
se->nEncodings = 0;
if (client->appData.encodingsString) {
const char *encStr = client->appData.encodingsString;
int encStrLen;
do {
const char *nextEncStr = strchr(encStr, ' ');
if (nextEncStr) {
encStrLen = nextEncStr - encStr;
nextEncStr++;
} else {
encStrLen = strlen(encStr);
}
if (strncasecmp(encStr,"raw",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
} else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
} else if (strncasecmp(encStr,"tight",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
if (client->appData.enableJPEG)
requestQualityLevel = TRUE;
#endif
#endif
} else if (strncasecmp(encStr,"hextile",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
} else if (strncasecmp(encStr,"zlib",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"trle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE);
} else if (strncasecmp(encStr,"zrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
} else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
requestQualityLevel = TRUE;
#endif
} else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) {
/* There are 2 encodings used in 'ultra' */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
} else if (strncasecmp(encStr,"corre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
} else if (strncasecmp(encStr,"rre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
} else {
rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr);
}
encStr = nextEncStr;
} while (encStr && se->nEncodings < MAX_ENCODINGS);
if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
}
if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
else {
if (SameMachine(client->sock)) {
/* TODO:
if (!tunnelSpecified) {
*/
rfbClientLog("Same machine: preferring raw encoding\n");
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
/*
} else {
rfbClientLog("Tunneling active: preferring tight encoding\n");
}
*/
}
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
#endif
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
} else /* if (!tunnelSpecified) */ {
/* If -tunnel option was provided, we assume that server machine is
not in the local network so we use default compression level for
tight encoding instead of fast compression. Thus we are
requesting level 1 compression only if tunneling is not used. */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1);
}
if (client->appData.enableJPEG) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
/* Remote Cursor Support (local to viewer) */
if (client->appData.useRemoteCursor) {
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos);
}
/* Keyboard State Encodings */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState);
/* New Frame Buffer Size */
if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize);
/* Last Rect */
if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect);
/* Server Capabilities */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity);
/* xvp */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp);
/* client extensions */
for(e = rfbClientExtensions; e; e = e->next)
if(e->encodings) {
int* enc;
for(enc = e->encodings; *enc; enc++)
if(se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc);
}
len = sz_rfbSetEncodingsMsg + se->nEncodings * 4;
se->nEncodings = rfbClientSwap16IfLE(se->nEncodings);
if (!WriteToRFBServer(client, buf, len)) return FALSE;
return TRUE;
}
/*
* SendIncrementalFramebufferUpdateRequest.
*/
rfbBool
SendIncrementalFramebufferUpdateRequest(rfbClient* client)
{
return SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h, TRUE);
}
/*
* SendFramebufferUpdateRequest.
*/
rfbBool
SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental)
{
rfbFramebufferUpdateRequestMsg fur;
if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE;
fur.type = rfbFramebufferUpdateRequest;
fur.incremental = incremental ? 1 : 0;
fur.x = rfbClientSwap16IfLE(x);
fur.y = rfbClientSwap16IfLE(y);
fur.w = rfbClientSwap16IfLE(w);
fur.h = rfbClientSwap16IfLE(h);
if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg))
return FALSE;
return TRUE;
}
/*
* SendScaleSetting.
*/
rfbBool
SendScaleSetting(rfbClient* client,int scaleSetting)
{
rfbSetScaleMsg ssm;
ssm.scale = scaleSetting;
ssm.pad = 0;
/* favor UltraVNC SetScale if both are supported */
if (SupportsClient2Server(client, rfbSetScale)) {
ssm.type = rfbSetScale;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) {
ssm.type = rfbPalmVNCSetScaleFactor;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
return TRUE;
}
/*
* TextChatFunctions (UltraVNC)
* Extremely bandwidth friendly method of communicating with a user
* (Think HelpDesk type applications)
*/
rfbBool TextChatSend(rfbClient* client, char *text)
{
rfbTextChatMsg chat;
int count = strlen(text);
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = (uint32_t)count;
chat.length = rfbClientSwap32IfLE(chat.length);
if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg))
return FALSE;
if (count>0) {
if (!WriteToRFBServer(client, text, count))
return FALSE;
}
return TRUE;
}
rfbBool TextChatOpen(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatOpen);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatClose(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatClose);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatFinish(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatFinished);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
/*
* UltraVNC Server Input Disable
* Apparently, the remote client can *prevent* the local user from interacting with the display
* I would think this is extremely helpful when used in a HelpDesk situation
*/
rfbBool PermitServerInput(rfbClient* client, int enabled)
{
rfbSetServerInputMsg msg;
if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE;
/* enabled==1, then server input from local keyboard is disabled */
msg.type = rfbSetServerInput;
msg.status = (enabled ? 1 : 0);
msg.pad = 0;
return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE);
}
/*
* send xvp client message
* A client supporting the xvp extension sends this to request that the server initiate
* a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the
* client is displaying.
*
* only version 1 is defined in the protocol specs
*
* possible values for code are:
* rfbXvp_Shutdown
* rfbXvp_Reboot
* rfbXvp_Reset
*/
rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code)
{
rfbXvpMsg xvp;
if (!SupportsClient2Server(client, rfbXvp)) return TRUE;
xvp.type = rfbXvp;
xvp.pad = 0;
xvp.version = version;
xvp.code = code;
if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg))
return FALSE;
return TRUE;
}
/*
* SendPointerEvent.
*/
rfbBool
SendPointerEvent(rfbClient* client,int x, int y, int buttonMask)
{
rfbPointerEventMsg pe;
if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE;
pe.type = rfbPointerEvent;
pe.buttonMask = buttonMask;
if (x < 0) x = 0;
if (y < 0) y = 0;
pe.x = rfbClientSwap16IfLE(x);
pe.y = rfbClientSwap16IfLE(y);
return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg);
}
/*
* SendKeyEvent.
*/
rfbBool
SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down)
{
rfbKeyEventMsg ke;
if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE;
memset(&ke, 0, sizeof(ke));
ke.type = rfbKeyEvent;
ke.down = down ? 1 : 0;
ke.key = rfbClientSwap32IfLE(key);
return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg);
}
/*
* SendClientCutText.
*/
rfbBool
SendClientCutText(rfbClient* client, char *str, int len)
{
rfbClientCutTextMsg cct;
if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE;
memset(&cct, 0, sizeof(cct));
cct.type = rfbClientCutText;
cct.length = rfbClientSwap32IfLE(len);
return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) &&
WriteToRFBServer(client, str, len));
}
/*
* HandleRFBServerMessage.
*/
rfbBool
HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
if (msg.sct.length > 1<<20) {
rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length);
return FALSE;
}
buffer = malloc(msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {
free(buffer);
return FALSE;
}
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
}
#define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++)
#define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++)
#define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++, \
((uint8_t*)&(pix))[2] = *(ptr)++, \
((uint8_t*)&(pix))[3] = *(ptr)++)
/* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also
expands its arguments if they are macros */
#define CONCAT2(a,b) a##b
#define CONCAT2E(a,b) CONCAT2(a,b)
#define CONCAT3(a,b,c) a##b##c
#define CONCAT3E(a,b,c) CONCAT3(a,b,c)
#define BPP 8
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#undef BPP
#define BPP 16
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 15
#include "trle.c"
#define REALBPP 15
#include "zrle.c"
#undef BPP
#define BPP 32
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 24
#include "trle.c"
#define REALBPP 24
#include "zrle.c"
#define REALBPP 24
#define UNCOMP 8
#include "trle.c"
#define REALBPP 24
#define UNCOMP 8
#include "zrle.c"
#define REALBPP 24
#define UNCOMP -8
#include "trle.c"
#define REALBPP 24
#define UNCOMP -8
#include "zrle.c"
#undef BPP
/*
* PrintPixelFormat.
*/
void
PrintPixelFormat(rfbPixelFormat *format)
{
if (format->bitsPerPixel == 1) {
rfbClientLog(" Single bit per pixel.\n");
rfbClientLog(
" %s significant bit in each byte is leftmost on the screen.\n",
(format->bigEndian ? "Most" : "Least"));
} else {
rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel);
if (format->bitsPerPixel != 8) {
rfbClientLog(" %s significant byte first in each pixel.\n",
(format->bigEndian ? "Most" : "Least"));
}
if (format->trueColour) {
rfbClientLog(" TRUE colour: max red %d green %d blue %d"
", shift red %d green %d blue %d\n",
format->redMax, format->greenMax, format->blueMax,
format->redShift, format->greenShift, format->blueShift);
} else {
rfbClientLog(" Colour map (not true colour).\n");
}
}
}
/* avoid name clashes with LibVNCServer */
#define rfbEncryptBytes rfbClientEncryptBytes
#define rfbEncryptBytes2 rfbClientEncryptBytes2
#define rfbDes rfbClientDes
#define rfbDesKey rfbClientDesKey
#define rfbUseKey rfbClientUseKey
#include "vncauth.c"
| ./CrossVul/dataset_final_sorted/CWE-770/c/bad_4064_0 |
crossvul-cpp_data_bad_4653_0 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Extensively modified by Motonori Shindo (mshindo@mshindo.net) for more
* complete PPP support.
*/
/* \summary: Point to Point Protocol (PPP) printer */
/*
* TODO:
* o resolve XXX as much as possible
* o MP support
* o BAP support
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#ifdef __bsdi__
#include <net/slcompress.h>
#include <net/if_ppp.h>
#endif
#include <stdlib.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ppp.h"
#include "chdlc.h"
#include "ethertype.h"
#include "oui.h"
/*
* The following constatns are defined by IANA. Please refer to
* http://www.isi.edu/in-notes/iana/assignments/ppp-numbers
* for the up-to-date information.
*/
/* Protocol Codes defined in ppp.h */
static const struct tok ppptype2str[] = {
{ PPP_IP, "IP" },
{ PPP_OSI, "OSI" },
{ PPP_NS, "NS" },
{ PPP_DECNET, "DECNET" },
{ PPP_APPLE, "APPLE" },
{ PPP_IPX, "IPX" },
{ PPP_VJC, "VJC IP" },
{ PPP_VJNC, "VJNC IP" },
{ PPP_BRPDU, "BRPDU" },
{ PPP_STII, "STII" },
{ PPP_VINES, "VINES" },
{ PPP_MPLS_UCAST, "MPLS" },
{ PPP_MPLS_MCAST, "MPLS" },
{ PPP_COMP, "Compressed"},
{ PPP_ML, "MLPPP"},
{ PPP_IPV6, "IP6"},
{ PPP_HELLO, "HELLO" },
{ PPP_LUXCOM, "LUXCOM" },
{ PPP_SNS, "SNS" },
{ PPP_IPCP, "IPCP" },
{ PPP_OSICP, "OSICP" },
{ PPP_NSCP, "NSCP" },
{ PPP_DECNETCP, "DECNETCP" },
{ PPP_APPLECP, "APPLECP" },
{ PPP_IPXCP, "IPXCP" },
{ PPP_STIICP, "STIICP" },
{ PPP_VINESCP, "VINESCP" },
{ PPP_IPV6CP, "IP6CP" },
{ PPP_MPLSCP, "MPLSCP" },
{ PPP_LCP, "LCP" },
{ PPP_PAP, "PAP" },
{ PPP_LQM, "LQM" },
{ PPP_CHAP, "CHAP" },
{ PPP_EAP, "EAP" },
{ PPP_SPAP, "SPAP" },
{ PPP_SPAP_OLD, "Old-SPAP" },
{ PPP_BACP, "BACP" },
{ PPP_BAP, "BAP" },
{ PPP_MPCP, "MLPPP-CP" },
{ PPP_CCP, "CCP" },
{ 0, NULL }
};
/* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */
#define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */
#define CPCODES_CONF_REQ 1 /* Configure-Request */
#define CPCODES_CONF_ACK 2 /* Configure-Ack */
#define CPCODES_CONF_NAK 3 /* Configure-Nak */
#define CPCODES_CONF_REJ 4 /* Configure-Reject */
#define CPCODES_TERM_REQ 5 /* Terminate-Request */
#define CPCODES_TERM_ACK 6 /* Terminate-Ack */
#define CPCODES_CODE_REJ 7 /* Code-Reject */
#define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */
#define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */
#define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */
#define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */
#define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */
#define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */
#define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */
#define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */
static const struct tok cpcodes[] = {
{CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */
{CPCODES_CONF_REQ, "Conf-Request"},
{CPCODES_CONF_ACK, "Conf-Ack"},
{CPCODES_CONF_NAK, "Conf-Nack"},
{CPCODES_CONF_REJ, "Conf-Reject"},
{CPCODES_TERM_REQ, "Term-Request"},
{CPCODES_TERM_ACK, "Term-Ack"},
{CPCODES_CODE_REJ, "Code-Reject"},
{CPCODES_PROT_REJ, "Prot-Reject"},
{CPCODES_ECHO_REQ, "Echo-Request"},
{CPCODES_ECHO_RPL, "Echo-Reply"},
{CPCODES_DISC_REQ, "Disc-Req"},
{CPCODES_ID, "Ident"}, /* RFC1570 */
{CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */
{CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */
{CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */
{0, NULL}
};
/* LCP Config Options */
#define LCPOPT_VEXT 0
#define LCPOPT_MRU 1
#define LCPOPT_ACCM 2
#define LCPOPT_AP 3
#define LCPOPT_QP 4
#define LCPOPT_MN 5
#define LCPOPT_DEP6 6
#define LCPOPT_PFC 7
#define LCPOPT_ACFC 8
#define LCPOPT_FCSALT 9
#define LCPOPT_SDP 10
#define LCPOPT_NUMMODE 11
#define LCPOPT_DEP12 12
#define LCPOPT_CBACK 13
#define LCPOPT_DEP14 14
#define LCPOPT_DEP15 15
#define LCPOPT_DEP16 16
#define LCPOPT_MLMRRU 17
#define LCPOPT_MLSSNHF 18
#define LCPOPT_MLED 19
#define LCPOPT_PROP 20
#define LCPOPT_DCEID 21
#define LCPOPT_MPP 22
#define LCPOPT_LD 23
#define LCPOPT_LCPAOPT 24
#define LCPOPT_COBS 25
#define LCPOPT_PE 26
#define LCPOPT_MLHF 27
#define LCPOPT_I18N 28
#define LCPOPT_SDLOS 29
#define LCPOPT_PPPMUX 30
#define LCPOPT_MIN LCPOPT_VEXT
#define LCPOPT_MAX LCPOPT_PPPMUX
static const char *lcpconfopts[] = {
"Vend-Ext", /* (0) */
"MRU", /* (1) */
"ACCM", /* (2) */
"Auth-Prot", /* (3) */
"Qual-Prot", /* (4) */
"Magic-Num", /* (5) */
"deprecated(6)", /* used to be a Quality Protocol */
"PFC", /* (7) */
"ACFC", /* (8) */
"FCS-Alt", /* (9) */
"SDP", /* (10) */
"Num-Mode", /* (11) */
"deprecated(12)", /* used to be a Multi-Link-Procedure*/
"Call-Back", /* (13) */
"deprecated(14)", /* used to be a Connect-Time */
"deprecated(15)", /* used to be a Compund-Frames */
"deprecated(16)", /* used to be a Nominal-Data-Encap */
"MRRU", /* (17) */
"12-Bit seq #", /* (18) */
"End-Disc", /* (19) */
"Proprietary", /* (20) */
"DCE-Id", /* (21) */
"MP+", /* (22) */
"Link-Disc", /* (23) */
"LCP-Auth-Opt", /* (24) */
"COBS", /* (25) */
"Prefix-elision", /* (26) */
"Multilink-header-Form",/* (27) */
"I18N", /* (28) */
"SDL-over-SONET/SDH", /* (29) */
"PPP-Muxing", /* (30) */
};
/* ECP - to be supported */
/* CCP Config Options */
#define CCPOPT_OUI 0 /* RFC1962 */
#define CCPOPT_PRED1 1 /* RFC1962 */
#define CCPOPT_PRED2 2 /* RFC1962 */
#define CCPOPT_PJUMP 3 /* RFC1962 */
/* 4-15 unassigned */
#define CCPOPT_HPPPC 16 /* RFC1962 */
#define CCPOPT_STACLZS 17 /* RFC1974 */
#define CCPOPT_MPPC 18 /* RFC2118 */
#define CCPOPT_GFZA 19 /* RFC1962 */
#define CCPOPT_V42BIS 20 /* RFC1962 */
#define CCPOPT_BSDCOMP 21 /* RFC1977 */
/* 22 unassigned */
#define CCPOPT_LZSDCP 23 /* RFC1967 */
#define CCPOPT_MVRCA 24 /* RFC1975 */
#define CCPOPT_DEC 25 /* RFC1976 */
#define CCPOPT_DEFLATE 26 /* RFC1979 */
/* 27-254 unassigned */
#define CCPOPT_RESV 255 /* RFC1962 */
static const struct tok ccpconfopts_values[] = {
{ CCPOPT_OUI, "OUI" },
{ CCPOPT_PRED1, "Pred-1" },
{ CCPOPT_PRED2, "Pred-2" },
{ CCPOPT_PJUMP, "Puddle" },
{ CCPOPT_HPPPC, "HP-PPC" },
{ CCPOPT_STACLZS, "Stac-LZS" },
{ CCPOPT_MPPC, "MPPC" },
{ CCPOPT_GFZA, "Gand-FZA" },
{ CCPOPT_V42BIS, "V.42bis" },
{ CCPOPT_BSDCOMP, "BSD-Comp" },
{ CCPOPT_LZSDCP, "LZS-DCP" },
{ CCPOPT_MVRCA, "MVRCA" },
{ CCPOPT_DEC, "DEC" },
{ CCPOPT_DEFLATE, "Deflate" },
{ CCPOPT_RESV, "Reserved"},
{0, NULL}
};
/* BACP Config Options */
#define BACPOPT_FPEER 1 /* RFC2125 */
static const struct tok bacconfopts_values[] = {
{ BACPOPT_FPEER, "Favored-Peer" },
{0, NULL}
};
/* SDCP - to be supported */
/* IPCP Config Options */
#define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */
#define IPCPOPT_IPCOMP 2 /* RFC1332 */
#define IPCPOPT_ADDR 3 /* RFC1332 */
#define IPCPOPT_MOBILE4 4 /* RFC2290 */
#define IPCPOPT_PRIDNS 129 /* RFC1877 */
#define IPCPOPT_PRINBNS 130 /* RFC1877 */
#define IPCPOPT_SECDNS 131 /* RFC1877 */
#define IPCPOPT_SECNBNS 132 /* RFC1877 */
static const struct tok ipcpopt_values[] = {
{ IPCPOPT_2ADDR, "IP-Addrs" },
{ IPCPOPT_IPCOMP, "IP-Comp" },
{ IPCPOPT_ADDR, "IP-Addr" },
{ IPCPOPT_MOBILE4, "Home-Addr" },
{ IPCPOPT_PRIDNS, "Pri-DNS" },
{ IPCPOPT_PRINBNS, "Pri-NBNS" },
{ IPCPOPT_SECDNS, "Sec-DNS" },
{ IPCPOPT_SECNBNS, "Sec-NBNS" },
{ 0, NULL }
};
#define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */
#define IPCPOPT_IPCOMP_MINLEN 14
static const struct tok ipcpopt_compproto_values[] = {
{ PPP_VJC, "VJ-Comp" },
{ IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" },
{ 0, NULL }
};
static const struct tok ipcpopt_compproto_subopt_values[] = {
{ 1, "RTP-Compression" },
{ 2, "Enhanced RTP-Compression" },
{ 0, NULL }
};
/* IP6CP Config Options */
#define IP6CP_IFID 1
static const struct tok ip6cpopt_values[] = {
{ IP6CP_IFID, "Interface-ID" },
{ 0, NULL }
};
/* ATCP - to be supported */
/* OSINLCP - to be supported */
/* BVCP - to be supported */
/* BCP - to be supported */
/* IPXCP - to be supported */
/* MPLSCP - to be supported */
/* Auth Algorithms */
/* 0-4 Reserved (RFC1994) */
#define AUTHALG_CHAPMD5 5 /* RFC1994 */
#define AUTHALG_MSCHAP1 128 /* RFC2433 */
#define AUTHALG_MSCHAP2 129 /* RFC2795 */
static const struct tok authalg_values[] = {
{ AUTHALG_CHAPMD5, "MD5" },
{ AUTHALG_MSCHAP1, "MS-CHAPv1" },
{ AUTHALG_MSCHAP2, "MS-CHAPv2" },
{ 0, NULL }
};
/* FCS Alternatives - to be supported */
/* Multilink Endpoint Discriminator (RFC1717) */
#define MEDCLASS_NULL 0 /* Null Class */
#define MEDCLASS_LOCAL 1 /* Locally Assigned */
#define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */
#define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */
#define MEDCLASS_MNB 4 /* PPP Magic Number Block */
#define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */
/* PPP LCP Callback */
#define CALLBACK_AUTH 0 /* Location determined by user auth */
#define CALLBACK_DSTR 1 /* Dialing string */
#define CALLBACK_LID 2 /* Location identifier */
#define CALLBACK_E164 3 /* E.164 number */
#define CALLBACK_X500 4 /* X.500 distinguished name */
#define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */
static const struct tok ppp_callback_values[] = {
{ CALLBACK_AUTH, "UserAuth" },
{ CALLBACK_DSTR, "DialString" },
{ CALLBACK_LID, "LocalID" },
{ CALLBACK_E164, "E.164" },
{ CALLBACK_X500, "X.500" },
{ CALLBACK_CBCP, "CBCP" },
{ 0, NULL }
};
/* CHAP */
#define CHAP_CHAL 1
#define CHAP_RESP 2
#define CHAP_SUCC 3
#define CHAP_FAIL 4
static const struct tok chapcode_values[] = {
{ CHAP_CHAL, "Challenge" },
{ CHAP_RESP, "Response" },
{ CHAP_SUCC, "Success" },
{ CHAP_FAIL, "Fail" },
{ 0, NULL}
};
/* PAP */
#define PAP_AREQ 1
#define PAP_AACK 2
#define PAP_ANAK 3
static const struct tok papcode_values[] = {
{ PAP_AREQ, "Auth-Req" },
{ PAP_AACK, "Auth-ACK" },
{ PAP_ANAK, "Auth-NACK" },
{ 0, NULL }
};
/* BAP */
#define BAP_CALLREQ 1
#define BAP_CALLRES 2
#define BAP_CBREQ 3
#define BAP_CBRES 4
#define BAP_LDQREQ 5
#define BAP_LDQRES 6
#define BAP_CSIND 7
#define BAP_CSRES 8
static int print_lcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ipcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int);
static int print_ccp_config_options(netdissect_options *, const u_char *p, int);
static int print_bacp_config_options(netdissect_options *, const u_char *p, int);
static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length);
/* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */
static void
handle_ctrl_proto(netdissect_options *ndo,
u_int proto, const u_char *pptr, int length)
{
const char *typestr;
u_int code, len;
int (*pfunc)(netdissect_options *, const u_char *, int);
int x, j;
const u_char *tptr;
tptr=pptr;
typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto);
ND_PRINT((ndo, "%s, ", typestr));
if (length < 4) /* FIXME weak boundary checking */
goto trunc;
ND_TCHECK2(*tptr, 2);
code = *tptr++;
ND_PRINT((ndo, "%s (0x%02x), id %u, length %u",
tok2str(cpcodes, "Unknown Opcode",code),
code,
*tptr++, /* ID */
length + 2));
if (!ndo->ndo_vflag)
return;
if (length <= 4)
return; /* there may be a NULL confreq etc. */
ND_TCHECK2(*tptr, 2);
len = EXTRACT_16BITS(tptr);
tptr += 2;
ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr - 2, "\n\t", 6);
switch (code) {
case CPCODES_VEXT:
if (length < 11)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
tptr += 4;
ND_TCHECK2(*tptr, 3);
ND_PRINT((ndo, " Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)),
EXTRACT_24BITS(tptr)));
/* XXX: need to decode Kind and Value(s)? */
break;
case CPCODES_CONF_REQ:
case CPCODES_CONF_ACK:
case CPCODES_CONF_NAK:
case CPCODES_CONF_REJ:
x = len - 4; /* Code(1), Identifier(1) and Length(2) */
do {
switch (proto) {
case PPP_LCP:
pfunc = print_lcp_config_options;
break;
case PPP_IPCP:
pfunc = print_ipcp_config_options;
break;
case PPP_IPV6CP:
pfunc = print_ip6cp_config_options;
break;
case PPP_CCP:
pfunc = print_ccp_config_options;
break;
case PPP_BACP:
pfunc = print_bacp_config_options;
break;
default:
/*
* No print routine for the options for
* this protocol.
*/
pfunc = NULL;
break;
}
if (pfunc == NULL) /* catch the above null pointer if unknown CP */
break;
if ((j = (*pfunc)(ndo, tptr, len)) == 0)
break;
x -= j;
tptr += j;
} while (x > 0);
break;
case CPCODES_TERM_REQ:
case CPCODES_TERM_ACK:
/* XXX: need to decode Data? */
break;
case CPCODES_CODE_REJ:
/* XXX: need to decode Rejected-Packet? */
break;
case CPCODES_PROT_REJ:
if (length < 6)
break;
ND_TCHECK2(*tptr, 2);
ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)",
tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
/* XXX: need to decode Rejected-Information? - hexdump for now */
if (len > 6) {
ND_PRINT((ndo, "\n\t Rejected Packet"));
print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2);
}
break;
case CPCODES_ECHO_REQ:
case CPCODES_ECHO_RPL:
case CPCODES_DISC_REQ:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* XXX: need to decode Data? - hexdump for now */
if (len > 8) {
ND_PRINT((ndo, "\n\t -----trailing data-----"));
ND_TCHECK2(tptr[4], len - 8);
print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8);
}
break;
case CPCODES_ID:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* RFC 1661 says this is intended to be human readable */
if (len > 8) {
ND_PRINT((ndo, "\n\t Message\n\t "));
if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend))
goto trunc;
}
break;
case CPCODES_TIME_REM:
if (length < 12)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4)));
/* XXX: need to decode Message? */
break;
default:
/* XXX this is dirty but we do not get the
* original pointer passed to the begin
* the PPP packet */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2);
break;
}
return;
trunc:
ND_PRINT((ndo, "[|%s]", typestr));
}
/* LCP config options */
static int
print_lcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
lcpconfopts[opt], opt, len));
else
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return 0;
}
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len));
else {
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return len;
}
switch (opt) {
case LCPOPT_VEXT:
if (len < 6) {
ND_PRINT((ndo, " (length bogus, should be >= 6)"));
return len;
}
ND_TCHECK_24BITS(p + 2);
ND_PRINT((ndo, ": Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)),
EXTRACT_24BITS(p + 2)));
#if 0
ND_TCHECK(p[5]);
ND_PRINT((ndo, ", kind: 0x%02x", p[5]));
ND_PRINT((ndo, ", Value: 0x"));
for (i = 0; i < len - 6; i++) {
ND_TCHECK(p[6 + i]);
ND_PRINT((ndo, "%02x", p[6 + i]));
}
#endif
break;
case LCPOPT_MRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return len;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_ACCM:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK_32BITS(p + 2);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_AP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2))));
switch (EXTRACT_16BITS(p+2)) {
case PPP_CHAP:
ND_TCHECK(p[4]);
ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4])));
break;
case PPP_PAP: /* fall through */
case PPP_EAP:
case PPP_SPAP:
case PPP_SPAP_OLD:
break;
default:
print_unknown_data(ndo, p, "\n\t", len);
}
break;
case LCPOPT_QP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK_16BITS(p+2);
if (EXTRACT_16BITS(p+2) == PPP_LQM)
ND_PRINT((ndo, ": LQR"));
else
ND_PRINT((ndo, ": unknown"));
break;
case LCPOPT_MN:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK_32BITS(p + 2);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_PFC:
break;
case LCPOPT_ACFC:
break;
case LCPOPT_LD:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_CBACK:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_PRINT((ndo, ": "));
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Callback Operation %s (%u)",
tok2str(ppp_callback_values, "Unknown", p[2]),
p[2]));
break;
case LCPOPT_MLMRRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_MLED:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_TCHECK(p[2]);
switch (p[2]) { /* class */
case MEDCLASS_NULL:
ND_PRINT((ndo, ": Null"));
break;
case MEDCLASS_LOCAL:
ND_PRINT((ndo, ": Local")); /* XXX */
break;
case MEDCLASS_IPV4:
if (len != 7) {
ND_PRINT((ndo, " (length bogus, should be = 7)"));
return 0;
}
ND_TCHECK2(*(p + 3), 4);
ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3)));
break;
case MEDCLASS_MAC:
if (len != 9) {
ND_PRINT((ndo, " (length bogus, should be = 9)"));
return 0;
}
ND_TCHECK2(*(p + 3), 6);
ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3)));
break;
case MEDCLASS_MNB:
ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */
break;
case MEDCLASS_PSNDN:
ND_PRINT((ndo, ": PSNDN")); /* XXX */
break;
default:
ND_PRINT((ndo, ": Unknown class %u", p[2]));
break;
}
break;
/* XXX: to be supported */
#if 0
case LCPOPT_DEP6:
case LCPOPT_FCSALT:
case LCPOPT_SDP:
case LCPOPT_NUMMODE:
case LCPOPT_DEP12:
case LCPOPT_DEP14:
case LCPOPT_DEP15:
case LCPOPT_DEP16:
case LCPOPT_MLSSNHF:
case LCPOPT_PROP:
case LCPOPT_DCEID:
case LCPOPT_MPP:
case LCPOPT_LCPAOPT:
case LCPOPT_COBS:
case LCPOPT_PE:
case LCPOPT_MLHF:
case LCPOPT_I18N:
case LCPOPT_SDLOS:
case LCPOPT_PPPMUX:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|lcp]"));
return 0;
}
/* ML-PPP*/
static const struct tok ppp_ml_flag_values[] = {
{ 0x80, "begin" },
{ 0x40, "end" },
{ 0, NULL }
};
static void
handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
if (length < 2) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
if (!ND_TTEST_16BITS(p)) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
/* CHAP */
static void
handle_chap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int val_size, name_size, msg_size;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|chap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|chap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "CHAP, %s (0x%02x)",
tok2str(chapcode_values,"unknown",code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
/*
* Note that this is a generic CHAP decoding routine. Since we
* don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1,
* MS-CHAPv2) is used at this point, we can't decode packet
* specifically to each algorithms. Instead, we simply decode
* the GCD (Gratest Common Denominator) for all algorithms.
*/
switch (code) {
case CHAP_CHAL:
case CHAP_RESP:
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
val_size = *p; /* value size */
p++;
if (length - (p - p0) < val_size)
return;
ND_PRINT((ndo, ", Value "));
for (i = 0; i < val_size; i++) {
ND_TCHECK(*p);
ND_PRINT((ndo, "%02x", *p++));
}
name_size = len - (p - p0);
ND_PRINT((ndo, ", Name "));
for (i = 0; i < name_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case CHAP_SUCC:
case CHAP_FAIL:
msg_size = len - (p - p0);
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|chap]"));
}
/* PAP (see RFC 1334) */
static void
handle_pap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int peerid_len, passwd_len, msg_len;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|pap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|pap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "PAP, %s (0x%02x)",
tok2str(papcode_values, "unknown", code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
if ((int)len > length) {
ND_PRINT((ndo, ", length %u > packet size", len));
return;
}
length = len;
if (length < (p - p0)) {
ND_PRINT((ndo, ", length %u < PAP header length", length));
return;
}
switch (code) {
case PAP_AREQ:
/* A valid Authenticate-Request is 6 or more octets long. */
if (len < 6)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
peerid_len = *p; /* Peer-ID Length */
p++;
if (length - (p - p0) < peerid_len)
return;
ND_PRINT((ndo, ", Peer "));
for (i = 0; i < peerid_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
passwd_len = *p; /* Password Length */
p++;
if (length - (p - p0) < passwd_len)
return;
ND_PRINT((ndo, ", Name "));
for (i = 0; i < passwd_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case PAP_AACK:
case PAP_ANAK:
/* Although some implementations ignore truncation at
* this point and at least one generates a truncated
* packet, RFC 1334 section 2.2.2 clearly states that
* both AACK and ANAK are at least 5 bytes long.
*/
if (len < 5)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
msg_len = *p; /* Msg-Length */
p++;
if (length - (p - p0) < msg_len)
return;
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pap]"));
}
/* BAP */
static void
handle_bap(netdissect_options *ndo _U_,
const u_char *p _U_, int length _U_)
{
/* XXX: to be supported!! */
}
/* IPCP config options */
static int
print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK_16BITS(p+2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
/* IP6CP config options */
static int
print_ip6cp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IP6CP_IFID:
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 2), 8);
ND_PRINT((ndo, ": %04x:%04x:%04x:%04x",
EXTRACT_16BITS(p + 2),
EXTRACT_16BITS(p + 4),
EXTRACT_16BITS(p + 6),
EXTRACT_16BITS(p + 8)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ip6cp]"));
return 0;
}
/* CCP config options */
static int
print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
/* BACP config options */
static int
print_bacp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case BACPOPT_FPEER:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK_32BITS(p + 2);
ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|bacp]"));
return 0;
}
static void
ppp_hdlc(netdissect_options *ndo,
const u_char *p, int length)
{
u_char *b, *t, c;
const u_char *s;
int i, proto;
const void *se;
if (length <= 0)
return;
b = (u_char *)malloc(length);
if (b == NULL)
return;
/*
* Unescape all the data into a temporary, private, buffer.
* Do this so that we dont overwrite the original packet
* contents.
*/
for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) {
c = *s++;
if (c == 0x7d) {
if (i <= 1 || !ND_TTEST(*s))
break;
i--;
c = *s++ ^ 0x20;
}
*t++ = c;
}
se = ndo->ndo_snapend;
ndo->ndo_snapend = t;
length = t - b;
/* now lets guess about the payload codepoint format */
if (length < 1)
goto trunc;
proto = *b; /* start with a one-octet codepoint guess */
switch (proto) {
case PPP_IP:
ip_print(ndo, b + 1, length - 1);
goto cleanup;
case PPP_IPV6:
ip6_print(ndo, b + 1, length - 1);
goto cleanup;
default: /* no luck - try next guess */
break;
}
if (length < 2)
goto trunc;
proto = EXTRACT_16BITS(b); /* next guess - load two octets */
switch (proto) {
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */
if (length < 4)
goto trunc;
proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */
handle_ppp(ndo, proto, b + 4, length - 4);
break;
default: /* last guess - proto must be a PPP proto-id */
handle_ppp(ndo, proto, b + 2, length - 2);
break;
}
cleanup:
ndo->ndo_snapend = se;
free(b);
return;
trunc:
ndo->ndo_snapend = se;
free(b);
ND_PRINT((ndo, "[|ppp]"));
}
/* PPP */
static void
handle_ppp(netdissect_options *ndo,
u_int proto, const u_char *p, int length)
{
if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */
ppp_hdlc(ndo, p - 1, length);
return;
}
switch (proto) {
case PPP_LCP: /* fall through */
case PPP_IPCP:
case PPP_OSICP:
case PPP_MPLSCP:
case PPP_IPV6CP:
case PPP_CCP:
case PPP_BACP:
handle_ctrl_proto(ndo, proto, p, length);
break;
case PPP_ML:
handle_mlppp(ndo, p, length);
break;
case PPP_CHAP:
handle_chap(ndo, p, length);
break;
case PPP_PAP:
handle_pap(ndo, p, length);
break;
case PPP_BAP: /* XXX: not yet completed */
handle_bap(ndo, p, length);
break;
case ETHERTYPE_IP: /*XXX*/
case PPP_VJNC:
case PPP_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6: /*XXX*/
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case ETHERTYPE_IPX: /*XXX*/
case PPP_IPX:
ipx_print(ndo, p, length);
break;
case PPP_OSI:
isoclns_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
case PPP_COMP:
ND_PRINT((ndo, "compressed PPP data"));
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
/* Standard PPP printer */
u_int
ppp_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int proto,ppp_header;
u_int olen = length; /* _o_riginal length */
u_int hdr_len = 0;
/*
* Here, we assume that p points to the Address and Control
* field (if they present).
*/
if (length < 2)
goto trunc;
ND_TCHECK2(*p, 2);
ppp_header = EXTRACT_16BITS(p);
switch(ppp_header) {
case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "In "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "Out "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL):
p += 2; /* ACFC not used */
length -= 2;
hdr_len += 2;
break;
default:
break;
}
if (length < 2)
goto trunc;
ND_TCHECK(*p);
if (*p % 2) {
proto = *p; /* PFC is used */
p++;
length--;
hdr_len++;
} else {
ND_TCHECK2(*p, 2);
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdr_len += 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s (0x%04x), length %u: ",
tok2str(ppptype2str, "unknown", proto),
proto,
olen));
handle_ppp(ndo, proto, p, length);
return (hdr_len);
trunc:
ND_PRINT((ndo, "[|ppp]"));
return (0);
}
/* PPP I/F printer */
u_int
ppp_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
if (caplen < PPP_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
#if 0
/*
* XXX: seems to assume that there are 2 octets prepended to an
* actual PPP frame. The 1st octet looks like Input/Output flag
* while 2nd octet is unknown, at least to me
* (mshindo@mshindo.net).
*
* That was what the original tcpdump code did.
*
* FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound
* packets and 0 for inbound packets - but only if the
* protocol field has the 0x8000 bit set (i.e., it's a network
* control protocol); it does so before running the packet through
* "bpf_filter" to see if it should be discarded, and to see
* if we should update the time we sent the most recent packet...
*
* ...but it puts the original address field back after doing
* so.
*
* NetBSD's "if_ppp.c" doesn't set the first octet in that fashion.
*
* I don't know if any PPP implementation handed up to a BPF
* device packets with the first octet being 1 for outbound and
* 0 for inbound packets, so I (guy@alum.mit.edu) don't know
* whether that ever needs to be checked or not.
*
* Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP,
* and its tcpdump appears to assume that the frame always
* begins with an address field and a control field, and that
* the address field might be 0x0f or 0x8f, for Cisco
* point-to-point with HDLC framing as per section 4.3.1 of RFC
* 1547, as well as 0xff, for PPP in HDLC-like framing as per
* RFC 1662.
*
* (Is the Cisco framing in question what DLT_C_HDLC, in
* BSD/OS, is?)
*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1]));
#endif
ppp_print(ndo, p, length);
return (0);
}
/*
* PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like
* framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547,
* is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL,
* discard them *if* those are the first two octets, and parse the remaining
* packet as a PPP packet, as "ppp_print()" does).
*
* This handles, for example, DLT_PPP_SERIAL in NetBSD.
*/
u_int
ppp_hdlc_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
u_int proto;
u_int hdrlen = 0;
if (caplen < 2) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
switch (p[0]) {
case PPP_ADDRESS:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
length -= 2;
hdrlen += 2;
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdrlen += 2;
ND_PRINT((ndo, "%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
handle_ppp(ndo, proto, p, length);
break;
case CHDLC_UNICAST:
case CHDLC_BCAST:
return (chdlc_if_print(ndo, h, p));
default:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
hdrlen += 2;
/*
* XXX - NetBSD's "ppp_netbsd_serial_if_print()" treats
* the next two octets as an Ethernet type; does that
* ever happen?
*/
ND_PRINT((ndo, "unknown addr %02x; ctrl %02x", p[0], p[1]));
break;
}
return (hdrlen);
}
#define PPP_BSDI_HDRLEN 24
/* BSD/OS specific PPP printer */
u_int
ppp_bsdos_if_print(netdissect_options *ndo _U_,
const struct pcap_pkthdr *h _U_, register const u_char *p _U_)
{
register int hdrlength;
#ifdef __bsdi__
register u_int length = h->len;
register u_int caplen = h->caplen;
uint16_t ptype;
const u_char *q;
int i;
if (caplen < PPP_BSDI_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen)
}
hdrlength = 0;
#if 0
if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", p[0], p[1]));
p += 2;
hdrlength = 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
/* Retrieve the protocol type */
if (*p & 01) {
/* Compressed protocol field */
ptype = *p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x ", ptype));
p++;
hdrlength += 1;
} else {
/* Un-compressed protocol field */
ptype = EXTRACT_16BITS(p);
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%04x ", ptype));
p += 2;
hdrlength += 2;
}
#else
ptype = 0; /*XXX*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c ", p[SLC_DIR] ? 'O' : 'I'));
if (p[SLC_LLHL]) {
/* link level header */
struct ppp_header *ph;
q = p + SLC_BPFHDRLEN;
ph = (struct ppp_header *)q;
if (ph->phdr_addr == PPP_ADDRESS
&& ph->phdr_ctl == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", q[0], q[1]));
ptype = EXTRACT_16BITS(&ph->phdr_type);
if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) {
ND_PRINT((ndo, "%s ", tok2str(ppptype2str,
"proto-#%d", ptype)));
}
} else {
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "LLH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
}
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
if (p[SLC_CHL]) {
q = p + SLC_BPFHDRLEN + p[SLC_LLHL];
switch (ptype) {
case PPP_VJC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
case PPP_VJNC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
default:
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "CH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
break;
}
}
hdrlength = PPP_BSDI_HDRLEN;
#endif
length -= hdrlength;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype)));
}
printx:
#else /* __bsdi */
hdrlength = 0;
#endif /* __bsdi__ */
return (hdrlength);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-770/c/bad_4653_0 |
crossvul-cpp_data_good_4064_0 | /*
* Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved.
* Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
/*
* rfbproto.c - functions to deal with client side of RFB protocol.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#define _XOPEN_SOURCE 600
#endif
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#endif
#include <errno.h>
#include <rfb/rfbclient.h>
#ifdef WIN32
#undef socklen_t
#endif
#ifdef LIBVNCSERVER_HAVE_LIBZ
#include <zlib.h>
#ifdef __CHECKER__
#undef Z_NULL
#define Z_NULL NULL
#endif
#endif
#ifndef _MSC_VER
/* Strings.h is not available in MSVC */
#include <strings.h>
#endif
#include <stdarg.h>
#include <time.h>
#include "crypto.h"
#include "sasl.h"
#ifdef LIBVNCSERVER_HAVE_LZO
#include <lzo/lzo1x.h>
#else
#include "minilzo.h"
#endif
#include "tls.h"
#define MAX_TEXTCHAT_SIZE 10485760 /* 10MB */
/*
* rfbClientLog prints a time-stamped message to the log file (stderr).
*/
rfbBool rfbEnableClientLogging=TRUE;
static void
rfbDefaultClientLog(const char *format, ...)
{
va_list args;
char buf[256];
time_t log_clock;
if(!rfbEnableClientLogging)
return;
va_start(args, format);
time(&log_clock);
strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock));
fprintf(stderr, "%s", buf);
vfprintf(stderr, format, args);
fflush(stderr);
va_end(args);
}
rfbClientLogProc rfbClientLog=rfbDefaultClientLog;
rfbClientLogProc rfbClientErr=rfbDefaultClientLog;
/* extensions */
rfbClientProtocolExtension* rfbClientExtensions = NULL;
void rfbClientRegisterExtension(rfbClientProtocolExtension* e)
{
e->next = rfbClientExtensions;
rfbClientExtensions = e;
}
/* client data */
void rfbClientSetClientData(rfbClient* client, void* tag, void* data)
{
rfbClientData* clientData = client->clientData;
while(clientData && clientData->tag != tag)
clientData = clientData->next;
if(clientData == NULL) {
clientData = calloc(sizeof(rfbClientData), 1);
clientData->next = client->clientData;
client->clientData = clientData;
clientData->tag = tag;
}
clientData->data = data;
}
void* rfbClientGetClientData(rfbClient* client, void* tag)
{
rfbClientData* clientData = client->clientData;
while(clientData) {
if(clientData->tag == tag)
return clientData->data;
clientData = clientData->next;
}
return NULL;
}
static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBZ
static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh);
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh);
static long ReadCompactLen (rfbClient* client);
#endif
static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh);
static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh);
#endif
/*
* Server Capability Functions
*/
rfbBool
SupportsClient2Server(rfbClient* client, int messageType)
{
return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
rfbBool
SupportsServer2Client(rfbClient* client, int messageType)
{
return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE);
}
void
SetClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
SetServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8));
}
void
ClearClient2Server(rfbClient* client, int messageType)
{
client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= ~(1<<(messageType % 8));
}
void
ClearServer2Client(rfbClient* client, int messageType)
{
client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= ~(1<<(messageType % 8));
}
void
DefaultSupportedMessages(rfbClient* client)
{
memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages));
/* Default client supported messages (universal RFB 3.3 protocol) */
SetClient2Server(client, rfbSetPixelFormat);
/* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */
SetClient2Server(client, rfbSetEncodings);
SetClient2Server(client, rfbFramebufferUpdateRequest);
SetClient2Server(client, rfbKeyEvent);
SetClient2Server(client, rfbPointerEvent);
SetClient2Server(client, rfbClientCutText);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbFramebufferUpdate);
SetServer2Client(client, rfbSetColourMapEntries);
SetServer2Client(client, rfbBell);
SetServer2Client(client, rfbServerCutText);
}
void
DefaultSupportedMessagesUltraVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetScale);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
SetClient2Server(client, rfbTextChat);
SetClient2Server(client, rfbPalmVNCSetScaleFactor);
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbResizeFrameBuffer);
SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer);
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
void
DefaultSupportedMessagesTightVNC(rfbClient* client)
{
DefaultSupportedMessages(client);
SetClient2Server(client, rfbFileTransfer);
SetClient2Server(client, rfbSetServerInput);
SetClient2Server(client, rfbSetSW);
/* SetClient2Server(client, rfbTextChat); */
/* technically, we only care what we can *send* to the server */
SetServer2Client(client, rfbFileTransfer);
SetServer2Client(client, rfbTextChat);
}
#ifndef WIN32
static rfbBool
IsUnixSocket(const char *name)
{
struct stat sb;
if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK)
return TRUE;
return FALSE;
}
#endif
/*
* ConnectToRFBServer.
*/
rfbBool
ConnectToRFBServer(rfbClient* client,const char *hostname, int port)
{
if (client->serverPort==-1) {
/* serverHost is a file recorded by vncrec. */
const char* magic="vncLog0.0";
char buffer[10];
rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec));
client->vncRec = rec;
rec->file = fopen(client->serverHost,"rb");
rec->tv.tv_sec = 0;
rec->readTimestamp = FALSE;
rec->doNotSleep = FALSE;
if (!rec->file) {
rfbClientLog("Could not open %s.\n",client->serverHost);
return FALSE;
}
setbuf(rec->file,NULL);
if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) {
rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost);
fclose(rec->file);
return FALSE;
}
client->sock = RFB_INVALID_SOCKET;
return TRUE;
}
#ifndef WIN32
if(IsUnixSocket(hostname))
/* serverHost is a UNIX socket. */
client->sock = ConnectClientToUnixSockWithTimeout(hostname, client->connectTimeout);
else
#endif
{
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6WithTimeout(hostname, port, client->connectTimeout);
#else
unsigned int host;
/* serverHost is a hostname */
if (!StringToIPAddr(hostname, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", hostname);
return FALSE;
}
client->sock = ConnectClientToTcpAddrWithTimeout(host, port, client->connectTimeout);
#endif
}
if (client->sock == RFB_INVALID_SOCKET) {
rfbClientLog("Unable to connect to VNC server\n");
return FALSE;
}
if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP))
return FALSE;
return TRUE;
}
/*
* ConnectToRFBRepeater.
*/
rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort)
{
rfbProtocolVersionMsg pv;
int major,minor;
char tmphost[250];
#ifdef LIBVNCSERVER_IPv6
client->sock = ConnectClientToTcpAddr6WithTimeout(repeaterHost, repeaterPort, client->connectTimeout);
#else
unsigned int host;
if (!StringToIPAddr(repeaterHost, &host)) {
rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost);
return FALSE;
}
client->sock = ConnectClientToTcpAddrWithTimeout(host, repeaterPort, client->connectTimeout);
#endif
if (client->sock == RFB_INVALID_SOCKET) {
rfbClientLog("Unable to connect to VNC repeater\n");
return FALSE;
}
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg))
return FALSE;
pv[sz_rfbProtocolVersionMsg] = 0;
/* UltraVNC repeater always report version 000.000 to identify itself */
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) {
rfbClientLog("Not a valid VNC repeater (%s)\n",pv);
return FALSE;
}
rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor);
memset(tmphost, 0, sizeof(tmphost));
if(snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort) >= (int)sizeof(tmphost))
return FALSE; /* output truncated */
if (!WriteToRFBServer(client, tmphost, sizeof(tmphost)))
return FALSE;
return TRUE;
}
extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd);
extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key);
static void
ReadReason(rfbClient* client)
{
uint32_t reasonLen;
char *reason;
if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return;
reasonLen = rfbClientSwap32IfLE(reasonLen);
if(reasonLen > 1<<20) {
rfbClientLog("VNC connection failed, but sent reason length of %u exceeds limit of 1MB",(unsigned int)reasonLen);
return;
}
reason = malloc(reasonLen+1);
if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; }
reason[reasonLen]=0;
rfbClientLog("VNC connection failed: %s\n",reason);
free(reason);
}
rfbBool
rfbHandleAuthResult(rfbClient* client)
{
uint32_t authResult=0;
if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;
authResult = rfbClientSwap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
rfbClientLog("VNC authentication succeeded\n");
return TRUE;
break;
case rfbVncAuthFailed:
if (client->major==3 && client->minor>7)
{
/* we have an error following */
ReadReason(client);
return FALSE;
}
rfbClientLog("VNC authentication failed\n");
return FALSE;
case rfbVncAuthTooMany:
rfbClientLog("VNC authentication failed - too many tries\n");
return FALSE;
}
rfbClientLog("Unknown VNC authentication result: %d\n",
(int)authResult);
return FALSE;
}
static rfbBool
ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth)
{
uint8_t count=0;
uint8_t loop=0;
uint8_t flag=0;
rfbBool extAuthHandler;
uint8_t tAuth[256];
char buf1[500],buf2[10];
uint32_t authScheme;
rfbClientProtocolExtension* e;
if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE;
if (count==0)
{
rfbClientLog("List of security types is ZERO, expecting an error to follow\n");
ReadReason(client);
return FALSE;
}
rfbClientLog("We have %d security types to read\n", count);
authScheme=0;
/* now, we have a list of available security types to read ( uint8_t[] ) */
for (loop=0;loop<count;loop++)
{
if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]);
if (flag) continue;
extAuthHandler=FALSE;
for (e = rfbClientExtensions; e; e = e->next) {
if (!e->handleAuthentication) continue;
uint32_t const* secType;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (tAuth[loop]==*secType) {
extAuthHandler=TRUE;
}
}
}
if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth ||
extAuthHandler ||
#if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL)
tAuth[loop]==rfbVeNCrypt ||
#endif
#ifdef LIBVNCSERVER_HAVE_SASL
tAuth[loop]==rfbSASL ||
#endif /* LIBVNCSERVER_HAVE_SASL */
(tAuth[loop]==rfbARD && client->GetCredential) ||
(!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential))))
{
if (!subAuth && client->clientAuthSchemes)
{
int i;
for (i=0;client->clientAuthSchemes[i];i++)
{
if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop])
{
flag++;
authScheme=tAuth[loop];
break;
}
}
}
else
{
flag++;
authScheme=tAuth[loop];
}
if (flag)
{
rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count);
/* send back a single byte indicating which security type to use */
if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE;
}
}
}
if (authScheme==0)
{
memset(buf1, 0, sizeof(buf1));
for (loop=0;loop<count;loop++)
{
if (strlen(buf1)>=sizeof(buf1)-1) break;
snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]);
strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1);
}
rfbClientLog("Unknown authentication scheme from VNC server: %s\n",
buf1);
return FALSE;
}
*result = authScheme;
return TRUE;
}
static rfbBool
HandleVncAuth(rfbClient *client)
{
uint8_t challenge[CHALLENGESIZE];
char *passwd=NULL;
int i;
if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
if (client->serverPort!=-1) { /* if not playing a vncrec file */
if (client->GetPassword)
passwd = client->GetPassword(client);
if ((!passwd) || (strlen(passwd) == 0)) {
rfbClientLog("Reading password failed\n");
return FALSE;
}
if (strlen(passwd) > 8) {
passwd[8] = '\0';
}
rfbClientEncryptBytes(challenge, passwd);
/* Lose the password from memory */
for (i = strlen(passwd); i >= 0; i--) {
passwd[i] = '\0';
}
free(passwd);
if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE;
}
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
static void
FreeUserCredential(rfbCredential *cred)
{
if (cred->userCredential.username) free(cred->userCredential.username);
if (cred->userCredential.password) free(cred->userCredential.password);
free(cred);
}
static rfbBool
HandlePlainAuth(rfbClient *client)
{
uint32_t ulen, ulensw;
uint32_t plen, plensw;
rfbCredential *cred;
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0);
ulensw = rfbClientSwap32IfLE(ulen);
plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0);
plensw = rfbClientSwap32IfLE(plen);
if (!WriteToRFBServer(client, (char *)&ulensw, 4) ||
!WriteToRFBServer(client, (char *)&plensw, 4))
{
FreeUserCredential(cred);
return FALSE;
}
if (ulen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.username, ulen))
{
FreeUserCredential(cred);
return FALSE;
}
}
if (plen > 0)
{
if (!WriteToRFBServer(client, cred->userCredential.password, plen))
{
FreeUserCredential(cred);
return FALSE;
}
}
FreeUserCredential(cred);
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
/* Simple 64bit big integer arithmetic implementation */
/* (x + y) % m, works even if (x + y) > 64bit */
#define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0))
/* (x * y) % m */
static uint64_t
rfbMulM64(uint64_t x, uint64_t y, uint64_t m)
{
uint64_t r;
for(r=0;x>0;x>>=1)
{
if (x&1) r=rfbAddM64(r,y,m);
y=rfbAddM64(y,y,m);
}
return r;
}
/* (x ^ y) % m */
static uint64_t
rfbPowM64(uint64_t b, uint64_t e, uint64_t m)
{
uint64_t r;
for(r=1;e>0;e>>=1)
{
if(e&1) r=rfbMulM64(r,b,m);
b=rfbMulM64(b,b,m);
}
return r;
}
static rfbBool
HandleMSLogonAuth(rfbClient *client)
{
uint64_t gen, mod, resp, priv, pub, key;
uint8_t username[256], password[64];
rfbCredential *cred;
if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE;
gen = rfbClientSwap64IfLE(gen);
mod = rfbClientSwap64IfLE(mod);
resp = rfbClientSwap64IfLE(resp);
if (!client->GetCredential)
{
rfbClientLog("GetCredential callback is not set.\n");
return FALSE;
}
rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\
"Use it only with SSH tunnel or trusted network.\n");
cred = client->GetCredential(client, rfbCredentialTypeUser);
if (!cred)
{
rfbClientLog("Reading credential failed\n");
return FALSE;
}
memset(username, 0, sizeof(username));
strncpy((char *)username, cred->userCredential.username, sizeof(username)-1);
memset(password, 0, sizeof(password));
strncpy((char *)password, cred->userCredential.password, sizeof(password)-1);
FreeUserCredential(cred);
srand(time(NULL));
priv = ((uint64_t)rand())<<32;
priv |= (uint64_t)rand();
pub = rfbPowM64(gen, priv, mod);
key = rfbPowM64(resp, priv, mod);
pub = rfbClientSwap64IfLE(pub);
key = rfbClientSwap64IfLE(key);
rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key);
rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key);
if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE;
if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE;
if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client)) return FALSE;
return TRUE;
}
static rfbBool
HandleARDAuth(rfbClient *client)
{
uint8_t gen[2], len[2];
size_t keylen;
uint8_t *mod = NULL, *resp = NULL, *priv = NULL, *pub = NULL, *key = NULL, *shared = NULL;
uint8_t userpass[128], ciphertext[128];
int ciphertext_len;
int passwordLen, usernameLen;
rfbCredential *cred = NULL;
rfbBool result = FALSE;
/* Step 1: Read the authentication material from the socket.
A two-byte generator value, a two-byte key length value. */
if (!ReadFromRFBServer(client, (char *)gen, 2)) {
rfbClientErr("HandleARDAuth: reading generator value failed\n");
goto out;
}
if (!ReadFromRFBServer(client, (char *)len, 2)) {
rfbClientErr("HandleARDAuth: reading key length failed\n");
goto out;
}
keylen = 256*len[0]+len[1]; /* convert from char[] to int */
mod = (uint8_t*)malloc(keylen*5); /* the block actually contains mod, resp, pub, priv and key */
if (!mod)
goto out;
resp = mod+keylen;
pub = resp+keylen;
priv = pub+keylen;
key = priv+keylen;
/* Step 1: Read the authentication material from the socket.
The prime modulus (keylen bytes) and the peer's generated public key (keylen bytes). */
if (!ReadFromRFBServer(client, (char *)mod, keylen)) {
rfbClientErr("HandleARDAuth: reading prime modulus failed\n");
goto out;
}
if (!ReadFromRFBServer(client, (char *)resp, keylen)) {
rfbClientErr("HandleARDAuth: reading peer's generated public key failed\n");
goto out;
}
/* Step 2: Generate own Diffie-Hellman public-private key pair. */
if(!dh_generate_keypair(priv, pub, gen, 2, mod, keylen)) {
rfbClientErr("HandleARDAuth: generating keypair failed\n");
goto out;
}
/* Step 3: Perform Diffie-Hellman key agreement, using the generator (gen),
prime (mod), and the peer's public key. The output will be a shared
secret known to both us and the peer. */
if(!dh_compute_shared_key(key, priv, resp, mod, keylen)) {
rfbClientErr("HandleARDAuth: creating shared key failed\n");
goto out;
}
/* Step 4: Perform an MD5 hash of the shared secret.
This 128-bit (16-byte) value will be used as the AES key. */
shared = malloc(MD5_HASH_SIZE);
if(!hash_md5(shared, key, keylen)) {
rfbClientErr("HandleARDAuth: hashing shared key failed\n");
goto out;
}
/* Step 5: Pack the username and password into a 128-byte
plaintext "userpass" structure: { username[64], password[64] }.
Null-terminate each. Fill the unused bytes with random characters
so that the encryption output is less predictable. */
if(!client->GetCredential) {
rfbClientErr("HandleARDAuth: GetCredential callback is not set\n");
goto out;
}
cred = client->GetCredential(client, rfbCredentialTypeUser);
if(!cred) {
rfbClientErr("HandleARDAuth: reading credential failed\n");
goto out;
}
passwordLen = strlen(cred->userCredential.password)+1;
usernameLen = strlen(cred->userCredential.username)+1;
if (passwordLen > sizeof(userpass)/2)
passwordLen = sizeof(userpass)/2;
if (usernameLen > sizeof(userpass)/2)
usernameLen = sizeof(userpass)/2;
random_bytes(userpass, sizeof(userpass));
memcpy(userpass, cred->userCredential.username, usernameLen);
memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen);
/* Step 6: Encrypt the plaintext credentials with the 128-bit MD5 hash
from step 4, using the AES 128-bit symmetric cipher in electronic
codebook (ECB) mode. Use no further padding for this block cipher. */
if(!encrypt_aes128ecb(ciphertext, &ciphertext_len, shared, userpass, sizeof(userpass))) {
rfbClientErr("HandleARDAuth: encrypting credentials failed\n");
goto out;
}
/* Step 7: Write the ciphertext from step 6 to the stream.
Write the generated DH public key to the stream. */
if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext)))
goto out;
if (!WriteToRFBServer(client, (char *)pub, keylen))
goto out;
/* Handle the SecurityResult message */
if (!rfbHandleAuthResult(client))
goto out;
result = TRUE;
out:
if (cred)
FreeUserCredential(cred);
free(mod);
free(shared);
return result;
}
/*
* SetClientAuthSchemes.
*/
void
SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size)
{
int i;
if (client->clientAuthSchemes)
{
free(client->clientAuthSchemes);
client->clientAuthSchemes = NULL;
}
if (authSchemes)
{
if (size<0)
{
/* If size<0 we assume the passed-in list is also 0-terminate, so we
* calculate the size here */
for (size=0;authSchemes[size];size++) ;
}
client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1));
for (i=0;i<size;i++)
client->clientAuthSchemes[i] = authSchemes[i];
client->clientAuthSchemes[size] = 0;
}
}
/*
* InitialiseRFBConnection.
*/
rfbBool
InitialiseRFBConnection(rfbClient* client)
{
rfbProtocolVersionMsg pv;
int major,minor;
uint32_t authScheme;
uint32_t subAuthScheme;
rfbClientInitMsg ci;
/* if the connection is immediately closed, don't report anything, so
that pmw's monitor can make test connections */
if (client->listenSpecified)
errorMessageOnReadFailure = FALSE;
if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
pv[sz_rfbProtocolVersionMsg]=0;
errorMessageOnReadFailure = TRUE;
pv[sz_rfbProtocolVersionMsg] = 0;
if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) {
rfbClientLog("Not a valid VNC server (%s)\n",pv);
return FALSE;
}
DefaultSupportedMessages(client);
client->major = major;
client->minor = minor;
/* fall back to viewer supported version */
if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion))
client->minor = rfbProtocolMinorVersion;
/* UltraVNC uses minor codes 4 and 6 for the server */
if (major==3 && (minor==4 || minor==6)) {
rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* UltraVNC Single Click uses minor codes 14 and 16 for the server */
if (major==3 && (minor==14 || minor==16)) {
minor = minor - 10;
client->minor = minor;
rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv);
DefaultSupportedMessagesUltraVNC(client);
}
/* TightVNC uses minor codes 5 for the server */
if (major==3 && minor==5) {
rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv);
DefaultSupportedMessagesTightVNC(client);
}
/* we do not support > RFB3.8 */
if ((major==3 && minor>8) || major>3)
{
client->major=3;
client->minor=8;
}
rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n",
major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion);
sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor);
if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE;
/* 3.7 and onwards sends a # of security types first */
if (client->major==3 && client->minor > 6)
{
if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE;
}
else
{
if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE;
authScheme = rfbClientSwap32IfLE(authScheme);
}
rfbClientLog("Selected Security Scheme %d\n", authScheme);
client->authScheme = authScheme;
switch (authScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
case rfbMSLogon:
if (!HandleMSLogonAuth(client)) return FALSE;
break;
case rfbARD:
if (!HandleARDAuth(client)) return FALSE;
break;
case rfbTLS:
if (!HandleAnonTLSAuth(client)) return FALSE;
/* After the TLS session is established, sub auth types are expected.
* Note that all following reading/writing are through the TLS session from here.
*/
if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE;
client->subAuthScheme = subAuthScheme;
switch (subAuthScheme) {
case rfbConnFailed:
ReadReason(client);
return FALSE;
case rfbNoAuth:
rfbClientLog("No sub authentication needed\n");
/* 3.8 and upwards sends a Security Result for rfbNoAuth */
if ((client->major==3 && client->minor > 7) || client->major>3)
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVncAuth:
if (!HandleVncAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
(int)subAuthScheme);
return FALSE;
}
break;
case rfbVeNCrypt:
if (!HandleVeNCryptAuth(client)) return FALSE;
switch (client->subAuthScheme) {
case rfbVeNCryptTLSNone:
case rfbVeNCryptX509None:
rfbClientLog("No sub authentication needed\n");
if (!rfbHandleAuthResult(client)) return FALSE;
break;
case rfbVeNCryptTLSVNC:
case rfbVeNCryptX509VNC:
if (!HandleVncAuth(client)) return FALSE;
break;
case rfbVeNCryptTLSPlain:
case rfbVeNCryptX509Plain:
if (!HandlePlainAuth(client)) return FALSE;
break;
#ifdef LIBVNCSERVER_HAVE_SASL
case rfbVeNCryptX509SASL:
case rfbVeNCryptTLSSASL:
if (!HandleSASLAuth(client)) return FALSE;
break;
#endif /* LIBVNCSERVER_HAVE_SASL */
default:
rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n",
client->subAuthScheme);
return FALSE;
}
break;
default:
{
rfbBool authHandled=FALSE;
rfbClientProtocolExtension* e;
for (e = rfbClientExtensions; e; e = e->next) {
uint32_t const* secType;
if (!e->handleAuthentication) continue;
for (secType = e->securityTypes; secType && *secType; secType++) {
if (authScheme==*secType) {
if (!e->handleAuthentication(client, authScheme)) return FALSE;
if (!rfbHandleAuthResult(client)) return FALSE;
authHandled=TRUE;
}
}
}
if (authHandled) break;
}
rfbClientLog("Unknown authentication scheme from VNC server: %d\n",
(int)authScheme);
return FALSE;
}
ci.shared = (client->appData.shareDesktop ? 1 : 0);
if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE;
if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE;
client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth);
client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight);
client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax);
client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax);
client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax);
client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength);
if (client->si.nameLength > 1<<20) {
rfbClientErr("Too big desktop name length sent by server: %u B > 1 MB\n", (unsigned int)client->si.nameLength);
return FALSE;
}
client->desktopName = malloc(client->si.nameLength + 1);
if (!client->desktopName) {
rfbClientLog("Error allocating memory for desktop name, %lu bytes\n",
(unsigned long)client->si.nameLength);
return FALSE;
}
if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE;
client->desktopName[client->si.nameLength] = 0;
rfbClientLog("Desktop name \"%s\"\n",client->desktopName);
rfbClientLog("Connected to VNC server, using protocol version %d.%d\n",
client->major, client->minor);
rfbClientLog("VNC server default format:\n");
PrintPixelFormat(&client->si.format);
return TRUE;
}
/*
* SetFormatAndEncodings.
*/
rfbBool
SetFormatAndEncodings(rfbClient* client)
{
rfbSetPixelFormatMsg spf;
char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4];
rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf;
uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]);
int len = 0;
rfbBool requestCompressLevel = FALSE;
rfbBool requestQualityLevel = FALSE;
rfbBool requestLastRectEncoding = FALSE;
rfbClientProtocolExtension* e;
if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE;
spf.type = rfbSetPixelFormat;
spf.pad1 = 0;
spf.pad2 = 0;
spf.format = client->format;
spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax);
spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax);
spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax);
if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg))
return FALSE;
if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE;
se->type = rfbSetEncodings;
se->pad = 0;
se->nEncodings = 0;
if (client->appData.encodingsString) {
const char *encStr = client->appData.encodingsString;
int encStrLen;
do {
const char *nextEncStr = strchr(encStr, ' ');
if (nextEncStr) {
encStrLen = nextEncStr - encStr;
nextEncStr++;
} else {
encStrLen = strlen(encStr);
}
if (strncasecmp(encStr,"raw",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
} else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
} else if (strncasecmp(encStr,"tight",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
if (client->appData.enableJPEG)
requestQualityLevel = TRUE;
#endif
#endif
} else if (strncasecmp(encStr,"hextile",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
} else if (strncasecmp(encStr,"zlib",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9)
requestCompressLevel = TRUE;
} else if (strncasecmp(encStr,"trle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE);
} else if (strncasecmp(encStr,"zrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
} else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
requestQualityLevel = TRUE;
#endif
} else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) {
/* There are 2 encodings used in 'ultra' */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
} else if (strncasecmp(encStr,"corre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
} else if (strncasecmp(encStr,"rre",encStrLen) == 0) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
} else {
rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr);
}
encStr = nextEncStr;
} while (encStr && se->nEncodings < MAX_ENCODINGS);
if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
}
if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
else {
if (SameMachine(client->sock)) {
/* TODO:
if (!tunnelSpecified) {
*/
rfbClientLog("Same machine: preferring raw encoding\n");
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw);
/*
} else {
rfbClientLog("Tunneling active: preferring tight encoding\n");
}
*/
}
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect);
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight);
requestLastRectEncoding = TRUE;
#endif
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile);
#ifdef LIBVNCSERVER_HAVE_LIBZ
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE);
#endif
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE);
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE);
if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) {
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel +
rfbEncodingCompressLevel0);
} else /* if (!tunnelSpecified) */ {
/* If -tunnel option was provided, we assume that server machine is
not in the local network so we use default compression level for
tight encoding instead of fast compression. Thus we are
requesting level 1 compression only if tunneling is not used. */
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1);
}
if (client->appData.enableJPEG) {
if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9)
client->appData.qualityLevel = 5;
encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel +
rfbEncodingQualityLevel0);
}
}
/* Remote Cursor Support (local to viewer) */
if (client->appData.useRemoteCursor) {
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos);
}
/* Keyboard State Encodings */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState);
/* New Frame Buffer Size */
if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize);
/* Last Rect */
if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect);
/* Server Capabilities */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings);
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity);
/* xvp */
if (se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp);
/* client extensions */
for(e = rfbClientExtensions; e; e = e->next)
if(e->encodings) {
int* enc;
for(enc = e->encodings; *enc; enc++)
if(se->nEncodings < MAX_ENCODINGS)
encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc);
}
len = sz_rfbSetEncodingsMsg + se->nEncodings * 4;
se->nEncodings = rfbClientSwap16IfLE(se->nEncodings);
if (!WriteToRFBServer(client, buf, len)) return FALSE;
return TRUE;
}
/*
* SendIncrementalFramebufferUpdateRequest.
*/
rfbBool
SendIncrementalFramebufferUpdateRequest(rfbClient* client)
{
return SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h, TRUE);
}
/*
* SendFramebufferUpdateRequest.
*/
rfbBool
SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental)
{
rfbFramebufferUpdateRequestMsg fur;
if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE;
fur.type = rfbFramebufferUpdateRequest;
fur.incremental = incremental ? 1 : 0;
fur.x = rfbClientSwap16IfLE(x);
fur.y = rfbClientSwap16IfLE(y);
fur.w = rfbClientSwap16IfLE(w);
fur.h = rfbClientSwap16IfLE(h);
if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg))
return FALSE;
return TRUE;
}
/*
* SendScaleSetting.
*/
rfbBool
SendScaleSetting(rfbClient* client,int scaleSetting)
{
rfbSetScaleMsg ssm;
ssm.scale = scaleSetting;
ssm.pad = 0;
/* favor UltraVNC SetScale if both are supported */
if (SupportsClient2Server(client, rfbSetScale)) {
ssm.type = rfbSetScale;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) {
ssm.type = rfbPalmVNCSetScaleFactor;
if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg))
return FALSE;
}
return TRUE;
}
/*
* TextChatFunctions (UltraVNC)
* Extremely bandwidth friendly method of communicating with a user
* (Think HelpDesk type applications)
*/
rfbBool TextChatSend(rfbClient* client, char *text)
{
rfbTextChatMsg chat;
int count = strlen(text);
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = (uint32_t)count;
chat.length = rfbClientSwap32IfLE(chat.length);
if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg))
return FALSE;
if (count>0) {
if (!WriteToRFBServer(client, text, count))
return FALSE;
}
return TRUE;
}
rfbBool TextChatOpen(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatOpen);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatClose(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatClose);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
rfbBool TextChatFinish(rfbClient* client)
{
rfbTextChatMsg chat;
if (!SupportsClient2Server(client, rfbTextChat)) return TRUE;
chat.type = rfbTextChat;
chat.pad1 = 0;
chat.pad2 = 0;
chat.length = rfbClientSwap32IfLE(rfbTextChatFinished);
return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE);
}
/*
* UltraVNC Server Input Disable
* Apparently, the remote client can *prevent* the local user from interacting with the display
* I would think this is extremely helpful when used in a HelpDesk situation
*/
rfbBool PermitServerInput(rfbClient* client, int enabled)
{
rfbSetServerInputMsg msg;
if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE;
/* enabled==1, then server input from local keyboard is disabled */
msg.type = rfbSetServerInput;
msg.status = (enabled ? 1 : 0);
msg.pad = 0;
return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE);
}
/*
* send xvp client message
* A client supporting the xvp extension sends this to request that the server initiate
* a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the
* client is displaying.
*
* only version 1 is defined in the protocol specs
*
* possible values for code are:
* rfbXvp_Shutdown
* rfbXvp_Reboot
* rfbXvp_Reset
*/
rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code)
{
rfbXvpMsg xvp;
if (!SupportsClient2Server(client, rfbXvp)) return TRUE;
xvp.type = rfbXvp;
xvp.pad = 0;
xvp.version = version;
xvp.code = code;
if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg))
return FALSE;
return TRUE;
}
/*
* SendPointerEvent.
*/
rfbBool
SendPointerEvent(rfbClient* client,int x, int y, int buttonMask)
{
rfbPointerEventMsg pe;
if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE;
pe.type = rfbPointerEvent;
pe.buttonMask = buttonMask;
if (x < 0) x = 0;
if (y < 0) y = 0;
pe.x = rfbClientSwap16IfLE(x);
pe.y = rfbClientSwap16IfLE(y);
return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg);
}
/*
* SendKeyEvent.
*/
rfbBool
SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down)
{
rfbKeyEventMsg ke;
if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE;
memset(&ke, 0, sizeof(ke));
ke.type = rfbKeyEvent;
ke.down = down ? 1 : 0;
ke.key = rfbClientSwap32IfLE(key);
return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg);
}
/*
* SendClientCutText.
*/
rfbBool
SendClientCutText(rfbClient* client, char *str, int len)
{
rfbClientCutTextMsg cct;
if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE;
memset(&cct, 0, sizeof(cct));
cct.type = rfbClientCutText;
cct.length = rfbClientSwap32IfLE(len);
return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) &&
WriteToRFBServer(client, str, len));
}
/*
* HandleRFBServerMessage.
*/
rfbBool
HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
if (msg.sct.length > 1<<20) {
rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length);
return FALSE;
}
buffer = malloc(msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {
free(buffer);
return FALSE;
}
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
if(msg.tc.length > MAX_TEXTCHAT_SIZE)
return FALSE;
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
}
#define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++)
#define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++)
#define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \
((uint8_t*)&(pix))[1] = *(ptr)++, \
((uint8_t*)&(pix))[2] = *(ptr)++, \
((uint8_t*)&(pix))[3] = *(ptr)++)
/* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also
expands its arguments if they are macros */
#define CONCAT2(a,b) a##b
#define CONCAT2E(a,b) CONCAT2(a,b)
#define CONCAT3(a,b,c) a##b##c
#define CONCAT3E(a,b,c) CONCAT3(a,b,c)
#define BPP 8
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#undef BPP
#define BPP 16
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 15
#include "trle.c"
#define REALBPP 15
#include "zrle.c"
#undef BPP
#define BPP 32
#include "rre.c"
#include "corre.c"
#include "hextile.c"
#include "ultra.c"
#include "zlib.c"
#include "tight.c"
#include "trle.c"
#include "zrle.c"
#define REALBPP 24
#include "trle.c"
#define REALBPP 24
#include "zrle.c"
#define REALBPP 24
#define UNCOMP 8
#include "trle.c"
#define REALBPP 24
#define UNCOMP 8
#include "zrle.c"
#define REALBPP 24
#define UNCOMP -8
#include "trle.c"
#define REALBPP 24
#define UNCOMP -8
#include "zrle.c"
#undef BPP
/*
* PrintPixelFormat.
*/
void
PrintPixelFormat(rfbPixelFormat *format)
{
if (format->bitsPerPixel == 1) {
rfbClientLog(" Single bit per pixel.\n");
rfbClientLog(
" %s significant bit in each byte is leftmost on the screen.\n",
(format->bigEndian ? "Most" : "Least"));
} else {
rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel);
if (format->bitsPerPixel != 8) {
rfbClientLog(" %s significant byte first in each pixel.\n",
(format->bigEndian ? "Most" : "Least"));
}
if (format->trueColour) {
rfbClientLog(" TRUE colour: max red %d green %d blue %d"
", shift red %d green %d blue %d\n",
format->redMax, format->greenMax, format->blueMax,
format->redShift, format->greenShift, format->blueShift);
} else {
rfbClientLog(" Colour map (not true colour).\n");
}
}
}
/* avoid name clashes with LibVNCServer */
#define rfbEncryptBytes rfbClientEncryptBytes
#define rfbEncryptBytes2 rfbClientEncryptBytes2
#define rfbDes rfbClientDes
#define rfbDesKey rfbClientDesKey
#define rfbUseKey rfbClientUseKey
#include "vncauth.c"
| ./CrossVul/dataset_final_sorted/CWE-770/c/good_4064_0 |
crossvul-cpp_data_good_2614_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N GGGG %
% P P NN N G %
% PPPP N N N G GG %
% P N NN G G %
% P N N GGG %
% %
% %
% Read/Write Portable Network Graphics Image Format %
% %
% Software Design %
% Cristy %
% Glenn Randers-Pehrson %
% November 1997 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/histogram.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/layer.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/transform.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_PNG_DELEGATE)
/* Suppress libpng pedantic warnings that were added in
* libpng-1.2.41 and libpng-1.4.0. If you are working on
* migration to libpng-1.5, remove these defines and then
* fix any code that generates warnings.
*/
/* #define PNG_DEPRECATED Use of this function is deprecated */
/* #define PNG_USE_RESULT The result of this function must be checked */
/* #define PNG_NORETURN This function does not return */
/* #define PNG_ALLOCATED The result of the function is new memory */
/* #define PNG_DEPSTRUCT Access to this struct member is deprecated */
/* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */
#define PNG_PTR_NORETURN
#include "png.h"
#include "zlib.h"
/* ImageMagick differences */
#define first_scene scene
#if PNG_LIBPNG_VER > 10011
/*
Optional declarations. Define or undefine them as you like.
*/
/* #define PNG_DEBUG -- turning this on breaks VisualC compiling */
/*
Features under construction. Define these to work on them.
*/
#undef MNG_OBJECT_BUFFERS
#undef MNG_BASI_SUPPORTED
#define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */
#define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */
#if defined(MAGICKCORE_JPEG_DELEGATE)
# define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */
#endif
#if !defined(RGBColorMatchExact)
#define IsPNGColorEqual(color,target) \
(((color).red == (target).red) && \
((color).green == (target).green) && \
((color).blue == (target).blue))
#endif
/* Table of recognized sRGB ICC profiles */
struct sRGB_info_struct
{
png_uint_32 len;
png_uint_32 crc;
png_byte intent;
};
const struct sRGB_info_struct sRGB_info[] =
{
/* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */
{ 3048, 0x3b8772b9UL, 0},
/* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */
{ 3052, 0x427ebb21UL, 1},
/* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */
{60988, 0x306fd8aeUL, 0},
/* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */
{60960, 0xbbef7812UL, 0},
/* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */
{ 3024, 0x5d5129ceUL, 1},
/* HP-Microsoft sRGB v2 perceptual */
{ 3144, 0x182ea552UL, 0},
/* HP-Microsoft sRGB v2 media-relative */
{ 3144, 0xf29e526dUL, 1},
/* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */
{ 524, 0xd4938c39UL, 0},
/* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */
{ 3212, 0x034af5a1UL, 0},
/* Not recognized */
{ 0, 0x00000000UL, 0},
};
/* Macros for left-bit-replication to ensure that pixels
* and PixelPackets all have the same image->depth, and for use
* in PNG8 quantization.
*/
/* LBR01: Replicate top bit */
#define LBR01PacketRed(pixelpacket) \
(pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketGreen(pixelpacket) \
(pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketBlue(pixelpacket) \
(pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketOpacity(pixelpacket) \
(pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketRGB(pixelpacket) \
{ \
LBR01PacketRed((pixelpacket)); \
LBR01PacketGreen((pixelpacket)); \
LBR01PacketBlue((pixelpacket)); \
}
#define LBR01PacketRGBO(pixelpacket) \
{ \
LBR01PacketRGB((pixelpacket)); \
LBR01PacketOpacity((pixelpacket)); \
}
#define LBR01PixelRed(pixel) \
(SetPixelRed((pixel), \
ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelGreen(pixel) \
(SetPixelGreen((pixel), \
ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelBlue(pixel) \
(SetPixelBlue((pixel), \
ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelOpacity(pixel) \
(SetPixelOpacity((pixel), \
ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelRGB(pixel) \
{ \
LBR01PixelRed((pixel)); \
LBR01PixelGreen((pixel)); \
LBR01PixelBlue((pixel)); \
}
#define LBR01PixelRGBO(pixel) \
{ \
LBR01PixelRGB((pixel)); \
LBR01PixelOpacity((pixel)); \
}
/* LBR02: Replicate top 2 bits */
#define LBR02PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketOpacity(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \
(pixelpacket).opacity=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketRGB(pixelpacket) \
{ \
LBR02PacketRed((pixelpacket)); \
LBR02PacketGreen((pixelpacket)); \
LBR02PacketBlue((pixelpacket)); \
}
#define LBR02PacketRGBO(pixelpacket) \
{ \
LBR02PacketRGB((pixelpacket)); \
LBR02PacketOpacity((pixelpacket)); \
}
#define LBR02PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xc0; \
SetPixelRed((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xc0; \
SetPixelGreen((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \
SetPixelBlue((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02Opacity(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \
SetPixelOpacity((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelRGB(pixel) \
{ \
LBR02PixelRed((pixel)); \
LBR02PixelGreen((pixel)); \
LBR02PixelBlue((pixel)); \
}
#define LBR02PixelRGBO(pixel) \
{ \
LBR02PixelRGB((pixel)); \
LBR02Opacity((pixel)); \
}
/* LBR03: Replicate top 3 bits (only used with opaque pixels during
PNG8 quantization) */
#define LBR03PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketRGB(pixelpacket) \
{ \
LBR03PacketRed((pixelpacket)); \
LBR03PacketGreen((pixelpacket)); \
LBR03PacketBlue((pixelpacket)); \
}
#define LBR03PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xe0; \
SetPixelRed((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xe0; \
SetPixelGreen((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelBlue(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \
& 0xe0; \
SetPixelBlue((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelRGB(pixel) \
{ \
LBR03PixelRed((pixel)); \
LBR03PixelGreen((pixel)); \
LBR03PixelBlue((pixel)); \
}
/* LBR04: Replicate top 4 bits */
#define LBR04PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \
(pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \
(pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \
(pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketOpacity(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \
(pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketRGB(pixelpacket) \
{ \
LBR04PacketRed((pixelpacket)); \
LBR04PacketGreen((pixelpacket)); \
LBR04PacketBlue((pixelpacket)); \
}
#define LBR04PacketRGBO(pixelpacket) \
{ \
LBR04PacketRGB((pixelpacket)); \
LBR04PacketOpacity((pixelpacket)); \
}
#define LBR04PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xf0; \
SetPixelRed((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xf0; \
SetPixelGreen((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \
SetPixelBlue((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelOpacity(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \
SetPixelOpacity((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelRGB(pixel) \
{ \
LBR04PixelRed((pixel)); \
LBR04PixelGreen((pixel)); \
LBR04PixelBlue((pixel)); \
}
#define LBR04PixelRGBO(pixel) \
{ \
LBR04PixelRGB((pixel)); \
LBR04PixelOpacity((pixel)); \
}
/*
Establish thread safety.
setjmp/longjmp is claimed to be safe on these platforms:
setjmp/longjmp is alleged to be unsafe on these platforms:
*/
#ifdef PNG_SETJMP_SUPPORTED
# ifndef IMPNG_SETJMP_IS_THREAD_SAFE
# define IMPNG_SETJMP_NOT_THREAD_SAFE
# endif
# ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
static SemaphoreInfo
*ping_semaphore = (SemaphoreInfo *) NULL;
# endif
#endif
/*
This temporary until I set up malloc'ed object attributes array.
Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but
waste more memory.
*/
#define MNG_MAX_OBJECTS 256
/*
If this not defined, spec is interpreted strictly. If it is
defined, an attempt will be made to recover from some errors,
including
o global PLTE too short
*/
#undef MNG_LOOSE
/*
Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure
it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work
with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8,
PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in
libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here.
PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and
will be enabled by default in libpng-1.2.0.
*/
#ifdef PNG_MNG_FEATURES_SUPPORTED
# ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
# define PNG_READ_EMPTY_PLTE_SUPPORTED
# endif
# ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED
# define PNG_WRITE_EMPTY_PLTE_SUPPORTED
# endif
#endif
/*
Maximum valid size_t in PNG/MNG chunks is (2^31)-1
This macro is only defined in libpng-1.0.3 and later.
Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6
*/
#ifndef PNG_UINT_31_MAX
#define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL
#endif
/*
Constant strings for known chunk types. If you need to add a chunk,
add a string holding the name here. To make the code more
portable, we use ASCII numbers like this, not characters.
*/
/* until registration of eXIf */
static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'};
/* after registration of eXIf */
static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'};
static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'};
static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'};
static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'};
static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'};
static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'};
static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'};
static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'};
static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'};
static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'};
static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'};
static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'};
static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'};
static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'};
static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'};
static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'};
static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'};
static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'};
static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'};
static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'};
static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'};
static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'};
static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'};
static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'};
static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'};
static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'};
static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'};
static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'};
static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'};
#if defined(JNG_SUPPORTED)
static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'};
static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'};
static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'};
static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'};
#endif
#if 0
/* Other known chunks that are not yet supported by ImageMagick: */
static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'};
static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'};
static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'};
static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'};
static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'};
static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'};
static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'};
#endif
typedef struct _MngBox
{
long
left,
right,
top,
bottom;
} MngBox;
typedef struct _MngPair
{
volatile long
a,
b;
} MngPair;
#ifdef MNG_OBJECT_BUFFERS
typedef struct _MngBuffer
{
size_t
height,
width;
Image
*image;
png_color
plte[256];
int
reference_count;
unsigned char
alpha_sample_depth,
compression_method,
color_type,
concrete,
filter_method,
frozen,
image_type,
interlace_method,
pixel_sample_depth,
plte_length,
sample_depth,
viewable;
} MngBuffer;
#endif
typedef struct _MngInfo
{
#ifdef MNG_OBJECT_BUFFERS
MngBuffer
*ob[MNG_MAX_OBJECTS];
#endif
Image *
image;
RectangleInfo
page;
int
adjoin,
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
bytes_in_read_buffer,
found_empty_plte,
#endif
equal_backgrounds,
equal_chrms,
equal_gammas,
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
equal_palettes,
#endif
equal_physs,
equal_srgbs,
framing_mode,
have_global_bkgd,
have_global_chrm,
have_global_gama,
have_global_phys,
have_global_sbit,
have_global_srgb,
have_saved_bkgd_index,
have_write_global_chrm,
have_write_global_gama,
have_write_global_plte,
have_write_global_srgb,
need_fram,
object_id,
old_framing_mode,
saved_bkgd_index;
int
new_number_colors;
ssize_t
image_found,
loop_count[256],
loop_iteration[256],
scenes_found,
x_off[MNG_MAX_OBJECTS],
y_off[MNG_MAX_OBJECTS];
MngBox
clip,
frame,
image_box,
object_clip[MNG_MAX_OBJECTS];
unsigned char
/* These flags could be combined into one byte */
exists[MNG_MAX_OBJECTS],
frozen[MNG_MAX_OBJECTS],
loop_active[256],
invisible[MNG_MAX_OBJECTS],
viewable[MNG_MAX_OBJECTS];
MagickOffsetType
loop_jump[256];
png_colorp
global_plte;
png_color_8
global_sbit;
png_byte
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
read_buffer[8],
#endif
global_trns[256];
float
global_gamma;
ChromaticityInfo
global_chrm;
RenderingIntent
global_srgb_intent;
unsigned int
delay,
global_plte_length,
global_trns_length,
global_x_pixels_per_unit,
global_y_pixels_per_unit,
mng_width,
mng_height,
ticks_per_second;
MagickBooleanType
need_blob;
unsigned int
IsPalette,
global_phys_unit_type,
basi_warning,
clon_warning,
dhdr_warning,
jhdr_warning,
magn_warning,
past_warning,
phyg_warning,
phys_warning,
sbit_warning,
show_warning,
mng_type,
write_mng,
write_png_colortype,
write_png_depth,
write_png_compression_level,
write_png_compression_strategy,
write_png_compression_filter,
write_png8,
write_png24,
write_png32,
write_png48,
write_png64;
#ifdef MNG_BASI_SUPPORTED
size_t
basi_width,
basi_height;
unsigned int
basi_depth,
basi_color_type,
basi_compression_method,
basi_filter_type,
basi_interlace_method,
basi_red,
basi_green,
basi_blue,
basi_alpha,
basi_viewable;
#endif
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
PixelPacket
mng_global_bkgd;
/* Added at version 6.6.6-7 */
MagickBooleanType
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
ping_exclude_eXIf,
ping_exclude_EXIF,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tRNS,
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
/* Added at version 6.8.5-7 */
ping_preserve_iCCP,
/* Added at version 6.8.9-9 */
ping_exclude_tIME;
} MngInfo;
#endif /* VER */
/*
Forward declarations.
*/
static MagickBooleanType
WritePNGImage(const ImageInfo *,Image *);
static MagickBooleanType
WriteMNGImage(const ImageInfo *,Image *);
#if defined(JNG_SUPPORTED)
static MagickBooleanType
WriteJNGImage(const ImageInfo *,Image *);
#endif
#if PNG_LIBPNG_VER > 10011
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
static MagickBooleanType
LosslessReduceDepthOK(Image *image)
{
/* Reduce bit depth if it can be reduced losslessly from 16+ to 8.
*
* This is true if the high byte and the next highest byte of
* each sample of the image, the colormap, and the background color
* are equal to each other. We check this by seeing if the samples
* are unchanged when we scale them down to 8 and back up to Quantum.
*
* We don't use the method GetImageDepth() because it doesn't check
* background and doesn't handle PseudoClass specially.
*/
#define QuantumToCharToQuantumEqQuantum(quantum) \
((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum)
MagickBooleanType
ok_to_reduce=MagickFalse;
if (image->depth >= 16)
{
const PixelPacket
*p;
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(image->background_color.red) &&
QuantumToCharToQuantumEqQuantum(image->background_color.green) &&
QuantumToCharToQuantumEqQuantum(image->background_color.blue) ?
MagickTrue : MagickFalse;
if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass)
{
int indx;
for (indx=0; indx < (ssize_t) image->colors; indx++)
{
ok_to_reduce=(
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].red) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].green) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].blue)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
}
}
if ((ok_to_reduce != MagickFalse) &&
(image->storage_class != PseudoClass))
{
ssize_t
y;
register ssize_t
x;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
{
ok_to_reduce = MagickFalse;
break;
}
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
p++;
}
if (x >= 0)
break;
}
}
if (ok_to_reduce != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OK to reduce PNG bit depth to 8 without loss of info");
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Not OK to reduce PNG bit depth to 8 without loss of info");
}
}
return ok_to_reduce;
}
#endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */
static const char* PngColorTypeToString(const unsigned int color_type)
{
const char
*result = "Unknown";
switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
result = "Gray";
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
result = "Gray+Alpha";
break;
case PNG_COLOR_TYPE_PALETTE:
result = "Palette";
break;
case PNG_COLOR_TYPE_RGB:
result = "RGB";
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
result = "RGB+Alpha";
break;
}
return result;
}
static int
Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent)
{
switch (intent)
{
case PerceptualIntent:
return 0;
case RelativeIntent:
return 1;
case SaturationIntent:
return 2;
case AbsoluteIntent:
return 3;
default:
return -1;
}
}
static RenderingIntent
Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return PerceptualIntent;
case 1:
return RelativeIntent;
case 2:
return SaturationIntent;
case 3:
return AbsoluteIntent;
default:
return UndefinedIntent;
}
}
static const char *
Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return "Perceptual Intent";
case 1:
return "Relative Intent";
case 2:
return "Saturation Intent";
case 3:
return "Absolute Intent";
default:
return "Undefined Intent";
}
}
static const char *
Magick_ColorType_from_PNG_ColorType(const int ping_colortype)
{
switch (ping_colortype)
{
case 0:
return "Grayscale";
case 2:
return "Truecolor";
case 3:
return "Indexed";
case 4:
return "GrayAlpha";
case 6:
return "RGBA";
default:
return "UndefinedColorType";
}
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif /* MAGICKCORE_PNG_DELEGATE */
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMNG() returns MagickTrue if the image format type, identified by the
% magick string, is MNG.
%
% The format of the IsMNG method is:
%
% MagickBooleanType IsMNG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJNG() returns MagickTrue if the image format type, identified by the
% magick string, is JNG.
%
% The format of the IsJNG method is:
%
% MagickBooleanType IsJNG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNG() returns MagickTrue if the image format type, identified by the
% magick string, is PNG.
%
% The format of the IsPNG method is:
%
% MagickBooleanType IsPNG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#if (PNG_LIBPNG_VER > 10011)
static size_t WriteBlobMSBULong(Image *image,const size_t value)
{
unsigned char
buffer[4];
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
return((size_t) WriteBlob(image,4,buffer));
}
static void PNGLong(png_bytep p,png_uint_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGsLong(png_bytep p,png_int_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGShort(png_bytep p,png_uint_16 value)
{
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGType(png_bytep p,const png_byte *type)
{
(void) CopyMagickMemory(p,type,4*sizeof(png_byte));
}
static void LogPNGChunk(MagickBooleanType logging, const png_byte *type,
size_t length)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing %c%c%c%c chunk, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
}
#endif /* PNG_LIBPNG_VER > 10011 */
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNGImage() reads a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image or set of images.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadPNGImage method is:
%
% Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
% To do, more or less in chronological order (as of version 5.5.2,
% November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage):
%
% Get 16-bit cheap transparency working.
%
% (At this point, PNG decoding is supposed to be in full MNG-LC compliance)
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% (At this point, PNG encoding should be in full MNG compliance)
%
% Provide options for choice of background to use when the MNG BACK
% chunk is not present or is not mandatory (i.e., leave transparent,
% user specified, MNG BACK, PNG bKGD)
%
% Implement LOOP/ENDL [done, but could do discretionary loops more
% efficiently by linking in the duplicate frames.].
%
% Decode and act on the MHDR simplicity profile (offer option to reject
% files or attempt to process them anyway when the profile isn't LC or VLC).
%
% Upgrade to full MNG without Delta-PNG.
%
% o BACK [done a while ago except for background image ID]
% o MOVE [done 15 May 1999]
% o CLIP [done 15 May 1999]
% o DISC [done 19 May 1999]
% o SAVE [partially done 19 May 1999 (marks objects frozen)]
% o SEEK [partially done 19 May 1999 (discard function only)]
% o SHOW
% o PAST
% o BASI
% o MNG-level tEXt/iTXt/zTXt
% o pHYg
% o pHYs
% o sBIT
% o bKGD
% o iTXt (wait for libpng implementation).
%
% Use the scene signature to discover when an identical scene is
% being reused, and just point to the original image->exception instead
% of storing another set of pixels. This not specific to MNG
% but could be applied generally.
%
% Upgrade to full MNG with Delta-PNG.
%
% JNG tEXt/iTXt/zTXt
%
% We will not attempt to read files containing the CgBI chunk.
% They are really Xcode files meant for display on the iPhone.
% These are not valid PNG files and it is impossible to recover
% the original PNG from files that have been converted to Xcode-PNG,
% since irretrievable loss of color data has occurred due to the
% use of premultiplied alpha.
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/*
This the function that does the actual reading of data. It is
the same as the one supplied in libpng, except that it receives the
datastream from the ReadBlob() function instead of standard input.
*/
static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) ReadBlob(image,(size_t) length,data);
if (check != length)
{
char
msg[MaxTextExtent];
(void) FormatLocaleString(msg,MaxTextExtent,
"Expected %.20g bytes; found %.20g bytes",(double) length,
(double) check);
png_warning(png_ptr,msg);
png_error(png_ptr,"Read Exception");
}
}
}
#if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \
!defined(PNG_MNG_FEATURES_SUPPORTED)
/* We use mng_get_data() instead of png_get_data() if we have a libpng
* older than libpng-1.0.3a, which was the first to allow the empty
* PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was
* ifdef'ed out. Earlier versions would crash if the bKGD chunk was
* encountered after an empty PLTE, so we have to look ahead for bKGD
* chunks and remove them from the datastream that is passed to libpng,
* and store their contents for later use.
*/
static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
MngInfo
*mng_info;
Image
*image;
png_size_t
check;
register ssize_t
i;
i=0;
mng_info=(MngInfo *) png_get_io_ptr(png_ptr);
image=(Image *) mng_info->image;
while (mng_info->bytes_in_read_buffer && length)
{
data[i]=mng_info->read_buffer[i];
mng_info->bytes_in_read_buffer--;
length--;
i++;
}
if (length != 0)
{
check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data);
if (check != length)
png_error(png_ptr,"Read Exception");
if (length == 4)
{
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 0))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0)
mng_info->found_empty_plte=MagickTrue;
if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0)
{
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
}
}
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 1))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0)
if (mng_info->found_empty_plte)
{
/*
Skip the bKGD data byte and CRC.
*/
check=(png_size_t)
ReadBlob(image,5,(char *) mng_info->read_buffer);
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->saved_bkgd_index=mng_info->read_buffer[0];
mng_info->have_saved_bkgd_index=MagickTrue;
mng_info->bytes_in_read_buffer=0;
}
}
}
}
}
#endif
static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) WriteBlob(image,(size_t) length,data);
if (check != length)
png_error(png_ptr,"WriteBlob Failed");
}
}
static void png_flush_data(png_structp png_ptr)
{
(void) png_ptr;
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
static int PalettesAreEqual(Image *a,Image *b)
{
ssize_t
i;
if ((a == (Image *) NULL) || (b == (Image *) NULL))
return((int) MagickFalse);
if (a->storage_class != PseudoClass || b->storage_class != PseudoClass)
return((int) MagickFalse);
if (a->colors != b->colors)
return((int) MagickFalse);
for (i=0; i < (ssize_t) a->colors; i++)
{
if ((a->colormap[i].red != b->colormap[i].red) ||
(a->colormap[i].green != b->colormap[i].green) ||
(a->colormap[i].blue != b->colormap[i].blue))
return((int) MagickFalse);
}
return((int) MagickTrue);
}
#endif
static void MngInfoDiscardObject(MngInfo *mng_info,int i)
{
if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) &&
mng_info->exists[i] && !mng_info->frozen[i])
{
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
{
if (mng_info->ob[i]->reference_count > 0)
mng_info->ob[i]->reference_count--;
if (mng_info->ob[i]->reference_count == 0)
{
if (mng_info->ob[i]->image != (Image *) NULL)
mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image);
mng_info->ob[i]=DestroyString(mng_info->ob[i]);
}
}
mng_info->ob[i]=(MngBuffer *) NULL;
#endif
mng_info->exists[i]=MagickFalse;
mng_info->invisible[i]=MagickFalse;
mng_info->viewable[i]=MagickFalse;
mng_info->frozen[i]=MagickFalse;
mng_info->x_off[i]=0;
mng_info->y_off[i]=0;
mng_info->object_clip[i].left=0;
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].top=0;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
}
static MngInfo *MngInfoFreeStruct(MngInfo *mng_info)
{
register ssize_t
i;
if (mng_info == (MngInfo *) NULL)
return((MngInfo *) NULL);
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
if (mng_info->global_plte != (png_colorp) NULL)
mng_info->global_plte=(png_colorp)
RelinquishMagickMemory(mng_info->global_plte);
return((MngInfo *) RelinquishMagickMemory(mng_info));
}
static MngBox mng_minimum_box(MngBox box1,MngBox box2)
{
MngBox
box;
box=box1;
if (box.left < box2.left)
box.left=box2.left;
if (box.top < box2.top)
box.top=box2.top;
if (box.right > box2.right)
box.right=box2.right;
if (box.bottom > box2.bottom)
box.bottom=box2.bottom;
return box;
}
static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p)
{
MngBox
box;
/*
Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk.
*/
box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]);
box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]);
box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]);
if (delta_type != 0)
{
box.left+=previous_box.left;
box.right+=previous_box.right;
box.top+=previous_box.top;
box.bottom+=previous_box.bottom;
}
return(box);
}
static MngPair mng_read_pair(MngPair previous_pair,int delta_type,
unsigned char *p)
{
MngPair
pair;
/*
Read two ssize_ts from CLON, MOVE or PAST chunk
*/
pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]);
if (delta_type != 0)
{
pair.a+=previous_pair.a;
pair.b+=previous_pair.b;
}
return(pair);
}
static long mng_get_long(unsigned char *p)
{
return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]));
}
typedef struct _PNGErrorInfo
{
Image
*image;
ExceptionInfo
*exception;
} PNGErrorInfo;
static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message)
{
Image
*image;
image=(Image *) png_get_error_ptr(ping);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message);
(void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError,
message,"`%s'",image->filename);
#if (PNG_LIBPNG_VER < 10500)
/* A warning about deprecated use of jmpbuf here is unavoidable if you
* are building with libpng-1.4.x and can be ignored.
*/
longjmp(ping->jmpbuf,1);
#else
png_longjmp(ping,1);
#endif
}
static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message)
{
Image
*image;
if (LocaleCompare(message, "Missing PLTE before tRNS") == 0)
png_error(ping, message);
image=(Image *) png_get_error_ptr(ping);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message);
(void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning,
message,"`%s'",image->filename);
}
#ifdef PNG_USER_MEM_SUPPORTED
#if PNG_LIBPNG_VER >= 10400
static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size)
#else
static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size)
#endif
{
(void) png_ptr;
return((png_voidp) AcquireMagickMemory((size_t) size));
}
/*
Free a pointer. It is removed from the list at the same time.
*/
static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr)
{
(void) png_ptr;
ptr=RelinquishMagickMemory(ptr);
return((png_free_ptr) NULL);
}
#endif
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static int
Magick_png_read_raw_profile(png_struct *ping,Image *image,
const ImageInfo *image_info, png_textp text,int ii)
{
register ssize_t
i;
register unsigned char
*dp;
register png_charp
sp;
png_uint_32
length,
nibbles;
StringInfo
*profile;
const unsigned char
unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12,
13,14,15};
sp=text[ii].text+1;
/* look for newline */
while (*sp != '\n')
sp++;
/* look for length */
while (*sp == '\0' || *sp == ' ' || *sp == '\n')
sp++;
length=(png_uint_32) StringToLong(sp);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu",(unsigned long) length);
while (*sp != ' ' && *sp != '\n')
sp++;
/* allocate space */
if (length == 0)
{
png_warning(ping,"invalid profile length");
return(MagickFalse);
}
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "unable to copy profile");
return(MagickFalse);
}
/* copy profile, skipping white space and column 1 "=" signs */
dp=GetStringInfoDatum(profile);
nibbles=length*2;
for (i=0; i < (ssize_t) nibbles; i++)
{
while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f')
{
if (*sp == '\0')
{
png_warning(ping, "ran out of profile data");
return(MagickFalse);
}
sp++;
}
if (i%2 == 0)
*dp=(unsigned char) (16*unhex[(int) *sp++]);
else
(*dp++)+=unhex[(int) *sp++];
}
/*
We have already read "Raw profile type.
*/
(void) SetImageProfile(image,&text[ii].key[17],profile);
profile=DestroyStringInfo(profile);
if (image_info->verbose)
(void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]);
return MagickTrue;
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk)
{
Image
*image;
/* The unknown chunk structure contains the chunk data:
png_byte name[5];
png_byte *data;
png_size_t size;
Note that libpng has already taken care of the CRC handling.
*/
LogMagickEvent(CoderEvent,GetMagickModule(),
" read_user_chunk: found %c%c%c%c chunk",
chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]);
if (chunk->name[0] == 101 &&
(chunk->name[1] == 88 || chunk->name[1] == 120 ) &&
chunk->name[2] == 73 &&
chunk-> name[3] == 102)
{
/* process eXIf or exIf chunk */
PNGErrorInfo
*error_info;
StringInfo
*profile;
unsigned char
*p;
png_byte
*s;
int
i;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" recognized eXIf|exIf chunk");
image=(Image *) png_get_user_chunk_ptr(ping);
error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
profile=BlobToStringInfo((const void *) NULL,chunk->size+6);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(error_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1);
}
p=GetStringInfoDatum(profile);
/* Initialize profile with "Exif\0\0" */
*p++ ='E';
*p++ ='x';
*p++ ='i';
*p++ ='f';
*p++ ='\0';
*p++ ='\0';
/* copy chunk->data to profile */
s=chunk->data;
for (i=0; i < (ssize_t) chunk->size; i++)
*p++ = *s++;
(void) SetImageProfile(image,"exif",profile);
return(1);
}
/* vpAg (deprecated, replaced by caNv) */
if (chunk->name[0] == 118 &&
chunk->name[1] == 112 &&
chunk->name[2] == 65 &&
chunk->name[3] == 103)
{
/* recognized vpAg */
if (chunk->size != 9)
return(-1); /* Error return */
if (chunk->data[8] != 0)
return(0); /* ImageMagick requires pixel units */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) ((chunk->data[0] << 24) |
(chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);
image->page.height=(size_t) ((chunk->data[4] << 24) |
(chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);
return(1);
}
/* caNv */
if (chunk->name[0] == 99 &&
chunk->name[1] == 97 &&
chunk->name[2] == 78 &&
chunk->name[3] == 118)
{
/* recognized caNv */
if (chunk->size != 16)
return(-1); /* Error return */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) ((chunk->data[0] << 24) |
(chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);
image->page.height=(size_t) ((chunk->data[4] << 24) |
(chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);
image->page.x=(size_t) ((chunk->data[8] << 24) |
(chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]);
image->page.y=(size_t) ((chunk->data[12] << 24) |
(chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]);
/* Return one of the following: */
/* return(-n); chunk had an error */
/* return(0); did not recognize */
/* return(n); success */
return(1);
}
return(0); /* Did not recognize */
}
#endif
#if defined(PNG_tIME_SUPPORTED)
static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info)
{
png_timep
time;
if (png_get_tIME(ping,info,&time))
{
char
timestamp[21];
FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ",
time->year,time->month,time->day,time->hour,time->minute,time->second);
SetImageProperty(image,"png:tIME",timestamp);
}
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file
% (minus the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the ReadOnePNGImage method is:
%
% Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
/* Read one PNG image */
/* To do: Read the tEXt/Creation Time chunk into the date:create property */
Image
*image;
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
int
intent, /* "PNG Rendering intent", which is ICC intent + 1 */
num_raw_profiles,
num_text,
num_text_total,
num_passes,
number_colors,
pass,
ping_bit_depth,
ping_color_type,
ping_file_depth,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans,
unit_type;
double
file_gamma;
LongPixelPacket
transparent_color;
MagickBooleanType
logging,
ping_found_cHRM,
ping_found_gAMA,
ping_found_iCCP,
ping_found_sRGB,
ping_found_sRGB_cHRM,
ping_preserve_iCCP,
status;
MemoryInfo
*volatile pixel_info;
png_bytep
ping_trans_alpha;
png_color_16p
ping_background,
ping_trans_color;
png_info
*end_info,
*ping_info;
png_struct
*ping;
png_textp
text;
png_uint_32
ping_height,
ping_width,
x_resolution,
y_resolution;
ssize_t
ping_rowbytes,
y;
register unsigned char
*p;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
size_t
length,
row_offset;
ssize_t
j;
unsigned char
*ping_pixels;
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
png_byte unused_chunks[]=
{
104, 73, 83, 84, (png_byte) '\0', /* hIST */
105, 84, 88, 116, (png_byte) '\0', /* iTXt */
112, 67, 65, 76, (png_byte) '\0', /* pCAL */
115, 67, 65, 76, (png_byte) '\0', /* sCAL */
115, 80, 76, 84, (png_byte) '\0', /* sPLT */
#if !defined(PNG_tIME_SUPPORTED)
116, 73, 77, 69, (png_byte) '\0', /* tIME */
#endif
#ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */
/* ignore the APNG chunks */
97, 99, 84, 76, (png_byte) '\0', /* acTL */
102, 99, 84, 76, (png_byte) '\0', /* fcTL */
102, 100, 65, 84, (png_byte) '\0', /* fdAT */
#endif
};
#endif
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,32);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,32);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOnePNGImage()\n"
" IM version = %s\n"
" Libpng version = %s",
im_vers, libpng_vers);
if (logging != MagickFalse)
{
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
#if (PNG_LIBPNG_VER >= 10400)
# ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */
if (image_info->verbose)
{
printf("Your PNG library (libpng-%s) is an old beta version.\n",
PNG_LIBPNG_VER_STRING);
printf("Please update it.\n");
}
# endif
#endif
image=mng_info->image;
if (logging != MagickFalse)
{
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" Before reading:\n"
" image->matte=%d\n"
" image->rendering_intent=%d\n"
" image->colorspace=%d\n"
" image->gamma=%f",
(int) image->matte, (int) image->rendering_intent,
(int) image->colorspace, image->gamma);
}
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent);
/* Set to an out-of-range color unless tRNS chunk is present */
transparent_color.red=65537;
transparent_color.green=65537;
transparent_color.blue=65537;
transparent_color.opacity=65537;
number_colors=0;
num_text = 0;
num_text_total = 0;
num_raw_profiles = 0;
ping_found_cHRM = MagickFalse;
ping_found_gAMA = MagickFalse;
ping_found_iCCP = MagickFalse;
ping_found_sRGB = MagickFalse;
ping_found_sRGB_cHRM = MagickFalse;
ping_preserve_iCCP = MagickFalse;
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image,
MagickPNGErrorHandler,MagickPNGWarningHandler, NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
end_info=png_create_info_struct(ping);
if (end_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG image is corrupt.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() with error.");
if (image != (Image *) NULL)
InheritException(exception,&image->exception);
return(GetFirstImageInList(image));
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for reading.
*/
mng_info->image_found++;
png_set_sig_bytes(ping,8);
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED)
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
png_set_read_fn(ping,image,png_get_data);
#else
#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED)
png_permit_empty_plte(ping,MagickTrue);
png_set_read_fn(ping,image,png_get_data);
#else
mng_info->image=image;
mng_info->bytes_in_read_buffer=0;
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
png_set_read_fn(ping,mng_info,mng_get_data);
#endif
#endif
}
else
png_set_read_fn(ping,image,png_get_data);
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",value) == MagickFalse)
{
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
ping_preserve_iCCP=MagickTrue;
#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)
/* Don't let libpng check for ICC/sRGB profile because we're going
* to do that anyway. This feature was added at libpng-1.6.12.
* If logging, go ahead and check and issue a warning as appropriate.
*/
if (logging == MagickFalse)
png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
else
{
/* Ignore the iCCP chunk */
png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1);
}
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
/* Ignore unused chunks and all unknown chunks except for exIf, caNv,
and vpAg */
# if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */
png_set_keep_unknown_chunks(ping, 2, NULL, 0);
# else
png_set_keep_unknown_chunks(ping, 1, NULL, 0);
# endif
png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1);
png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1);
png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1);
png_set_keep_unknown_chunks(ping, 1, unused_chunks,
(int)sizeof(unused_chunks)/5);
/* Callback for other unknown chunks */
png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
#if (PNG_LIBPNG_VER >= 10400)
/* Limit the size of the chunk storage cache used for sPLT, text,
* and unknown chunks.
*/
png_set_chunk_cache_max(ping, 32767);
#endif
#endif
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature */
png_set_check_for_invalid_index (ping, 0);
#endif
#if (PNG_LIBPNG_VER < 10400)
# if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \
(PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__)
/* Disable thread-unsafe features of pnggccrd */
if (png_access_version_number() >= 10200)
{
png_uint_32 mmx_disable_mask=0;
png_uint_32 asm_flags;
mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
| PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
| PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
| PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
asm_flags=png_get_asm_flags(ping);
png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask);
}
# endif
#endif
png_read_info(ping,ping_info);
/* Read and check IHDR chunk data */
png_get_IHDR(ping,ping_info,&ping_width,&ping_height,
&ping_bit_depth,&ping_color_type,
&ping_interlace_method,&ping_compression_method,
&ping_filter_method);
ping_file_depth = ping_bit_depth;
/* Swap bytes if requested */
if (ping_file_depth == 16)
{
const char
*value;
value=GetImageOption(image_info,"png:swap-bytes");
if (value == NULL)
value=GetImageArtifact(image,"png:swap-bytes");
if (value != NULL)
png_set_swap(ping);
}
/* Save bit-depth and color-type in case we later want to write a PNG00 */
{
char
msg[MaxTextExtent];
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type);
(void) SetImageProperty(image,"png:IHDR.color-type-orig",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth);
(void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg);
}
(void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans,
&ping_trans_color);
(void) png_get_bKGD(ping, ping_info, &ping_background);
if (ping_bit_depth < 8)
{
png_set_packing(ping);
ping_bit_depth = 8;
}
image->depth=ping_bit_depth;
image->depth=GetImageQuantumDepth(image,MagickFalse);
image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace;
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
image->rendering_intent=UndefinedIntent;
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent);
(void) ResetMagickMemory(&image->chromaticity,0,
sizeof(image->chromaticity));
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG width: %.20g, height: %.20g\n"
" PNG color_type: %d, bit_depth: %d\n"
" PNG compression_method: %d\n"
" PNG interlace_method: %d, filter_method: %d",
(double) ping_width, (double) ping_height,
ping_color_type, ping_bit_depth,
ping_compression_method,
ping_interlace_method,ping_filter_method);
}
if (png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_gAMA))
{
ping_found_gAMA=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG gAMA chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
ping_found_cHRM=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG cHRM chunk.");
}
if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
ping_found_sRGB=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG sRGB chunk.");
}
#ifdef PNG_READ_iCCP_SUPPORTED
if (ping_found_iCCP !=MagickTrue &&
ping_found_sRGB != MagickTrue &&
png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_iCCP))
{
int
compression;
#if (PNG_LIBPNG_VER < 10500)
png_charp
info;
#else
png_bytep
info;
#endif
png_charp
name;
png_uint_32
profile_length;
(void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info,
&profile_length);
if (profile_length != 0)
{
StringInfo
*profile;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG iCCP chunk.");
profile=BlobToStringInfo(info,profile_length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "ICC profile is NULL");
profile=DestroyStringInfo(profile);
}
else
{
if (ping_preserve_iCCP == MagickFalse)
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
break;
}
}
}
if (sRGB_info[icheck].len == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
(void) SetImageProfile(image,"icc",profile);
}
}
else /* Preserve-iCCP */
{
(void) SetImageProfile(image,"icc",profile);
}
profile=DestroyStringInfo(profile);
}
}
}
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
{
if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
if (png_get_sRGB(ping,ping_info,&intent))
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent (intent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG sRGB chunk: rendering_intent: %d",intent);
}
}
else if (mng_info->have_global_srgb)
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent
(mng_info->global_srgb_intent);
}
}
#endif
{
if (!png_get_gAMA(ping,ping_info,&file_gamma))
if (mng_info->have_global_gama)
png_set_gAMA(ping,ping_info,mng_info->global_gamma);
if (png_get_gAMA(ping,ping_info,&file_gamma))
{
image->gamma=(float) file_gamma;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG gAMA chunk: gamma: %f",file_gamma);
}
}
if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
if (mng_info->have_global_chrm != MagickFalse)
{
(void) png_set_cHRM(ping,ping_info,
mng_info->global_chrm.white_point.x,
mng_info->global_chrm.white_point.y,
mng_info->global_chrm.red_primary.x,
mng_info->global_chrm.red_primary.y,
mng_info->global_chrm.green_primary.x,
mng_info->global_chrm.green_primary.y,
mng_info->global_chrm.blue_primary.x,
mng_info->global_chrm.blue_primary.y);
}
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
(void) png_get_cHRM(ping,ping_info,
&image->chromaticity.white_point.x,
&image->chromaticity.white_point.y,
&image->chromaticity.red_primary.x,
&image->chromaticity.red_primary.y,
&image->chromaticity.green_primary.x,
&image->chromaticity.green_primary.y,
&image->chromaticity.blue_primary.x,
&image->chromaticity.blue_primary.y);
ping_found_cHRM=MagickTrue;
if (image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f)
ping_found_sRGB_cHRM=MagickTrue;
}
if (image->rendering_intent != UndefinedIntent)
{
if (ping_found_sRGB != MagickTrue &&
(ping_found_gAMA != MagickTrue ||
(image->gamma > .45 && image->gamma < .46)) &&
(ping_found_cHRM != MagickTrue ||
ping_found_sRGB_cHRM != MagickFalse) &&
ping_found_iCCP != MagickTrue)
{
png_set_sRGB(ping,ping_info,
Magick_RenderingIntent_to_PNG_RenderingIntent
(image->rendering_intent));
file_gamma=1.000f/2.200f;
ping_found_sRGB=MagickTrue;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting sRGB as if in input");
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info);
image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info);
if (logging != MagickFalse)
if (image->page.x || image->page.y)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double)
image->page.x,(double) image->page.y);
}
#endif
#if defined(PNG_pHYs_SUPPORTED)
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
if (mng_info->have_global_phys)
{
png_set_pHYs(ping,ping_info,
mng_info->global_x_pixels_per_unit,
mng_info->global_y_pixels_per_unit,
mng_info->global_phys_unit_type);
}
}
x_resolution=0;
y_resolution=0;
unit_type=0;
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
/*
Set image resolution.
*/
(void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution,
&unit_type);
image->x_resolution=(double) x_resolution;
image->y_resolution=(double) y_resolution;
if (unit_type == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=(double) x_resolution/100.0;
image->y_resolution=(double) y_resolution/100.0;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) x_resolution,(double) y_resolution,unit_type);
}
#endif
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
if ((number_colors == 0) &&
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE))
{
if (mng_info->global_plte_length)
{
png_set_PLTE(ping,ping_info,mng_info->global_plte,
(int) mng_info->global_plte_length);
if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS))
if (mng_info->global_trns_length)
{
if (mng_info->global_trns_length >
mng_info->global_plte_length)
{
png_warning(ping,
"global tRNS has more entries than global PLTE");
}
else
{
png_set_tRNS(ping,ping_info,mng_info->global_trns,
(int) mng_info->global_trns_length,NULL);
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
mng_info->have_saved_bkgd_index ||
#endif
png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
png_color_16
background;
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
if (mng_info->have_saved_bkgd_index)
background.index=mng_info->saved_bkgd_index;
#endif
if (png_get_valid(ping, ping_info, PNG_INFO_bKGD))
background.index=ping_background->index;
background.red=(png_uint_16)
mng_info->global_plte[background.index].red;
background.green=(png_uint_16)
mng_info->global_plte[background.index].green;
background.blue=(png_uint_16)
mng_info->global_plte[background.index].blue;
background.gray=(png_uint_16)
mng_info->global_plte[background.index].green;
png_set_bKGD(ping,ping_info,&background);
}
#endif
}
else
png_error(ping,"No global PLTE in file");
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (mng_info->have_global_bkgd &&
(!png_get_valid(ping,ping_info,PNG_INFO_bKGD)))
image->background_color=mng_info->mng_global_bkgd;
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
unsigned int
bkgd_scale;
/* Set image background color.
* Scale background components to 16-bit, then scale
* to quantum depth
*/
bkgd_scale = 1;
if (ping_file_depth == 1)
bkgd_scale = 255;
else if (ping_file_depth == 2)
bkgd_scale = 85;
else if (ping_file_depth == 4)
bkgd_scale = 17;
if (ping_file_depth <= 8)
bkgd_scale *= 257;
ping_background->red *= bkgd_scale;
ping_background->green *= bkgd_scale;
ping_background->blue *= bkgd_scale;
if (logging != MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n"
" bkgd_scale=%d. ping_background=(%d,%d,%d).",
ping_background->red,ping_background->green,
ping_background->blue,
bkgd_scale,ping_background->red,
ping_background->green,ping_background->blue);
}
image->background_color.red=
ScaleShortToQuantum(ping_background->red);
image->background_color.green=
ScaleShortToQuantum(ping_background->green);
image->background_color.blue=
ScaleShortToQuantum(ping_background->blue);
image->background_color.opacity=OpaqueOpacity;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->background_color=(%.20g,%.20g,%.20g).",
(double) image->background_color.red,
(double) image->background_color.green,
(double) image->background_color.blue);
}
#endif /* PNG_READ_bKGD_SUPPORTED */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
/*
Image has a tRNS chunk.
*/
int
max_sample;
size_t
one=1;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG tRNS chunk.");
max_sample = (int) ((one << ping_file_depth) - 1);
if ((ping_color_type == PNG_COLOR_TYPE_GRAY &&
(int)ping_trans_color->gray > max_sample) ||
(ping_color_type == PNG_COLOR_TYPE_RGB &&
((int)ping_trans_color->red > max_sample ||
(int)ping_trans_color->green > max_sample ||
(int)ping_trans_color->blue > max_sample)))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Ignoring PNG tRNS chunk with out-of-range sample.");
png_free_data(ping, ping_info, PNG_FREE_TRNS, 0);
png_set_invalid(ping,ping_info,PNG_INFO_tRNS);
image->matte=MagickFalse;
}
else
{
int
scale_to_short;
scale_to_short = 65535L/((1UL << ping_file_depth)-1);
/* Scale transparent_color to short */
transparent_color.red= scale_to_short*ping_trans_color->red;
transparent_color.green= scale_to_short*ping_trans_color->green;
transparent_color.blue= scale_to_short*ping_trans_color->blue;
transparent_color.opacity= scale_to_short*ping_trans_color->gray;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Raw tRNS graylevel = %d, scaled graylevel = %d.",
ping_trans_color->gray,transparent_color.opacity);
}
transparent_color.red=transparent_color.opacity;
transparent_color.green=transparent_color.opacity;
transparent_color.blue=transparent_color.opacity;
}
}
}
#if defined(PNG_READ_sBIT_SUPPORTED)
if (mng_info->have_global_sbit)
{
if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT))
png_set_sBIT(ping,ping_info,&mng_info->global_sbit);
}
#endif
num_passes=png_set_interlace_handling(ping);
png_read_update_info(ping,ping_info);
ping_rowbytes=png_get_rowbytes(ping,ping_info);
/*
Initialize image structure.
*/
mng_info->image_box.left=0;
mng_info->image_box.right=(ssize_t) ping_width;
mng_info->image_box.top=0;
mng_info->image_box.bottom=(ssize_t) ping_height;
if (mng_info->mng_type == 0)
{
mng_info->mng_width=ping_width;
mng_info->mng_height=ping_height;
mng_info->frame=mng_info->image_box;
mng_info->clip=mng_info->image_box;
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
image->compression=ZipCompression;
image->columns=ping_width;
image->rows=ping_height;
if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
((int) ping_bit_depth < 16 &&
(int) ping_color_type == PNG_COLOR_TYPE_GRAY))
{
size_t
one;
image->storage_class=PseudoClass;
one=1;
image->colors=one << ping_file_depth;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->colors > 256)
image->colors=256;
#else
if (image->colors > 65536L)
image->colors=65536L;
#endif
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
image->colors=(size_t) number_colors;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG PLTE chunk: number_colors: %d.",number_colors);
}
}
if (image->storage_class == PseudoClass)
{
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
png_error(ping,"Memory allocation failed");
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(palette[i].red);
image->colormap[i].green=ScaleCharToQuantum(palette[i].green);
image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue);
}
for ( ; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=0;
image->colormap[i].green=0;
image->colormap[i].blue=0;
}
}
else
{
Quantum
scale;
scale = 65535/((1UL << ping_file_depth)-1);
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
scale = ScaleShortToQuantum(scale);
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(Quantum) (i*scale);
image->colormap[i].green=(Quantum) (i*scale);
image->colormap[i].blue=(Quantum) (i*scale);
}
}
}
/* Set some properties for reporting by "identify" */
{
char
msg[MaxTextExtent];
/* encode ping_width, ping_height, ping_file_depth, ping_color_type,
ping_interlace_method in value */
(void) FormatLocaleString(msg,MaxTextExtent,
"%d, %d",(int) ping_width, (int) ping_height);
(void) SetImageProperty(image,"png:IHDR.width,height",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth);
(void) SetImageProperty(image,"png:IHDR.bit_depth",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)",
(int) ping_color_type,
Magick_ColorType_from_PNG_ColorType((int)ping_color_type));
(void) SetImageProperty(image,"png:IHDR.color_type",msg);
if (ping_interlace_method == 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)",
(int) ping_interlace_method);
}
else if (ping_interlace_method == 1)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)",
(int) ping_interlace_method);
}
else
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)",
(int) ping_interlace_method);
}
(void) SetImageProperty(image,"png:IHDR.interlace_method",msg);
if (number_colors != 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d",
(int) number_colors);
(void) SetImageProperty(image,"png:PLTE.number_colors",msg);
}
}
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,ping_info);
#endif
/*
Read image scanlines.
*/
if (image->delay != 0)
mng_info->scenes_found++;
if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || (
(image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t)
(image_info->first_scene+image_info->number_scenes))))
{
/* This happens later in non-ping decodes */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
image->storage_class=DirectClass;
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping PNG image data for scene %.20g",(double)
mng_info->scenes_found-1);
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage().");
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG IDAT chunk(s)");
if (num_passes > 1)
pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes*
sizeof(*ping_pixels));
else
pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Memory allocation failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting PNG pixels to pixel packets");
/*
Convert PNG pixels to pixel packets.
*/
{
MagickBooleanType
found_transparent_pixel;
found_transparent_pixel=MagickFalse;
if (image->storage_class == DirectClass)
{
QuantumInfo
*quantum_info;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Failed to allocate quantum_info");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert image to DirectClass pixel packets.
*/
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
for (y=0; y < (ssize_t) image->rows; y++)
{
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
else
{
if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayAlphaQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBAQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
IndexQuantum,ping_pixels+row_offset,exception);
else /* ping_color_type == PNG_COLOR_TYPE_RGB */
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBQuantum,ping_pixels+row_offset,exception);
}
if (found_transparent_pixel == MagickFalse)
{
/* Is there a transparent pixel in the row? */
if (y== 0 && logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Looking for cheap transparent pixel");
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if ((ping_color_type == PNG_COLOR_TYPE_RGBA ||
ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) &&
(GetPixelOpacity(q) != OpaqueOpacity))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
if ((ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_GRAY) &&
(ScaleQuantumToShort(GetPixelRed(q))
== transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(q))
== transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(q))
== transparent_color.blue))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
q++;
}
}
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,
(MagickOffsetType) y, image->rows);
if (status == MagickFalse)
break;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
else /* image->storage_class != DirectClass */
for (pass=0; pass < num_passes; pass++)
{
Quantum
*quantum_scanline;
register Quantum
*r;
/*
Convert grayscale image to PseudoClass pixel packets.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting grayscale pixels to pixel packets");
image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ?
MagickTrue : MagickFalse;
quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns,
(image->matte ? 2 : 1)*sizeof(*quantum_scanline));
if (quantum_scanline == (Quantum *) NULL)
png_error(ping,"Memory allocation failed");
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
alpha;
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=ping_pixels+row_offset;
r=quantum_scanline;
switch (ping_bit_depth)
{
case 8:
{
if (ping_color_type == 4)
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
*r++=*p++;
/* In image.h, OpaqueOpacity is 0
* TransparentOpacity is QuantumRange
* In a PNG datastream, Opaque is QuantumRange
* and Transparent is 0.
*/
alpha=ScaleCharToQuantum((unsigned char)*p++);
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
q++;
}
else
for (x=(ssize_t) image->columns-1; x >= 0; x--)
*r++=*p++;
break;
}
case 16:
{
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
size_t
quantum;
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
*r=ScaleShortToQuantum(quantum);
r++;
if (ping_color_type == 4)
{
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
alpha=ScaleShortToQuantum(quantum);
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
q++;
}
#else /* MAGICKCORE_QUANTUM_DEPTH == 8 */
*r++=(*p++);
p++; /* strip low byte */
if (ping_color_type == 4)
{
alpha=*p++;
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
p++;
q++;
}
#endif
}
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=quantum_scanline;
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*r++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline);
}
image->matte=found_transparent_pixel;
if (logging != MagickFalse)
{
if (found_transparent_pixel != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found transparent pixel");
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No transparent pixel was found");
ping_color_type&=0x03;
}
}
}
if (image->storage_class == PseudoClass)
{
MagickBooleanType
matte;
matte=image->matte;
image->matte=MagickFalse;
(void) SyncImage(image);
image->matte=matte;
}
png_read_end(ping,end_info);
if (image_info->number_scenes != 0 && mng_info->scenes_found-1 <
(ssize_t) image_info->first_scene && image->delay != 0)
{
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
image->colors=2;
(void) SetImageBackgroundColor(image);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() early.");
return(image);
}
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
ClassType
storage_class;
/*
Image has a transparent background.
*/
storage_class=image->storage_class;
image->matte=MagickTrue;
/* Balfour fix from imagemagick discourse server, 5 Feb 2010 */
if (storage_class == PseudoClass)
{
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
for (x=0; x < ping_num_trans; x++)
{
image->colormap[x].opacity =
ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x]));
}
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
for (x=0; x < (int) image->colors; x++)
{
if (ScaleQuantumToShort(image->colormap[x].red) ==
transparent_color.opacity)
{
image->colormap[x].opacity = (Quantum) TransparentOpacity;
}
}
}
(void) SyncImage(image);
}
#if 1 /* Should have already been done above, but glennrp problem P10
* needs this.
*/
else
{
for (y=0; y < (ssize_t) image->rows; y++)
{
image->storage_class=storage_class;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
/* Caution: on a Q8 build, this does not distinguish between
* 16-bit colors that differ only in the low byte
*/
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if (ScaleQuantumToShort(GetPixelRed(q))
== transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(q))
== transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(q))
== transparent_color.blue)
{
SetPixelOpacity(q,TransparentOpacity);
}
#if 0 /* I have not found a case where this is needed. */
else
{
SetPixelOpacity(q)=(Quantum) OpaqueOpacity;
}
#endif
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
image->storage_class=DirectClass;
}
if ((ping_color_type == PNG_COLOR_TYPE_GRAY) ||
(ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
double
image_gamma = image->gamma;
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->gamma=%f",(float) image_gamma);
if (image_gamma > 0.75)
{
/* Set image->rendering_intent to Undefined,
* image->colorspace to GRAY, and reset image->chromaticity.
*/
image->intensity = Rec709LuminancePixelIntensityMethod;
SetImageColorspace(image,GRAYColorspace);
}
else
{
RenderingIntent
save_rendering_intent = image->rendering_intent;
ChromaticityInfo
save_chromaticity = image->chromaticity;
SetImageColorspace(image,GRAYColorspace);
image->rendering_intent = save_rendering_intent;
image->chromaticity = save_chromaticity;
}
image->gamma = image_gamma;
}
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colorspace=%d",(int) image->colorspace);
for (j = 0; j < 2; j++)
{
if (j == 0)
status = png_get_text(ping,ping_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
else
status = png_get_text(ping,end_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
if (status != MagickFalse)
for (i=0; i < (ssize_t) num_text; i++)
{
/* Check for a profile */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG text chunk");
if (strlen(text[i].key) > 16 &&
memcmp(text[i].key, "Raw profile type ",17) == 0)
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember(text[i].key+17,value) == MagickFalse)
{
(void) Magick_png_read_raw_profile(ping,image,image_info,text,
(int) i);
num_raw_profiles++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Read raw profile %s",text[i].key+17);
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping raw profile %s",text[i].key+17);
}
}
else
{
char
*value;
length=text[i].text_length;
value=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*value));
if (value == (char *) NULL)
png_error(ping,"Memory allocation failed");
*value='\0';
(void) ConcatenateMagickString(value,text[i].text,length+2);
/* Don't save "density" or "units" property if we have a pHYs
* chunk
*/
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) ||
(LocaleCompare(text[i].key,"density") != 0 &&
LocaleCompare(text[i].key,"units") != 0))
(void) SetImageProperty(image,text[i].key,value);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu\n"
" Keyword: %s",
(unsigned long) length,
text[i].key);
}
value=DestroyString(value);
}
}
num_text_total += num_text;
}
#ifdef MNG_OBJECT_BUFFERS
/*
Store the object if necessary.
*/
if (object_id && !mng_info->frozen[object_id])
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
{
/*
create a new object buffer.
*/
mng_info->ob[object_id]=(MngBuffer *)
AcquireMagickMemory(sizeof(MngBuffer));
if (mng_info->ob[object_id] != (MngBuffer *) NULL)
{
mng_info->ob[object_id]->image=(Image *) NULL;
mng_info->ob[object_id]->reference_count=1;
}
}
if ((mng_info->ob[object_id] == (MngBuffer *) NULL) ||
mng_info->ob[object_id]->frozen)
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
png_error(ping,"Memory allocation failed");
if (mng_info->ob[object_id]->frozen)
png_error(ping,"Cannot overwrite frozen MNG object buffer");
}
else
{
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image=DestroyImage
(mng_info->ob[object_id]->image);
mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue,
&image->exception);
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image->file=(FILE *) NULL;
else
png_error(ping, "Cloning image for object buffer failed");
if (ping_width > 250000L || ping_height > 250000L)
png_error(ping,"PNG Image dimensions are too large.");
mng_info->ob[object_id]->width=ping_width;
mng_info->ob[object_id]->height=ping_height;
mng_info->ob[object_id]->color_type=ping_color_type;
mng_info->ob[object_id]->sample_depth=ping_bit_depth;
mng_info->ob[object_id]->interlace_method=ping_interlace_method;
mng_info->ob[object_id]->compression_method=
ping_compression_method;
mng_info->ob[object_id]->filter_method=ping_filter_method;
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
plte;
/*
Copy the PLTE to the object buffer.
*/
png_get_PLTE(ping,ping_info,&plte,&number_colors);
mng_info->ob[object_id]->plte_length=number_colors;
for (i=0; i < number_colors; i++)
{
mng_info->ob[object_id]->plte[i]=plte[i];
}
}
else
mng_info->ob[object_id]->plte_length=0;
}
}
#endif
/* Set image->matte to MagickTrue if the input colortype supports
* alpha or if a valid tRNS chunk is present, no matter whether there
* is actual transparency present.
*/
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
#if 0 /* I'm not sure what's wrong here but it does not work. */
if (image->matte != MagickFalse)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) SetImageType(image,GrayscaleMatteType);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteMatteType);
else
(void) SetImageType(image,TrueColorMatteType);
}
else
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) SetImageType(image,GrayscaleType);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteType);
else
(void) SetImageType(image,TrueColorType);
}
#endif
/* Set more properties for identify to retrieve */
{
char
msg[MaxTextExtent];
if (num_text_total != 0)
{
/* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */
(void) FormatLocaleString(msg,MaxTextExtent,
"%d tEXt/zTXt/iTXt chunks were found", num_text_total);
(void) SetImageProperty(image,"png:text",msg);
}
if (num_raw_profiles != 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"%d were found", num_raw_profiles);
(void) SetImageProperty(image,"png:text-encoded profiles",msg);
}
/* cHRM chunk: */
if (ping_found_cHRM != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found (see Chromaticity, above)");
(void) SetImageProperty(image,"png:cHRM",msg);
}
/* bKGD chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found (see Background color, above)");
(void) SetImageProperty(image,"png:bKGD",msg);
}
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found");
/* iCCP chunk: */
if (ping_found_iCCP != MagickFalse)
(void) SetImageProperty(image,"png:iCCP",msg);
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
(void) SetImageProperty(image,"png:tRNS",msg);
#if defined(PNG_sRGB_SUPPORTED)
/* sRGB chunk: */
if (ping_found_sRGB != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"intent=%d (%s)",
(int) intent,
Magick_RenderingIntentString_from_PNG_RenderingIntent(intent));
(void) SetImageProperty(image,"png:sRGB",msg);
}
#endif
/* gAMA chunk: */
if (ping_found_gAMA != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"gamma=%.8g (See Gamma, above)", file_gamma);
(void) SetImageProperty(image,"png:gAMA",msg);
}
#if defined(PNG_pHYs_SUPPORTED)
/* pHYs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"x_res=%.10g, y_res=%.10g, units=%d",
(double) x_resolution,(double) y_resolution, unit_type);
(void) SetImageProperty(image,"png:pHYs",msg);
}
#endif
#if defined(PNG_oFFs_SUPPORTED)
/* oFFs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
(void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g",
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:oFFs",msg);
}
#endif
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,end_info);
#endif
/* caNv chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
(image->page.x != 0 || image->page.y != 0))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:caNv",msg);
}
/* vpAg chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"width=%.20g, height=%.20g",
(double) image->page.width,(double) image->page.height);
(void) SetImageProperty(image,"png:vpAg",msg);
}
}
/*
Relinquish resources.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block, revert to
* Throwing an Exception when an error occurs.
*/
return(image);
/* end of reading one PNG image */
}
static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
ThrowReaderException(FileOpenError,"UnableToOpenFile");
/*
Verify PNG signature.
*/
count=ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a PNG datastream.
*/
if (GetBlobSize(image) < 61)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOnePNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if ((image->columns == 0) || (image->rows == 0))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error.");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if ((IssRGBColorspace(image->colorspace) != MagickFalse) &&
((image->gamma < .45) || (image->gamma > .46)) &&
!(image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f))
SetImageColorspace(image,RGBColorspace);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()");
return(image);
}
#if defined(JNG_SUPPORTED)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file
% (minus the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadOneJNGImage method is:
%
% Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJNGImage() reads a JPEG Network Graphics (JNG) image file
% (including the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadJNGImage method is:
%
% Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo
% *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a JNG datastream.
*/
if (GetBlobSize(image) < 147)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
#endif
static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length+
MagickPathExtent,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length > 1)
{
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
(p[5] << 16) | (p[6] << 8) | p[7]);
mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
(p[9] << 16) | (p[10] << 8) | p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && (p-chunk) < (ssize_t) (length-4))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && (p-chunk) < (ssize_t) (length-4))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && (p-chunk) < (ssize_t) (length-17))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=17;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(p[12] << 8) & p[13];
else
basi_red=0;
if (length > 15)
basi_green=(p[14] << 8) & p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(p[16] << 8) & p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(p[18] << 8) & p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
}
static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/* Open image file. */
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneMNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadMNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()");
return(GetFirstImageInList(image));
}
#else /* PNG_LIBPNG_VER > 10011 */
static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"PNG library is too old","`%s'",image_info->filename);
return(Image *) NULL;
}
static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
return(ReadPNGImage(image_info,exception));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNGImage() adds properties for the PNG image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPNGImage method is:
%
% size_t RegisterPNGImage(void)
%
*/
ModuleExport size_t RegisterPNGImage(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
static const char
*PNGNote=
{
"See http://www.libpng.org/ for details about the PNG format."
},
*JNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the JNG\n"
"format."
},
*MNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the MNG\n"
"format."
};
*version='\0';
#if defined(PNG_LIBPNG_VER_STRING)
(void) ConcatenateMagickString(version,"libpng ",MaxTextExtent);
(void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent);
if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,png_get_libpng_ver(NULL),
MaxTextExtent);
}
#endif
entry=SetMagickInfo("MNG");
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadMNGImage;
entry->encoder=(EncodeImageHandler *) WriteMNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsMNG;
entry->description=ConstantString("Multiple-image Network Graphics");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("video/x-mng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(MNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Portable Network Graphics");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
if (*version != '\0')
entry->version=ConstantString(version);
entry->note=ConstantString(PNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG8");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"8-bit indexed with optional binary transparency");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG24");
*version='\0';
#if defined(ZLIB_VERSION)
(void) ConcatenateMagickString(version,"zlib ",MaxTextExtent);
(void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent);
if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,zlib_version,MaxTextExtent);
}
#endif
if (*version != '\0')
entry->version=ConstantString(version);
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 24-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG32");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 32-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG48");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 48-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG64");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 64-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG00");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"PNG inheriting bit-depth, color-type from original if possible");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JNG");
#if defined(JNG_SUPPORTED)
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJNGImage;
entry->encoder=(EncodeImageHandler *) WriteJNGImage;
#endif
#endif
entry->magick=(IsImageFormatHandler *) IsJNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("JPEG Network Graphics");
entry->mime_type=ConstantString("image/x-jng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(JNGNote);
(void) RegisterMagickInfo(entry);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
ping_semaphore=AllocateSemaphoreInfo();
#endif
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNGImage() removes format registrations made by the
% PNG module from the list of supported formats.
%
% The format of the UnregisterPNGImage method is:
%
% UnregisterPNGImage(void)
%
*/
ModuleExport void UnregisterPNGImage(void)
{
(void) UnregisterMagickInfo("MNG");
(void) UnregisterMagickInfo("PNG");
(void) UnregisterMagickInfo("PNG8");
(void) UnregisterMagickInfo("PNG24");
(void) UnregisterMagickInfo("PNG32");
(void) UnregisterMagickInfo("PNG48");
(void) UnregisterMagickInfo("PNG64");
(void) UnregisterMagickInfo("PNG00");
(void) UnregisterMagickInfo("JNG");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
if (ping_semaphore != (SemaphoreInfo *) NULL)
DestroySemaphoreInfo(&ping_semaphore);
#endif
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMNGImage() writes an image in the Portable Network Graphics
% Group's "Multiple-image Network Graphics" encoded image format.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteMNGImage method is:
%
% MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
% To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also
% "To do" under ReadPNGImage):
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% Write the iCCP chunk at MNG level when (icc profile length > 0)
%
% Improve selection of color type (use indexed-colour or indexed-colour
% with tRNS when 256 or fewer unique RGBA values are present).
%
% Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3)
% This will be complicated if we limit ourselves to generating MNG-LC
% files. For now we ignore disposal method 3 and simply overlay the next
% image on it.
%
% Check for identical PLTE's or PLTE/tRNS combinations and use a
% global MNG PLTE or PLTE/tRNS combination when appropriate.
% [mostly done 15 June 1999 but still need to take care of tRNS]
%
% Check for identical sRGB and replace with a global sRGB (and remove
% gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and
% replace with global gAMA/cHRM (or with sRGB if appropriate; replace
% local gAMA/cHRM with local sRGB if appropriate).
%
% Check for identical sBIT chunks and write global ones.
%
% Provide option to skip writing the signature tEXt chunks.
%
% Use signatures to detect identical objects and reuse the first
% instance of such objects instead of writing duplicate objects.
%
% Use a smaller-than-32k value of compression window size when
% appropriate.
%
% Encode JNG datastreams. Mostly done as of 5.5.2; need to write
% ancillary text chunks and save profiles.
%
% Provide an option to force LC files (to ensure exact framing rate)
% instead of VLC.
%
% Provide an option to force VLC files instead of LC, even when offsets
% are present. This will involve expanding the embedded images with a
% transparent region at the top and/or left.
*/
static void
Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping,
png_info *ping_info, unsigned char *profile_type, unsigned char
*profile_description, unsigned char *profile_data, png_uint_32 length)
{
png_textp
text;
register ssize_t
i;
unsigned char
*sp;
png_charp
dp;
png_uint_32
allocated_length,
description_length;
unsigned char
hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0)
return;
if (image_info->verbose)
{
(void) printf("writing raw profile: type=%s, length=%.20g\n",
(char *) profile_type, (double) length);
}
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
description_length=(png_uint_32) strlen((const char *) profile_description);
allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20
+ description_length);
#if PNG_LIBPNG_VER >= 10400
text[0].text=(png_charp) png_malloc(ping,
(png_alloc_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80);
#else
text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80);
#endif
text[0].key[0]='\0';
(void) ConcatenateMagickString(text[0].key,
"Raw profile type ",MaxTextExtent);
(void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62);
sp=profile_data;
dp=text[0].text;
*dp++='\n';
(void) CopyMagickString(dp,(const char *) profile_description,
allocated_length);
dp+=description_length;
*dp++='\n';
(void) FormatLocaleString(dp,allocated_length-
(png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length);
dp+=8;
for (i=0; i < (ssize_t) length; i++)
{
if (i%36 == 0)
*dp++='\n';
*(dp++)=(char) hex[((*sp >> 4) & 0x0f)];
*(dp++)=(char) hex[((*sp++ ) & 0x0f)];
}
*dp++='\n';
*dp='\0';
text[0].text_length=(png_size_t) (dp-text[0].text);
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? -1 : 0;
if (text[0].text_length <= allocated_length)
png_set_text(ping,ping_info,text,1);
png_free(ping,text[0].text);
png_free(ping,text[0].key);
png_free(ping,text);
}
static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image,
const char *string, MagickBooleanType logging)
{
char
*name;
const StringInfo
*profile;
unsigned char
*data;
png_uint_32 length;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (const StringInfo *) NULL)
{
StringInfo
*ping_profile;
if (LocaleNCompare(name,string,11) == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found %s profile",name);
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
data[4]=data[3];
data[3]=data[2];
data[2]=data[1];
data[1]=data[0];
(void) WriteBlobMSBULong(image,length-5); /* data length */
(void) WriteBlob(image,length-1,data+1);
(void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1));
ping_profile=DestroyStringInfo(ping_profile);
}
}
name=GetNextImageProfile(image);
}
return(MagickTrue);
}
#if defined(PNG_tIME_SUPPORTED)
static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info,
const char *date)
{
unsigned int
day,
hour,
minute,
month,
second,
year;
png_time
ptime;
time_t
ttime;
if (date != (const char *) NULL)
{
if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute,
&second) != 6)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,
"Invalid date format specified for png:tIME","`%s'",
image->filename);
return;
}
ptime.year=(png_uint_16) year;
ptime.month=(png_byte) month;
ptime.day=(png_byte) day;
ptime.hour=(png_byte) hour;
ptime.minute=(png_byte) minute;
ptime.second=(png_byte) second;
}
else
{
time(&ttime);
png_convert_from_time_t(&ptime,ttime);
}
png_set_tIME(ping,info,&ptime);
}
#endif
/* Write one PNG image */
static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info,Image *image)
{
char
s[2];
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MaxTextExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MaxTextExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s",
im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s",
libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
/* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_vpAg=mng_info->ping_exclude_vpAg;
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
property=(const char *) NULL;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->magick= %s",image_info->magick);
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register PixelPacket
*r;
ExceptionInfo
*exception;
exception=(&image->exception);
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 && image->matte == MagickFalse)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
number_opaque = (int) image->colors;
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
else
ping_have_color=MagickTrue;
ping_have_non_bw=MagickFalse;
if (image->matte != MagickFalse)
{
number_transparent = 2;
number_semitransparent = 1;
}
else
{
number_transparent = 0;
number_semitransparent = 0;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->matte is MagickFalse, we ignore the opacity channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
ExceptionInfo
*exception;
int
n;
PixelPacket
opaque[260],
semitransparent[260],
transparent[260];
register IndexPacket
*indexes;
register const PixelPacket
*s,
*q;
register PixelPacket
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->matte=%.20g",(double) image->matte);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,opacity)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
exception=(&image->exception);
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte == MagickFalse ||
GetPixelOpacity(q) == OpaqueOpacity)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelRGB(q, opaque);
opaque[0].opacity=OpaqueOpacity;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (IsColorEqual(q, opaque+i))
break;
}
if (i == (ssize_t) number_opaque &&
number_opaque < 259)
{
number_opaque++;
GetPixelRGB(q, opaque+i);
opaque[i].opacity=OpaqueOpacity;
}
}
}
else if (q->opacity == TransparentOpacity)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelRGBO(q, transparent);
ping_trans_color.red=
(unsigned short) GetPixelRed(q);
ping_trans_color.green=
(unsigned short) GetPixelGreen(q);
ping_trans_color.blue=
(unsigned short) GetPixelBlue(q);
ping_trans_color.gray=
(unsigned short) GetPixelRed(q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (IsColorEqual(q, transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelRGBO(q, transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelRGBO(q, semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (IsColorEqual(q, semitransparent+i)
&& GetPixelOpacity(q) ==
semitransparent[i].opacity)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelRGBO(q, semitransparent+i);
}
}
}
q++;
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(s) != GetPixelGreen(s) ||
GetPixelRed(s) != GetPixelBlue(s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s++;
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(s) != 0 &&
GetPixelRed(s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s++;
}
}
}
}
}
if (image_colors < 257)
{
PixelPacket
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors) ==
MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->matte == MagickFalse ||
image->colormap[i].opacity ==
GetPixelOpacity(q)) &&
image->colormap[i].red ==
GetPixelRed(q) &&
image->colormap[i].green ==
GetPixelGreen(q) &&
image->colormap[i].blue ==
GetPixelBlue(q))
{
SetPixelIndex(indexes+x,i);
break;
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,opacity)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) > TransparentOpacity/2)
{
SetPixelOpacity(r,TransparentOpacity);
SetPixelRgb(r,&image->background_color);
}
else
SetPixelOpacity(r,OpaqueOpacity);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].opacity =
(image->colormap[i].opacity > TransparentOpacity/2 ?
TransparentOpacity : OpaqueOpacity);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR04PixelRGB(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR03PixelRGB(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR02PixelBlue(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 &&
GetPixelOpacity(r) == OpaqueOpacity)
{
SetPixelRed(r,ScaleCharToQuantum(0x24));
}
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
ExceptionInfo
*exception;
register const PixelPacket
*q;
exception=(&image->exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (q->opacity != TransparentOpacity &&
(unsigned short) GetPixelRed(q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q++;
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->matte;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",image->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->matte);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->x_resolution != 0) && (image->y_resolution != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->x_resolution+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->y_resolution+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->x_resolution;
ping_pHYs_y_resolution=(png_uint_32) image->y_resolution;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorMatteType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteMatteType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image,
image->colormap))) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte) (255-
ScaleQuantumToChar(image->colormap[i].opacity));
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16)
((maxval/65535.)*(ScaleQuantumToShort((Quantum)
GetPixelLuma(image,&image->background_color)))+.5);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_background.index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_background.gray is %d",
(int) ping_background.gray);
}
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This is addressed by using
"-define png:compression-strategy", etc., which takes precedence
over -quality.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->matte == MagickFalse)
{
/* Add an opaque matte channel */
image->matte = MagickTrue;
(void) SetImageOpacity(image,0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
if (mng_info->have_write_global_plte && matte == MagickFalse)
{
png_set_PLTE(ping,ping_info,NULL,0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up empty PLTE chunk");
}
else
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(const png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
ping_have_iCCP = MagickTrue;
}
}
else
#endif
if (ping_exclude_zCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXT chunk with uuencoded ICC");
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
ping_have_iCCP = MagickTrue;
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk with %s profile",name);
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME");
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify");
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
(void) ping_have_blob;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
/* write any png-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging);
png_write_info(ping,ping_info);
/* write any PNG-chunk-m profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging);
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
/* write vpAg chunk (deprecated, replaced by caNv) */
if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
unsigned char
chunk[14];
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
}
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const PixelPacket
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const PixelPacket
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const PixelPacket
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass);
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
&image->exception);
}
else
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write any PNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging);
/* write exIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
#if 0 /* eXIf chunk is registered */
PNGType(chunk,mng_eXIf);
#else /* eXIf chunk not yet registered; write exIf instead */
PNGType(chunk,mng_exIf);
#endif
if (length < 7)
break; /* othewise crashes */
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data+6);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),
data+6, (uInt) length));
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(image,"png:bit-depth-written",s);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNGImage() writes a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) image file.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WritePNGImage method is:
%
% MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% Returns MagickTrue on success, MagickFalse on failure.
%
% Communicating with the PNG encoder:
%
% While the datastream written is always in PNG format and normally would
% be given the "png" file extension, this method also writes the following
% pseudo-formats which are subsets of png:
%
% o PNG8: An 8-bit indexed PNG datastream is written. If the image has
% a depth greater than 8, the depth is reduced. If transparency
% is present, the tRNS chunk must only have values 0 and 255
% (i.e., transparency is binary: fully opaque or fully
% transparent). If other values are present they will be
% 50%-thresholded to binary transparency. If more than 256
% colors are present, they will be quantized to the 4-4-4-1,
% 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color
% of any resulting fully-transparent pixels is changed to
% the image's background color.
%
% If you want better quantization or dithering of the colors
% or alpha than that, you need to do it before calling the
% PNG encoder. The pixels contain 8-bit indices even if
% they could be represented with 1, 2, or 4 bits. Grayscale
% images will be written as indexed PNG files even though the
% PNG grayscale type might be slightly more efficient. Please
% note that writing to the PNG8 format may result in loss
% of color and alpha data.
%
% o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. The only loss incurred
% is reduction of sample depth to 8. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG32: An 8-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 255. The alpha
% channel is present even if the image is fully opaque.
% The only loss in data is the reduction of the sample depth
% to 8.
%
% o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG64: A 16-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 65535. The alpha
% channel is present even if the image is fully opaque.
%
% o PNG00: A PNG that inherits its colortype and bit-depth from the input
% image, if the input was a PNG, is written. If these values
% cannot be found, or if the pixels have been changed in a way
% that makes this impossible, then "PNG00" falls back to the
% regular "PNG" format.
%
% o -define: For more precise control of the PNG output, you can use the
% Image options "png:bit-depth" and "png:color-type". These
% can be set from the commandline with "-define" and also
% from the application programming interfaces. The options
% are case-independent and are converted to lowercase before
% being passed to this encoder.
%
% png:color-type can be 0, 2, 3, 4, or 6.
%
% When png:color-type is 0 (Grayscale), png:bit-depth can
% be 1, 2, 4, 8, or 16.
%
% When png:color-type is 2 (RGB), png:bit-depth can
% be 8 or 16.
%
% When png:color-type is 3 (Indexed), png:bit-depth can
% be 1, 2, 4, or 8. This refers to the number of bits
% used to store the index. The color samples always have
% bit-depth 8 in indexed PNG files.
%
% When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte),
% png:bit-depth can be 8 or 16.
%
% If the image cannot be written without loss with the
% requested bit-depth and color-type, a PNG file will not
% be written, a warning will be issued, and the encoder will
% return MagickFalse.
%
% Since image encoders should not be responsible for the "heavy lifting",
% the user should make sure that ImageMagick has already reduced the
% image depth and number of colors and limit transparency to binary
% transparency prior to attempting to write the image with depth, color,
% or transparency limitations.
%
% To do: Enforce the previous paragraph.
%
% Note that another definition, "png:bit-depth-written" exists, but it
% is not intended for external use. It is only used internally by the
% PNG encoder to inform the JNG encoder of the depth of the alpha channel.
%
% It is possible to request that the PNG encoder write previously-formatted
% ancillary chunks in the output PNG file, using the "-profile" commandline
% option as shown below or by setting the profile via a programming
% interface:
%
% -profile PNG-chunk-x:<file>
%
% where x is a location flag and <file> is a file containing the chunk
% name in the first 4 bytes, then a colon (":"), followed by the chunk data.
% This encoder will compute the chunk length and CRC, so those must not
% be included in the file.
%
% "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT),
% or "e" (end, i.e., after IDAT). If you want to write multiple chunks
% of the same type, then add a short unique string after the "x" to prevent
% subsequent profiles from overwriting the preceding ones, e.g.,
%
% -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02
%
% As of version 6.6.6 the following optimizations are always done:
%
% o 32-bit depth is reduced to 16.
% o 16-bit depth is reduced to 8 if all pixels contain samples whose
% high byte and low byte are identical.
% o Palette is sorted to remove unused entries and to put a
% transparent color first, if BUILD_PNG_PALETTE is defined.
% o Opaque matte channel is removed when writing an indexed PNG.
% o Grayscale images are reduced to 1, 2, or 4 bit depth if
% this can be done without loss and a larger bit depth N was not
% requested via the "-define png:bit-depth=N" option.
% o If matte channel is present but only one transparent color is
% present, RGB+tRNS is written instead of RGBA
% o Opaque matte channel is removed (or added, if color-type 4 or 6
% was requested when converting an opaque image).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
excluding,
logging,
status;
MngInfo
*mng_info;
const char
*value;
int
source;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
mng_info->equal_backgrounds=MagickTrue;
/* See if user has requested a specific PNG subformat */
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0;
mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0;
value=GetImageOption(image_info,"png:format");
if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0)
{
mng_info->write_png8 = MagickFalse;
mng_info->write_png24 = MagickFalse;
mng_info->write_png32 = MagickFalse;
mng_info->write_png48 = MagickFalse;
mng_info->write_png64 = MagickFalse;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",value);
if (LocaleCompare(value,"png8") == 0)
mng_info->write_png8 = MagickTrue;
else if (LocaleCompare(value,"png24") == 0)
mng_info->write_png24 = MagickTrue;
else if (LocaleCompare(value,"png32") == 0)
mng_info->write_png32 = MagickTrue;
else if (LocaleCompare(value,"png48") == 0)
mng_info->write_png48 = MagickTrue;
else if (LocaleCompare(value,"png64") == 0)
mng_info->write_png64 = MagickTrue;
else if ((LocaleCompare(value,"png00") == 0) ||
LocaleCompare(image_info->magick,"PNG00") == 0)
{
/* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */
value=GetImageProperty(image,"png:IHDR.bit-depth-orig");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited bit depth=%s",value);
if (value != (char *) NULL)
{
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
}
value=GetImageProperty(image,"png:IHDR.color-type-orig");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited color type=%s",value);
if (value != (char *) NULL)
{
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
}
}
}
if (mng_info->write_png8)
{
mng_info->write_png_colortype = /* 3 */ 4;
mng_info->write_png_depth = 8;
image->depth = 8;
}
if (mng_info->write_png24)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 8;
image->depth = 8;
if (image->matte != MagickFalse)
(void) SetImageType(image,TrueColorMatteType);
else
(void) SetImageType(image,TrueColorType);
(void) SyncImage(image);
}
if (mng_info->write_png32)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 8;
image->depth = 8;
image->matte = MagickTrue;
(void) SetImageType(image,TrueColorMatteType);
(void) SyncImage(image);
}
if (mng_info->write_png48)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 16;
image->depth = 16;
if (image->matte != MagickFalse)
(void) SetImageType(image,TrueColorMatteType);
else
(void) SetImageType(image,TrueColorType);
(void) SyncImage(image);
}
if (mng_info->write_png64)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 16;
image->depth = 16;
image->matte = MagickTrue;
(void) SetImageType(image,TrueColorMatteType);
(void) SyncImage(image);
}
value=GetImageOption(image_info,"png:bit-depth");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:bit-depth",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:bit-depth=%d was defined.\n",mng_info->write_png_depth);
}
value=GetImageOption(image_info,"png:color-type");
if (value != (char *) NULL)
{
/* We must store colortype+1 because 0 is a valid colortype */
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:color-type",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:color-type=%d was defined.\n",mng_info->write_png_colortype-1);
}
/* Check for chunks to be excluded:
*
* The default is to not exclude any known chunks except for any
* listed in the "unused_chunks" array, above.
*
* Chunks can be listed for exclusion via a "png:exclude-chunk"
* define (in the image properties or in the image artifacts)
* or via a mng_info member. For convenience, in addition
* to or instead of a comma-separated list of chunks, the
* "exclude-chunk" string can be simply "all" or "none".
*
* The exclude-chunk define takes priority over the mng_info.
*
* A "png:include-chunk" define takes priority over both the
* mng_info and the "png:exclude-chunk" define. Like the
* "exclude-chunk" string, it can define "all" or "none" as
* well as a comma-separated list. Chunks that are unknown to
* ImageMagick are always excluded, regardless of their "copy-safe"
* status according to the PNG specification, and even if they
* appear in the "include-chunk" list. Such defines appearing among
* the image options take priority over those found among the image
* artifacts.
*
* Finally, all chunks listed in the "unused_chunks" array are
* automatically excluded, regardless of the other instructions
* or lack thereof.
*
* if you exclude sRGB but not gAMA (recommended), then sRGB chunk
* will not be written and the gAMA chunk will only be written if it
* is not between .45 and .46, or approximately (1.0/2.2).
*
* If you exclude tRNS and the image has transparency, the colortype
* is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA).
*
* The -strip option causes StripImage() to set the png:include-chunk
* artifact to "none,trns,gama".
*/
mng_info->ping_exclude_bKGD=MagickFalse;
mng_info->ping_exclude_caNv=MagickFalse;
mng_info->ping_exclude_cHRM=MagickFalse;
mng_info->ping_exclude_date=MagickFalse;
mng_info->ping_exclude_eXIf=MagickFalse;
mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */
mng_info->ping_exclude_gAMA=MagickFalse;
mng_info->ping_exclude_iCCP=MagickFalse;
/* mng_info->ping_exclude_iTXt=MagickFalse; */
mng_info->ping_exclude_oFFs=MagickFalse;
mng_info->ping_exclude_pHYs=MagickFalse;
mng_info->ping_exclude_sRGB=MagickFalse;
mng_info->ping_exclude_tEXt=MagickFalse;
mng_info->ping_exclude_tIME=MagickFalse;
mng_info->ping_exclude_tRNS=MagickFalse;
mng_info->ping_exclude_vpAg=MagickFalse;
mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */
mng_info->ping_exclude_zTXt=MagickFalse;
mng_info->ping_preserve_colormap=MagickFalse;
value=GetImageOption(image_info,"png:preserve-colormap");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-colormap");
if (value != NULL)
mng_info->ping_preserve_colormap=MagickTrue;
mng_info->ping_preserve_iCCP=MagickFalse;
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
mng_info->ping_preserve_iCCP=MagickTrue;
/* These compression-level, compression-strategy, and compression-filter
* defines take precedence over values from the -quality option.
*/
value=GetImageOption(image_info,"png:compression-level");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-level");
if (value != NULL)
{
/* To do: use a "LocaleInteger:()" function here. */
/* We have to add 1 to everything because 0 is a valid input,
* and we want to use 0 (the default) to mean undefined.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_level = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_level = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_level = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_level = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_level = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_level = 6;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_compression_level = 7;
else if (LocaleCompare(value,"7") == 0)
mng_info->write_png_compression_level = 8;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_compression_level = 9;
else if (LocaleCompare(value,"9") == 0)
mng_info->write_png_compression_level = 10;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-level",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-strategy");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-strategy");
if (value != NULL)
{
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_strategy = Z_FILTERED+1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
else if (LocaleCompare(value,"3") == 0)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy = Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else if (LocaleCompare(value,"4") == 0)
#ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */
mng_info->write_png_compression_strategy = Z_FIXED+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-strategy",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-filter");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-filter");
if (value != NULL)
{
/* To do: combinations of filters allowed by libpng
* masks 0x08 through 0xf8
*
* Implement this as a comma-separated list of 0,1,2,3,4,5
* where 5 is a special case meaning PNG_ALL_FILTERS.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_filter = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_filter = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_filter = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_filter = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_filter = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_filter = 6;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-filter",
"=%s",value);
}
for (source=0; source<8; source++)
{
value = NULL;
if (source == 0)
value=GetImageOption(image_info,"png:exclude-chunks");
if (source == 1)
value=GetImageArtifact(image,"png:exclude-chunks");
if (source == 2)
value=GetImageOption(image_info,"png:exclude-chunk");
if (source == 3)
value=GetImageArtifact(image,"png:exclude-chunk");
if (source == 4)
value=GetImageOption(image_info,"png:include-chunks");
if (source == 5)
value=GetImageArtifact(image,"png:include-chunks");
if (source == 6)
value=GetImageOption(image_info,"png:include-chunk");
if (source == 7)
value=GetImageArtifact(image,"png:include-chunk");
if (value == NULL)
continue;
if (source < 4)
excluding = MagickTrue;
else
excluding = MagickFalse;
if (logging != MagickFalse)
{
if (source == 0 || source == 2)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image options.\n", value);
else if (source == 1 || source == 3)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image artifacts.\n", value);
else if (source == 4 || source == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image options.\n", value);
else /* if (source == 5 || source == 7) */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image artifacts.\n", value);
}
if (IsOptionMember("all",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding;
mng_info->ping_exclude_caNv=excluding;
mng_info->ping_exclude_cHRM=excluding;
mng_info->ping_exclude_date=excluding;
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
mng_info->ping_exclude_gAMA=excluding;
mng_info->ping_exclude_iCCP=excluding;
/* mng_info->ping_exclude_iTXt=excluding; */
mng_info->ping_exclude_oFFs=excluding;
mng_info->ping_exclude_pHYs=excluding;
mng_info->ping_exclude_sRGB=excluding;
mng_info->ping_exclude_tIME=excluding;
mng_info->ping_exclude_tEXt=excluding;
mng_info->ping_exclude_tRNS=excluding;
mng_info->ping_exclude_vpAg=excluding;
mng_info->ping_exclude_zCCP=excluding;
mng_info->ping_exclude_zTXt=excluding;
}
if (IsOptionMember("none",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
/* mng_info->ping_exclude_iTXt=!excluding; */
mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
}
if (IsOptionMember("bkgd",value) != MagickFalse)
mng_info->ping_exclude_bKGD=excluding;
if (IsOptionMember("caNv",value) != MagickFalse)
mng_info->ping_exclude_caNv=excluding;
if (IsOptionMember("chrm",value) != MagickFalse)
mng_info->ping_exclude_cHRM=excluding;
if (IsOptionMember("date",value) != MagickFalse)
mng_info->ping_exclude_date=excluding;
if (IsOptionMember("exif",value) != MagickFalse)
{
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
}
if (IsOptionMember("gama",value) != MagickFalse)
mng_info->ping_exclude_gAMA=excluding;
if (IsOptionMember("iccp",value) != MagickFalse)
mng_info->ping_exclude_iCCP=excluding;
#if 0
if (IsOptionMember("itxt",value) != MagickFalse)
mng_info->ping_exclude_iTXt=excluding;
#endif
if (IsOptionMember("offs",value) != MagickFalse)
mng_info->ping_exclude_oFFs=excluding;
if (IsOptionMember("phys",value) != MagickFalse)
mng_info->ping_exclude_pHYs=excluding;
if (IsOptionMember("srgb",value) != MagickFalse)
mng_info->ping_exclude_sRGB=excluding;
if (IsOptionMember("text",value) != MagickFalse)
mng_info->ping_exclude_tEXt=excluding;
if (IsOptionMember("time",value) != MagickFalse)
mng_info->ping_exclude_tIME=excluding;
if (IsOptionMember("trns",value) != MagickFalse)
mng_info->ping_exclude_tRNS=excluding;
if (IsOptionMember("vpag",value) != MagickFalse)
mng_info->ping_exclude_vpAg=excluding;
if (IsOptionMember("zccp",value) != MagickFalse)
mng_info->ping_exclude_zCCP=excluding;
if (IsOptionMember("ztxt",value) != MagickFalse)
mng_info->ping_exclude_zTXt=excluding;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Chunks to be excluded from the output png:");
if (mng_info->ping_exclude_bKGD != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" bKGD");
if (mng_info->ping_exclude_caNv != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" caNv");
if (mng_info->ping_exclude_cHRM != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" cHRM");
if (mng_info->ping_exclude_date != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" date");
if (mng_info->ping_exclude_EXIF != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" EXIF");
if (mng_info->ping_exclude_eXIf != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" eXIf");
if (mng_info->ping_exclude_gAMA != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" gAMA");
if (mng_info->ping_exclude_iCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iCCP");
#if 0
if (mng_info->ping_exclude_iTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iTXt");
#endif
if (mng_info->ping_exclude_oFFs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" oFFs");
if (mng_info->ping_exclude_pHYs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pHYs");
if (mng_info->ping_exclude_sRGB != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" sRGB");
if (mng_info->ping_exclude_tEXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tEXt");
if (mng_info->ping_exclude_tIME != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tIME");
if (mng_info->ping_exclude_tRNS != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS");
if (mng_info->ping_exclude_vpAg != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" vpAg");
if (mng_info->ping_exclude_zCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zCCP");
if (mng_info->ping_exclude_zTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zTXt");
}
mng_info->need_blob = MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image);
(void) CloseBlob(image);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()");
return(status);
}
#if defined(JNG_SUPPORTED)
/* Write one JNG image */
static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info,Image *image)
{
Image
*jpeg_image;
ImageInfo
*jpeg_image_info;
int
unique_filenames;
MagickBooleanType
logging,
status;
size_t
length;
unsigned char
*blob,
chunk[80],
*p;
unsigned int
jng_alpha_compression_method,
jng_alpha_sample_depth,
jng_color_type,
transparent;
size_t
jng_alpha_quality,
jng_quality;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOneJNGImage()");
blob=(unsigned char *) NULL;
jpeg_image=(Image *) NULL;
jpeg_image_info=(ImageInfo *) NULL;
length=0;
unique_filenames=0;
status=MagickTrue;
transparent=image_info->type==GrayscaleMatteType ||
image_info->type==TrueColorMatteType || image->matte != MagickFalse;
jng_alpha_sample_depth = 0;
jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000;
jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0;
jng_alpha_quality=image_info->quality == 0UL ? 75UL :
image_info->quality;
if (jng_alpha_quality >= 1000)
jng_alpha_quality /= 1000;
if (transparent != 0)
{
jng_color_type=14;
/* Create JPEG blob, image, and image_info */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info for opacity.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
status=SeparateImageChannel(jpeg_image,OpacityChannel);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=NegateImage(jpeg_image,MagickFalse);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
jpeg_image->matte=MagickFalse;
jpeg_image_info->type=GrayscaleType;
jpeg_image->quality=jng_alpha_quality;
(void) SetImageType(jpeg_image,GrayscaleType);
(void) AcquireUniqueFilename(jpeg_image->filename);
unique_filenames++;
(void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,
"%s",jpeg_image->filename);
}
else
{
jng_alpha_compression_method=0;
jng_color_type=10;
jng_alpha_sample_depth=0;
}
/* To do: check bit depth of PNG alpha channel */
/* Check if image is grayscale. */
if (image_info->type != TrueColorMatteType && image_info->type !=
TrueColorType && SetImageGray(image,&image->exception))
jng_color_type-=2;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Quality = %d",(int) jng_quality);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Color Type = %d",jng_color_type);
if (transparent != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Compression = %d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Depth = %d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Quality = %d",(int) jng_alpha_quality);
}
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
const char
*value;
/* Encode opacity as a grayscale PNG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating PNG blob for alpha.");
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
length=0;
(void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent);
jpeg_image_info->interlace=NoInterlace;
/* Exclude all ancillary chunks */
(void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all");
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,
&image->exception);
/* Retrieve sample depth used */
value=GetImageProperty(jpeg_image,"png:bit-depth-written");
if (value != (char *) NULL)
jng_alpha_sample_depth= (unsigned int) value[0];
}
else
{
/* Encode opacity as a grayscale JPEG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating JPEG blob for alpha.");
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
jpeg_image_info->interlace=NoInterlace;
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,
&image->exception);
jng_alpha_sample_depth=8;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
}
/* Destroy JPEG image and image_info */
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
unique_filenames--;
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
}
/* Write JHDR chunk */
(void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */
PNGType(chunk,mng_JHDR);
LogPNGChunk(logging,mng_JHDR,16L);
PNGLong(chunk+4,(png_uint_32) image->columns);
PNGLong(chunk+8,(png_uint_32) image->rows);
chunk[12]=jng_color_type;
chunk[13]=8; /* sample depth */
chunk[14]=8; /*jng_image_compression_method */
chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8);
chunk[16]=jng_alpha_sample_depth;
chunk[17]=jng_alpha_compression_method;
chunk[18]=0; /*jng_alpha_filter_method */
chunk[19]=0; /*jng_alpha_interlace_method */
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG width:%15lu",(unsigned long) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG height:%14lu",(unsigned long) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG color type:%10d",jng_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG sample depth:%8d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG compression:%9d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG interlace:%11d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha depth:%9d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha compression:%3d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha filter:%8d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha interlace:%5d",0);
}
/* Write any JNG-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging);
/*
Write leading ancillary chunks
*/
if (transparent != 0)
{
/*
Write JNG bKGD chunk
*/
unsigned char
blue,
green,
red;
ssize_t
num_bytes;
if (jng_color_type == 8 || jng_color_type == 12)
num_bytes=6L;
else
num_bytes=10L;
(void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L));
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L));
red=ScaleQuantumToChar(image->background_color.red);
green=ScaleQuantumToChar(image->background_color.green);
blue=ScaleQuantumToChar(image->background_color.blue);
*(chunk+4)=0;
*(chunk+5)=red;
*(chunk+6)=0;
*(chunk+7)=green;
*(chunk+8)=0;
*(chunk+9)=blue;
(void) WriteBlob(image,(size_t) num_bytes,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes));
}
if ((image->colorspace == sRGBColorspace || image->rendering_intent))
{
/*
Write JNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
if (image->gamma != 0.0)
{
/*
Write JNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
}
if ((mng_info->equal_chrms == MagickFalse) &&
(image->chromaticity.red_primary.x != 0.0))
{
PrimaryInfo
primary;
/*
Write JNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
}
}
if (image->x_resolution && image->y_resolution && !mng_info->equal_physs)
{
/*
Write JNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5));
PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.x || image->page.y))
{
/*
Write JNG oFFs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_oFFs);
LogPNGChunk(logging,mng_oFFs,9L);
PNGsLong(chunk+4,(ssize_t) (image->page.x));
PNGsLong(chunk+8,(ssize_t) (image->page.y));
chunk[12]=0;
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.width || image->page.height))
{
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
register ssize_t
i;
size_t
len;
/* Write IDAT chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write IDAT chunks from blob, length=%.20g.",(double)
length);
/* Copy IDAT chunks */
len=0;
p=blob+8;
for (i=8; i<(ssize_t) length; i+=len+12)
{
len=(size_t) (*p) << 24;
len|=(size_t) (*(p+1)) << 16;
len|=(size_t) (*(p+2)) << 8;
len|=(size_t) (*(p+3));
p+=4;
if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */
{
/* Found an IDAT chunk. */
(void) WriteBlobMSBULong(image,len);
LogPNGChunk(logging,mng_IDAT,len);
(void) WriteBlob(image,len+4,p);
(void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4));
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping %c%c%c%c chunk, length=%.20g.",
*(p),*(p+1),*(p+2),*(p+3),(double) len);
}
p+=(8+len);
}
}
else if (length != 0)
{
/* Write JDAA chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAA chunk, length=%.20g.",(double) length);
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAA);
LogPNGChunk(logging,mng_JDAA,length);
/* Write JDAT chunk(s) data */
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,
(uInt) length));
}
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/* Encode image as a JPEG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
(void) AcquireUniqueFilename(jpeg_image->filename);
unique_filenames++;
(void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s",
jpeg_image->filename);
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns,
(double) jpeg_image->rows);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (jng_color_type == 8 || jng_color_type == 12)
jpeg_image_info->type=GrayscaleType;
jpeg_image_info->quality=jng_quality;
jpeg_image->quality=jng_quality;
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating blob.");
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAT chunk, length=%.20g.",(double) length);
}
/* Write JDAT chunk(s) */
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAT);
LogPNGChunk(logging,mng_JDAT,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length));
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
unique_filenames--;
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
blob=(unsigned char *) RelinquishMagickMemory(blob);
/* Write any JNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging);
/* Write IEND chunk */
(void) WriteBlobMSBULong(image,0L);
PNGType(chunk,mng_IEND);
LogPNGChunk(logging,mng_IEND,0);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJNGImage() writes a JPEG Network Graphics (JNG) image file.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteJNGImage method is:
%
% MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
(void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n");
status=WriteOneJNGImage(mng_info,image_info,image);
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
(void) CatchImageException(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteJNGImage()");
return(status);
}
#endif
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
{
const char
*option;
Image
*next_image;
MagickBooleanType
status;
volatile MagickBooleanType
logging;
MngInfo
*mng_info;
int
image_count,
need_iterations,
need_matte;
volatile int
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
need_local_plte,
#endif
all_images_are_gray,
need_defi,
use_global_plte;
register ssize_t
i;
unsigned char
chunk[800];
volatile unsigned int
write_jng,
write_mng;
volatile size_t
scene;
size_t
final_delay=0,
initial_delay;
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
write_mng=LocaleCompare(image_info->magick,"MNG") == 0;
/*
* See if user has requested a specific PNG subformat to be used
* for all of the PNGs in the MNG being written, e.g.,
*
* convert *.png png8:animation.mng
*
* To do: check -define png:bit_depth and png:color_type as well,
* or perhaps use mng:bit_depth and mng:color_type instead for
* global settings.
*/
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
write_jng=MagickFalse;
if (image_info->compression == JPEGCompression)
write_jng=MagickTrue;
mng_info->adjoin=image_info->adjoin &&
(GetNextImageInList(image) != (Image *) NULL) && write_mng;
if (logging != MagickFalse)
{
/* Log some info about the input */
Image
*p;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Checking input image(s)\n"
" Image_info depth: %.20g, Type: %d",
(double) image_info->depth, image_info->type);
scene=0;
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scene: %.20g\n, Image depth: %.20g",
(double) scene++, (double) p->depth);
if (p->matte)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: True");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: False");
if (p->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: PseudoClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: DirectClass");
if (p->colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) p->colors);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: unspecified");
if (mng_info->adjoin == MagickFalse)
break;
}
}
use_global_plte=MagickFalse;
all_images_are_gray=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_defi=MagickFalse;
need_matte=MagickFalse;
mng_info->framing_mode=1;
mng_info->old_framing_mode=1;
if (write_mng)
if (image_info->page != (char *) NULL)
{
/*
Determine image bounding box.
*/
SetGeometry(image,&mng_info->page);
(void) ParseMetaGeometry(image_info->page,&mng_info->page.x,
&mng_info->page.y,&mng_info->page.width,&mng_info->page.height);
}
if (write_mng)
{
unsigned int
need_geom;
unsigned short
red,
green,
blue;
mng_info->page=image->page;
need_geom=MagickTrue;
if (mng_info->page.width || mng_info->page.height)
need_geom=MagickFalse;
/*
Check all the scenes.
*/
initial_delay=image->delay;
need_iterations=MagickFalse;
mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0;
mng_info->equal_physs=MagickTrue,
mng_info->equal_gammas=MagickTrue;
mng_info->equal_srgbs=MagickTrue;
mng_info->equal_backgrounds=MagickTrue;
image_count=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
all_images_are_gray=MagickTrue;
mng_info->equal_palettes=MagickFalse;
need_local_plte=MagickFalse;
#endif
for (next_image=image; next_image != (Image *) NULL; )
{
if (need_geom)
{
if ((next_image->columns+next_image->page.x) > mng_info->page.width)
mng_info->page.width=next_image->columns+next_image->page.x;
if ((next_image->rows+next_image->page.y) > mng_info->page.height)
mng_info->page.height=next_image->rows+next_image->page.y;
}
if (next_image->page.x || next_image->page.y)
need_defi=MagickTrue;
if (next_image->matte)
need_matte=MagickTrue;
if ((int) next_image->dispose >= BackgroundDispose)
if (next_image->matte || next_image->page.x || next_image->page.y ||
((next_image->columns < mng_info->page.width) &&
(next_image->rows < mng_info->page.height)))
mng_info->need_fram=MagickTrue;
if (next_image->iterations)
need_iterations=MagickTrue;
final_delay=next_image->delay;
if (final_delay != initial_delay || final_delay > 1UL*
next_image->ticks_per_second)
mng_info->need_fram=1;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
check for global palette possibility.
*/
if (image->matte != MagickFalse)
need_local_plte=MagickTrue;
if (need_local_plte == 0)
{
if (SetImageGray(image,&image->exception) == MagickFalse)
all_images_are_gray=MagickFalse;
mng_info->equal_palettes=PalettesAreEqual(image,next_image);
if (use_global_plte == 0)
use_global_plte=mng_info->equal_palettes;
need_local_plte=!mng_info->equal_palettes;
}
#endif
if (GetNextImageInList(next_image) != (Image *) NULL)
{
if (next_image->background_color.red !=
next_image->next->background_color.red ||
next_image->background_color.green !=
next_image->next->background_color.green ||
next_image->background_color.blue !=
next_image->next->background_color.blue)
mng_info->equal_backgrounds=MagickFalse;
if (next_image->gamma != next_image->next->gamma)
mng_info->equal_gammas=MagickFalse;
if (next_image->rendering_intent !=
next_image->next->rendering_intent)
mng_info->equal_srgbs=MagickFalse;
if ((next_image->units != next_image->next->units) ||
(next_image->x_resolution != next_image->next->x_resolution) ||
(next_image->y_resolution != next_image->next->y_resolution))
mng_info->equal_physs=MagickFalse;
if (mng_info->equal_chrms)
{
if (next_image->chromaticity.red_primary.x !=
next_image->next->chromaticity.red_primary.x ||
next_image->chromaticity.red_primary.y !=
next_image->next->chromaticity.red_primary.y ||
next_image->chromaticity.green_primary.x !=
next_image->next->chromaticity.green_primary.x ||
next_image->chromaticity.green_primary.y !=
next_image->next->chromaticity.green_primary.y ||
next_image->chromaticity.blue_primary.x !=
next_image->next->chromaticity.blue_primary.x ||
next_image->chromaticity.blue_primary.y !=
next_image->next->chromaticity.blue_primary.y ||
next_image->chromaticity.white_point.x !=
next_image->next->chromaticity.white_point.x ||
next_image->chromaticity.white_point.y !=
next_image->next->chromaticity.white_point.y)
mng_info->equal_chrms=MagickFalse;
}
}
image_count++;
next_image=GetNextImageInList(next_image);
}
if (image_count < 2)
{
mng_info->equal_backgrounds=MagickFalse;
mng_info->equal_chrms=MagickFalse;
mng_info->equal_gammas=MagickFalse;
mng_info->equal_srgbs=MagickFalse;
mng_info->equal_physs=MagickFalse;
use_global_plte=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_iterations=MagickFalse;
}
if (mng_info->need_fram == MagickFalse)
{
/*
Only certain framing rates 100/n are exactly representable without
the FRAM chunk but we'll allow some slop in VLC files
*/
if (final_delay == 0)
{
if (need_iterations != MagickFalse)
{
/*
It's probably a GIF with loop; don't run it *too* fast.
*/
if (mng_info->adjoin)
{
final_delay=10;
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"input has zero delay between all frames; assuming",
" 10 cs `%s'","");
}
}
else
mng_info->ticks_per_second=0;
}
if (final_delay != 0)
mng_info->ticks_per_second=(png_uint_32)
(image->ticks_per_second/final_delay);
if (final_delay > 50)
mng_info->ticks_per_second=2;
if (final_delay > 75)
mng_info->ticks_per_second=1;
if (final_delay > 125)
mng_info->need_fram=MagickTrue;
if (need_defi && final_delay > 2 && (final_delay != 4) &&
(final_delay != 5) && (final_delay != 10) && (final_delay != 20) &&
(final_delay != 25) && (final_delay != 50) &&
(final_delay != (size_t) image->ticks_per_second))
mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */
}
if (mng_info->need_fram != MagickFalse)
mng_info->ticks_per_second=1UL*image->ticks_per_second;
/*
If pseudocolor, we should also check to see if all the
palettes are identical and write a global PLTE if they are.
../glennrp Feb 99.
*/
/*
Write the MNG version 1.0 signature and MHDR chunk.
*/
(void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n");
(void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */
PNGType(chunk,mng_MHDR);
LogPNGChunk(logging,mng_MHDR,28L);
PNGLong(chunk+4,(png_uint_32) mng_info->page.width);
PNGLong(chunk+8,(png_uint_32) mng_info->page.height);
PNGLong(chunk+12,mng_info->ticks_per_second);
PNGLong(chunk+16,0L); /* layer count=unknown */
PNGLong(chunk+20,0L); /* frame count=unknown */
PNGLong(chunk+24,0L); /* play time=unknown */
if (write_jng)
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,27L); /* simplicity=LC+JNG */
else
PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */
else
PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */
}
}
else
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,11L); /* simplicity=LC */
else
PNGLong(chunk+28,9L); /* simplicity=VLC */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */
else
PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */
}
}
(void) WriteBlob(image,32,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,32));
option=GetImageOption(image_info,"mng:need-cacheoff");
if (option != (const char *) NULL)
{
size_t
length;
/*
Write "nEED CACHEOFF" to turn playback caching off for streaming MNG.
*/
PNGType(chunk,mng_nEED);
length=CopyMagickString((char *) chunk+4,"CACHEOFF",20);
(void) WriteBlobMSBULong(image,(size_t) length);
LogPNGChunk(logging,mng_nEED,(size_t) length);
length+=4;
(void) WriteBlob(image,length,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length));
}
if ((GetPreviousImageInList(image) == (Image *) NULL) &&
(GetNextImageInList(image) != (Image *) NULL) &&
(image->iterations != 1))
{
/*
Write MNG TERM chunk
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_TERM);
LogPNGChunk(logging,mng_TERM,10L);
chunk[4]=3; /* repeat animation */
chunk[5]=0; /* show last frame when done */
PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
PNGLong(chunk+10,PNG_UINT_31_MAX);
else
PNGLong(chunk+10,(png_uint_32) image->iterations);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM delay: %.20g",(double) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM iterations: %.20g",(double) PNG_UINT_31_MAX);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image iterations: %.20g",(double) image->iterations);
}
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
}
/*
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if ((image->colorspace == sRGBColorspace || image->rendering_intent) &&
mng_info->equal_srgbs)
{
/*
Write MNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
mng_info->have_write_global_srgb=MagickTrue;
}
else
{
if (image->gamma && mng_info->equal_gammas)
{
/*
Write MNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
mng_info->have_write_global_gama=MagickTrue;
}
if (mng_info->equal_chrms)
{
PrimaryInfo
primary;
/*
Write MNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
mng_info->have_write_global_chrm=MagickTrue;
}
}
if (image->x_resolution && image->y_resolution && mng_info->equal_physs)
{
/*
Write MNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5));
PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
/*
Write MNG BACK chunk and global bKGD chunk, if the image is transparent
or does not cover the entire frame.
*/
if (write_mng && (image->matte || image->page.x > 0 ||
image->page.y > 0 || (image->page.width &&
(image->page.width+image->page.x < mng_info->page.width))
|| (image->page.height && (image->page.height+image->page.y
< mng_info->page.height))))
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_BACK);
LogPNGChunk(logging,mng_BACK,6L);
red=ScaleQuantumToShort(image->background_color.red);
green=ScaleQuantumToShort(image->background_color.green);
blue=ScaleQuantumToShort(image->background_color.blue);
PNGShort(chunk+4,red);
PNGShort(chunk+6,green);
PNGShort(chunk+8,blue);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
if (mng_info->equal_backgrounds)
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,6L);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
}
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if ((need_local_plte == MagickFalse) &&
(image->storage_class == PseudoClass) &&
(all_images_are_gray == MagickFalse))
{
size_t
data_length;
/*
Write MNG PLTE chunk
*/
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff;
chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff;
chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff;
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
#endif
}
scene=0;
mng_info->delay=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
mng_info->equal_palettes=MagickFalse;
#endif
do
{
if (mng_info->adjoin)
{
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
If we aren't using a global palette for the entire MNG, check to
see if we can use one for two or more consecutive images.
*/
if (need_local_plte && use_global_plte && !all_images_are_gray)
{
if (mng_info->IsPalette)
{
/*
When equal_palettes is true, this image has the same palette
as the previous PseudoClass image
*/
mng_info->have_write_global_plte=mng_info->equal_palettes;
mng_info->equal_palettes=PalettesAreEqual(image,image->next);
if (mng_info->equal_palettes && !mng_info->have_write_global_plte)
{
/*
Write MNG PLTE chunk
*/
size_t
data_length;
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red);
chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green);
chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue);
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,
(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
}
else
mng_info->have_write_global_plte=MagickFalse;
}
#endif
if (need_defi)
{
ssize_t
previous_x,
previous_y;
if (scene != 0)
{
previous_x=mng_info->page.x;
previous_y=mng_info->page.y;
}
else
{
previous_x=0;
previous_y=0;
}
mng_info->page=image->page;
if ((mng_info->page.x != previous_x) ||
(mng_info->page.y != previous_y))
{
(void) WriteBlobMSBULong(image,12L); /* data length=12 */
PNGType(chunk,mng_DEFI);
LogPNGChunk(logging,mng_DEFI,12L);
chunk[4]=0; /* object 0 MSB */
chunk[5]=0; /* object 0 LSB */
chunk[6]=0; /* visible */
chunk[7]=0; /* abstract */
PNGLong(chunk+8,(png_uint_32) mng_info->page.x);
PNGLong(chunk+12,(png_uint_32) mng_info->page.y);
(void) WriteBlob(image,16,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,16));
}
}
}
mng_info->write_mng=write_mng;
if ((int) image->dispose >= 3)
mng_info->framing_mode=3;
if (mng_info->need_fram && mng_info->adjoin &&
((image->delay != mng_info->delay) ||
(mng_info->framing_mode != mng_info->old_framing_mode)))
{
if (image->delay == mng_info->delay)
{
/*
Write a MNG FRAM chunk with the new framing mode.
*/
(void) WriteBlobMSBULong(image,1L); /* data length=1 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,1L);
chunk[4]=(unsigned char) mng_info->framing_mode;
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
/*
Write a MNG FRAM chunk with the delay.
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,10L);
chunk[4]=(unsigned char) mng_info->framing_mode;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=2; /* flag for changing default delay */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=0; /* flag for changing frame clipping */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32)
((mng_info->ticks_per_second*
image->delay)/MagickMax(image->ticks_per_second,1)));
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
mng_info->delay=(png_uint_32) image->delay;
}
mng_info->old_framing_mode=mng_info->framing_mode;
}
#if defined(JNG_SUPPORTED)
if (image_info->compression == JPEGCompression)
{
ImageInfo
*write_info;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing JNG object.");
/* To do: specify the desired alpha compression method. */
write_info=CloneImageInfo(image_info);
write_info->compression=UndefinedCompression;
status=WriteOneJNGImage(mng_info,write_info,image);
write_info=DestroyImageInfo(write_info);
}
else
#endif
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG object.");
mng_info->need_blob = MagickFalse;
mng_info->ping_preserve_colormap = MagickFalse;
/* We don't want any ancillary chunks written */
mng_info->ping_exclude_bKGD=MagickTrue;
mng_info->ping_exclude_caNv=MagickTrue;
mng_info->ping_exclude_cHRM=MagickTrue;
mng_info->ping_exclude_date=MagickTrue;
mng_info->ping_exclude_EXIF=MagickTrue;
mng_info->ping_exclude_eXIf=MagickTrue;
mng_info->ping_exclude_gAMA=MagickTrue;
mng_info->ping_exclude_iCCP=MagickTrue;
/* mng_info->ping_exclude_iTXt=MagickTrue; */
mng_info->ping_exclude_oFFs=MagickTrue;
mng_info->ping_exclude_pHYs=MagickTrue;
mng_info->ping_exclude_sRGB=MagickTrue;
mng_info->ping_exclude_tEXt=MagickTrue;
mng_info->ping_exclude_tRNS=MagickTrue;
mng_info->ping_exclude_vpAg=MagickTrue;
mng_info->ping_exclude_zCCP=MagickTrue;
mng_info->ping_exclude_zTXt=MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image);
}
if (status == MagickFalse)
{
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
return(MagickFalse);
}
(void) CatchImageException(image);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (mng_info->adjoin);
if (write_mng)
{
while (GetPreviousImageInList(image) != (Image *) NULL)
image=GetPreviousImageInList(image);
/*
Write the MEND chunk.
*/
(void) WriteBlobMSBULong(image,0x00000000L);
PNGType(chunk,mng_MEND);
LogPNGChunk(logging,mng_MEND,0L);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
}
/*
Relinquish resources.
*/
(void) CloseBlob(image);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()");
return(MagickTrue);
}
#else /* PNG_LIBPNG_VER > 10011 */
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
{
(void) image;
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
ThrowBinaryException(CoderError,"PNG library is too old",
image_info->filename);
}
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
{
return(WritePNGImage(image_info,image));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
| ./CrossVul/dataset_final_sorted/CWE-770/c/good_2614_0 |
crossvul-cpp_data_bad_3143_1 | /* $OpenBSD: server_file.c,v 1.63 2017/01/30 09:54:41 reyk Exp $ */
/*
* Copyright (c) 2006 - 2015 Reyk Floeter <reyk@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* 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.
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <limits.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <time.h>
#include <event.h>
#include "httpd.h"
#include "http.h"
#define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
#define MAX_RANGES 4
struct range {
off_t start;
off_t end;
};
int server_file_access(struct httpd *, struct client *,
char *, size_t);
int server_file_request(struct httpd *, struct client *,
char *, struct stat *);
int server_partial_file_request(struct httpd *, struct client *,
char *, struct stat *, char *);
int server_file_index(struct httpd *, struct client *,
struct stat *);
int server_file_modified_since(struct http_descriptor *,
struct stat *);
int server_file_method(struct client *);
int parse_range_spec(char *, size_t, struct range *);
struct range *parse_range(char *, size_t, int *);
int buffer_add_range(int, struct evbuffer *, struct range *);
int
server_file_access(struct httpd *env, struct client *clt,
char *path, size_t len)
{
struct http_descriptor *desc = clt->clt_descreq;
struct server_config *srv_conf = clt->clt_srv_conf;
struct stat st;
struct kv *r, key;
char *newpath, *encodedpath;
int ret;
errno = 0;
if (access(path, R_OK) == -1) {
goto fail;
} else if (stat(path, &st) == -1) {
goto fail;
} else if (S_ISDIR(st.st_mode)) {
/* Deny access if directory indexing is disabled */
if (srv_conf->flags & SRVFLAG_NO_INDEX) {
errno = EACCES;
goto fail;
}
if (desc->http_path_alias != NULL) {
/* Recursion - the index "file" is a directory? */
errno = EINVAL;
goto fail;
}
/* Redirect to path with trailing "/" */
if (path[strlen(path) - 1] != '/') {
if ((encodedpath = url_encode(desc->http_path)) == NULL)
return (500);
if (asprintf(&newpath, "http%s://%s%s/",
srv_conf->flags & SRVFLAG_TLS ? "s" : "",
desc->http_host, encodedpath) == -1) {
free(encodedpath);
return (500);
}
free(encodedpath);
/* Path alias will be used for the redirection */
desc->http_path_alias = newpath;
/* Indicate that the file has been moved */
return (301);
}
/* Append the default index file to the location */
if (asprintf(&newpath, "%s%s", desc->http_path,
srv_conf->index) == -1)
return (500);
desc->http_path_alias = newpath;
if (server_getlocation(clt, newpath) != srv_conf) {
/* The location has changed */
return (server_file(env, clt));
}
/* Otherwise append the default index file to the path */
if (strlcat(path, srv_conf->index, len) >= len) {
errno = EACCES;
goto fail;
}
ret = server_file_access(env, clt, path, len);
if (ret == 404) {
/*
* Index file not found; fail if auto-indexing is
* not enabled, otherwise return success but
* indicate directory with S_ISDIR of the previous
* stat.
*/
if ((srv_conf->flags & SRVFLAG_AUTO_INDEX) == 0) {
errno = EACCES;
goto fail;
}
return (server_file_index(env, clt, &st));
}
return (ret);
} else if (!S_ISREG(st.st_mode)) {
/* Don't follow symlinks and ignore special files */
errno = EACCES;
goto fail;
}
key.kv_key = "Range";
r = kv_find(&desc->http_headers, &key);
if (r != NULL)
return (server_partial_file_request(env, clt, path, &st,
r->kv_value));
else
return (server_file_request(env, clt, path, &st));
fail:
switch (errno) {
case ENOENT:
case ENOTDIR:
return (404);
case EACCES:
return (403);
default:
return (500);
}
/* NOTREACHED */
}
int
server_file(struct httpd *env, struct client *clt)
{
struct http_descriptor *desc = clt->clt_descreq;
struct server_config *srv_conf = clt->clt_srv_conf;
char path[PATH_MAX];
const char *stripped, *errstr = NULL;
int ret = 500;
if (srv_conf->flags & SRVFLAG_FCGI)
return (server_fcgi(env, clt));
/* Request path is already canonicalized */
stripped = server_root_strip(
desc->http_path_alias != NULL ?
desc->http_path_alias : desc->http_path,
srv_conf->strip);
if ((size_t)snprintf(path, sizeof(path), "%s%s",
srv_conf->root, stripped) >= sizeof(path)) {
errstr = desc->http_path;
goto abort;
}
/* Returns HTTP status code on error */
if ((ret = server_file_access(env, clt, path, sizeof(path))) > 0) {
errstr = desc->http_path_alias != NULL ?
desc->http_path_alias : desc->http_path;
goto abort;
}
return (ret);
abort:
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, ret, errstr);
return (-1);
}
int
server_file_method(struct client *clt)
{
struct http_descriptor *desc = clt->clt_descreq;
switch (desc->http_method) {
case HTTP_METHOD_GET:
case HTTP_METHOD_HEAD:
return (0);
default:
/* Other methods are not allowed */
errno = EACCES;
return (405);
}
/* NOTREACHED */
}
int
server_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct media_type *media;
const char *errstr = NULL;
int fd = -1, ret, code = 500;
if ((ret = server_file_method(clt)) != 0) {
code = ret;
goto abort;
}
if ((ret = server_file_modified_since(clt->clt_descreq, st)) != -1)
return (ret);
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
ret = server_response_http(clt, 200, media, st->st_size,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
close(fd);
goto done;
default:
break;
}
clt->clt_fd = fd;
if (clt->clt_srvbev != NULL)
bufferevent_free(clt->clt_srvbev);
clt->clt_srvbev_throttled = 0;
clt->clt_srvbev = bufferevent_new(clt->clt_fd, server_read,
server_write, server_file_error, clt);
if (clt->clt_srvbev == NULL) {
errstr = "failed to allocate file buffer event";
goto fail;
}
/* Adjust read watermark to the socket output buffer size */
bufferevent_setwatermark(clt->clt_srvbev, EV_READ, 0,
clt->clt_sndbufsiz);
bufferevent_settimeout(clt->clt_srvbev,
srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
bufferevent_enable(clt->clt_srvbev, EV_READ);
bufferevent_disable(clt->clt_bev, EV_READ);
done:
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
int
server_partial_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st, char *range_str)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct http_descriptor *resp = clt->clt_descresp;
struct http_descriptor *desc = clt->clt_descreq;
struct media_type *media, multipart_media;
struct range *range;
struct evbuffer *evb = NULL;
size_t content_length;
int code = 500, fd = -1, i, nranges, ret;
uint32_t boundary;
char content_range[64];
const char *errstr = NULL;
/* Ignore range request for methods other than GET */
if (desc->http_method != HTTP_METHOD_GET)
return server_file_request(env, clt, path, st);
if ((range = parse_range(range_str, st->st_size, &nranges)) == NULL) {
code = 416;
(void)snprintf(content_range, sizeof(content_range),
"bytes */%lld", st->st_size);
errstr = content_range;
goto abort;
}
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
if ((evb = evbuffer_new()) == NULL) {
errstr = "failed to allocate file buffer";
goto abort;
}
if (nranges == 1) {
(void)snprintf(content_range, sizeof(content_range),
"bytes %lld-%lld/%lld", range->start, range->end,
st->st_size);
if (kv_add(&resp->http_headers, "Content-Range",
content_range) == NULL)
goto abort;
content_length = range->end - range->start + 1;
if (buffer_add_range(fd, evb, range) == 0)
goto abort;
} else {
content_length = 0;
boundary = arc4random();
/* Generate a multipart payload of byteranges */
while (nranges--) {
if ((i = evbuffer_add_printf(evb, "\r\n--%ud\r\n",
boundary)) == -1)
goto abort;
content_length += i;
if ((i = evbuffer_add_printf(evb,
"Content-Type: %s/%s\r\n",
media->media_type, media->media_subtype)) == -1)
goto abort;
content_length += i;
if ((i = evbuffer_add_printf(evb,
"Content-Range: bytes %lld-%lld/%lld\r\n\r\n",
range->start, range->end, st->st_size)) == -1)
goto abort;
content_length += i;
if (buffer_add_range(fd, evb, range) == 0)
goto abort;
content_length += range->end - range->start + 1;
range++;
}
if ((i = evbuffer_add_printf(evb, "\r\n--%ud--\r\n",
boundary)) == -1)
goto abort;
content_length += i;
/* prepare multipart/byteranges media type */
(void)strlcpy(multipart_media.media_type, "multipart",
sizeof(multipart_media.media_type));
(void)snprintf(multipart_media.media_subtype,
sizeof(multipart_media.media_subtype),
"byteranges; boundary=%ud", boundary);
media = &multipart_media;
}
close(fd);
fd = -1;
ret = server_response_http(clt, 206, media, content_length,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
goto done;
default:
break;
}
if (server_bufferevent_write_buffer(clt, evb) == -1)
goto fail;
bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
if (clt->clt_persist)
clt->clt_toread = TOREAD_HTTP_HEADER;
else
clt->clt_toread = TOREAD_HTTP_NONE;
clt->clt_done = 0;
done:
evbuffer_free(evb);
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (evb != NULL)
evbuffer_free(evb);
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
int
server_file_index(struct httpd *env, struct client *clt, struct stat *st)
{
char path[PATH_MAX];
char tmstr[21];
struct http_descriptor *desc = clt->clt_descreq;
struct server_config *srv_conf = clt->clt_srv_conf;
struct dirent **namelist, *dp;
int namesize, i, ret, fd = -1, namewidth, skip;
int code = 500;
struct evbuffer *evb = NULL;
struct media_type *media;
const char *stripped, *style;
char *escapeduri, *escapedhtml, *escapedpath;
struct tm tm;
time_t t, dir_mtime;
if ((ret = server_file_method(clt)) != 0) {
code = ret;
goto abort;
}
/* Request path is already canonicalized */
stripped = server_root_strip(desc->http_path, srv_conf->strip);
if ((size_t)snprintf(path, sizeof(path), "%s%s",
srv_conf->root, stripped) >= sizeof(path))
goto abort;
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
/* Save last modification time */
dir_mtime = MINIMUM(time(NULL), st->st_mtim.tv_sec);
if ((evb = evbuffer_new()) == NULL)
goto abort;
if ((namesize = scandir(path, &namelist, NULL, alphasort)) == -1)
goto abort;
/* Indicate failure but continue going through the list */
skip = 0;
if ((escapedpath = escape_html(desc->http_path)) == NULL)
goto fail;
/* A CSS stylesheet allows minimal customization by the user */
style = "body { background-color: white; color: black; font-family: "
"sans-serif; }\nhr { border: 0; border-bottom: 1px dashed; }\n";
/* Generate simple HTML index document */
if (evbuffer_add_printf(evb,
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; "
"charset=utf-8\"/>\n"
"<title>Index of %s</title>\n"
"<style type=\"text/css\"><!--\n%s\n--></style>\n"
"</head>\n"
"<body>\n"
"<h1>Index of %s</h1>\n"
"<hr>\n<pre>\n",
escapedpath, style, escapedpath) == -1)
skip = 1;
free(escapedpath);
for (i = 0; i < namesize; i++) {
dp = namelist[i];
if (skip ||
fstatat(fd, dp->d_name, st, 0) == -1) {
free(dp);
continue;
}
t = st->st_mtime;
localtime_r(&t, &tm);
strftime(tmstr, sizeof(tmstr), "%d-%h-%Y %R", &tm);
namewidth = 51 - strlen(dp->d_name);
if ((escapeduri = url_encode(dp->d_name)) == NULL)
goto fail;
if ((escapedhtml = escape_html(dp->d_name)) == NULL)
goto fail;
if (dp->d_name[0] == '.' &&
!(dp->d_name[1] == '.' && dp->d_name[2] == '\0')) {
/* ignore hidden files starting with a dot */
} else if (S_ISDIR(st->st_mode)) {
namewidth -= 1; /* trailing slash */
if (evbuffer_add_printf(evb,
"<a href=\"%s%s/\">%s/</a>%*s%s%20s\n",
strchr(escapeduri, ':') != NULL ? "./" : "",
escapeduri, escapedhtml,
MAXIMUM(namewidth, 0), " ", tmstr, "-") == -1)
skip = 1;
} else if (S_ISREG(st->st_mode)) {
if (evbuffer_add_printf(evb,
"<a href=\"%s%s\">%s</a>%*s%s%20llu\n",
strchr(escapeduri, ':') != NULL ? "./" : "",
escapeduri, escapedhtml,
MAXIMUM(namewidth, 0), " ",
tmstr, st->st_size) == -1)
skip = 1;
}
free(escapeduri);
free(escapedhtml);
free(dp);
}
free(namelist);
if (skip ||
evbuffer_add_printf(evb,
"</pre>\n<hr>\n</body>\n</html>\n") == -1)
goto abort;
close(fd);
fd = -1;
media = media_find_config(env, srv_conf, "index.html");
ret = server_response_http(clt, 200, media, EVBUFFER_LENGTH(evb),
dir_mtime);
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
evbuffer_free(evb);
goto done;
default:
break;
}
if (server_bufferevent_write_buffer(clt, evb) == -1)
goto fail;
evbuffer_free(evb);
evb = NULL;
bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
if (clt->clt_persist)
clt->clt_toread = TOREAD_HTTP_HEADER;
else
clt->clt_toread = TOREAD_HTTP_NONE;
clt->clt_done = 0;
done:
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (fd != -1)
close(fd);
if (evb != NULL)
evbuffer_free(evb);
server_abort_http(clt, code, desc->http_path);
return (-1);
}
void
server_file_error(struct bufferevent *bev, short error, void *arg)
{
struct client *clt = arg;
struct evbuffer *dst;
if (error & EVBUFFER_TIMEOUT) {
server_close(clt, "buffer event timeout");
return;
}
if (error & EVBUFFER_ERROR) {
if (errno == EFBIG) {
bufferevent_enable(bev, EV_READ);
return;
}
server_close(clt, "buffer event error");
return;
}
if (error & (EVBUFFER_READ|EVBUFFER_WRITE|EVBUFFER_EOF)) {
bufferevent_disable(bev, EV_READ|EV_WRITE);
clt->clt_done = 1;
if (clt->clt_persist) {
/* Close input file and wait for next HTTP request */
if (clt->clt_fd != -1)
close(clt->clt_fd);
clt->clt_fd = -1;
clt->clt_toread = TOREAD_HTTP_HEADER;
server_reset_http(clt);
bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
return;
}
dst = EVBUFFER_OUTPUT(clt->clt_bev);
if (EVBUFFER_LENGTH(dst)) {
/* Finish writing all data first */
bufferevent_enable(clt->clt_bev, EV_WRITE);
return;
}
server_close(clt, "done");
return;
}
server_close(clt, "unknown event error");
return;
}
int
server_file_modified_since(struct http_descriptor *desc, struct stat *st)
{
struct kv key, *since;
struct tm tm;
key.kv_key = "If-Modified-Since";
if ((since = kv_find(&desc->http_headers, &key)) != NULL &&
since->kv_value != NULL) {
memset(&tm, 0, sizeof(struct tm));
/*
* Return "Not modified" if the file hasn't changed since
* the requested time.
*/
if (strptime(since->kv_value,
"%a, %d %h %Y %T %Z", &tm) != NULL &&
timegm(&tm) >= st->st_mtim.tv_sec)
return (304);
}
return (-1);
}
struct range *
parse_range(char *str, size_t file_sz, int *nranges)
{
static struct range ranges[MAX_RANGES];
int i = 0;
char *p, *q;
/* Extract range unit */
if ((p = strchr(str, '=')) == NULL)
return (NULL);
*p++ = '\0';
/* Check if it's a bytes range spec */
if (strcmp(str, "bytes") != 0)
return (NULL);
while ((q = strchr(p, ',')) != NULL) {
*q++ = '\0';
/* Extract start and end positions */
if (parse_range_spec(p, file_sz, &ranges[i]) == 0)
continue;
i++;
if (i == MAX_RANGES)
return (NULL);
p = q;
}
if (parse_range_spec(p, file_sz, &ranges[i]) != 0)
i++;
*nranges = i;
return (i ? ranges : NULL);
}
int
parse_range_spec(char *str, size_t size, struct range *r)
{
size_t start_str_len, end_str_len;
char *p, *start_str, *end_str;
const char *errstr;
if ((p = strchr(str, '-')) == NULL)
return (0);
*p++ = '\0';
start_str = str;
end_str = p;
start_str_len = strlen(start_str);
end_str_len = strlen(end_str);
/* Either 'start' or 'end' is optional but not both */
if ((start_str_len == 0) && (end_str_len == 0))
return (0);
if (end_str_len) {
r->end = strtonum(end_str, 0, LLONG_MAX, &errstr);
if (errstr)
return (0);
if ((size_t)r->end >= size)
r->end = size - 1;
} else
r->end = size - 1;
if (start_str_len) {
r->start = strtonum(start_str, 0, LLONG_MAX, &errstr);
if (errstr)
return (0);
if ((size_t)r->start >= size)
return (0);
} else {
r->start = size - r->end;
r->end = size - 1;
}
if (r->end < r->start)
return (0);
return (1);
}
int
buffer_add_range(int fd, struct evbuffer *evb, struct range *range)
{
char buf[BUFSIZ];
size_t n, range_sz;
ssize_t nread;
if (lseek(fd, range->start, SEEK_SET) == -1)
return (0);
range_sz = range->end - range->start + 1;
while (range_sz) {
n = MINIMUM(range_sz, sizeof(buf));
if ((nread = read(fd, buf, n)) == -1)
return (0);
evbuffer_add(evb, buf, nread);
range_sz -= nread;
}
return (1);
}
| ./CrossVul/dataset_final_sorted/CWE-770/c/bad_3143_1 |
crossvul-cpp_data_good_367_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-2018 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/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.
*/
if (bmp_info.ba_offset == 0)
start_position=TellBlob(image)-2;
bmp_info.ba_offset=0;
while (LocaleNCompare((char *) magick,"BA",2) == 0)
{
bmp_info.file_size=ReadBlobLSBLong(image);
bmp_info.ba_offset=ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
count=ReadBlob(image,2,magick);
if (count != 2)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c",
magick[0],magick[1]);
if ((count != 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 (((MagickSizeType) length/8) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
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-770/c/good_367_0 |
crossvul-cpp_data_good_4653_0 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Extensively modified by Motonori Shindo (mshindo@mshindo.net) for more
* complete PPP support.
*/
/* \summary: Point to Point Protocol (PPP) printer */
/*
* TODO:
* o resolve XXX as much as possible
* o MP support
* o BAP support
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#ifdef __bsdi__
#include <net/slcompress.h>
#include <net/if_ppp.h>
#endif
#include <stdlib.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ppp.h"
#include "chdlc.h"
#include "ethertype.h"
#include "oui.h"
/*
* The following constatns are defined by IANA. Please refer to
* http://www.isi.edu/in-notes/iana/assignments/ppp-numbers
* for the up-to-date information.
*/
/* Protocol Codes defined in ppp.h */
static const struct tok ppptype2str[] = {
{ PPP_IP, "IP" },
{ PPP_OSI, "OSI" },
{ PPP_NS, "NS" },
{ PPP_DECNET, "DECNET" },
{ PPP_APPLE, "APPLE" },
{ PPP_IPX, "IPX" },
{ PPP_VJC, "VJC IP" },
{ PPP_VJNC, "VJNC IP" },
{ PPP_BRPDU, "BRPDU" },
{ PPP_STII, "STII" },
{ PPP_VINES, "VINES" },
{ PPP_MPLS_UCAST, "MPLS" },
{ PPP_MPLS_MCAST, "MPLS" },
{ PPP_COMP, "Compressed"},
{ PPP_ML, "MLPPP"},
{ PPP_IPV6, "IP6"},
{ PPP_HELLO, "HELLO" },
{ PPP_LUXCOM, "LUXCOM" },
{ PPP_SNS, "SNS" },
{ PPP_IPCP, "IPCP" },
{ PPP_OSICP, "OSICP" },
{ PPP_NSCP, "NSCP" },
{ PPP_DECNETCP, "DECNETCP" },
{ PPP_APPLECP, "APPLECP" },
{ PPP_IPXCP, "IPXCP" },
{ PPP_STIICP, "STIICP" },
{ PPP_VINESCP, "VINESCP" },
{ PPP_IPV6CP, "IP6CP" },
{ PPP_MPLSCP, "MPLSCP" },
{ PPP_LCP, "LCP" },
{ PPP_PAP, "PAP" },
{ PPP_LQM, "LQM" },
{ PPP_CHAP, "CHAP" },
{ PPP_EAP, "EAP" },
{ PPP_SPAP, "SPAP" },
{ PPP_SPAP_OLD, "Old-SPAP" },
{ PPP_BACP, "BACP" },
{ PPP_BAP, "BAP" },
{ PPP_MPCP, "MLPPP-CP" },
{ PPP_CCP, "CCP" },
{ 0, NULL }
};
/* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */
#define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */
#define CPCODES_CONF_REQ 1 /* Configure-Request */
#define CPCODES_CONF_ACK 2 /* Configure-Ack */
#define CPCODES_CONF_NAK 3 /* Configure-Nak */
#define CPCODES_CONF_REJ 4 /* Configure-Reject */
#define CPCODES_TERM_REQ 5 /* Terminate-Request */
#define CPCODES_TERM_ACK 6 /* Terminate-Ack */
#define CPCODES_CODE_REJ 7 /* Code-Reject */
#define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */
#define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */
#define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */
#define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */
#define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */
#define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */
#define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */
#define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */
static const struct tok cpcodes[] = {
{CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */
{CPCODES_CONF_REQ, "Conf-Request"},
{CPCODES_CONF_ACK, "Conf-Ack"},
{CPCODES_CONF_NAK, "Conf-Nack"},
{CPCODES_CONF_REJ, "Conf-Reject"},
{CPCODES_TERM_REQ, "Term-Request"},
{CPCODES_TERM_ACK, "Term-Ack"},
{CPCODES_CODE_REJ, "Code-Reject"},
{CPCODES_PROT_REJ, "Prot-Reject"},
{CPCODES_ECHO_REQ, "Echo-Request"},
{CPCODES_ECHO_RPL, "Echo-Reply"},
{CPCODES_DISC_REQ, "Disc-Req"},
{CPCODES_ID, "Ident"}, /* RFC1570 */
{CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */
{CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */
{CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */
{0, NULL}
};
/* LCP Config Options */
#define LCPOPT_VEXT 0
#define LCPOPT_MRU 1
#define LCPOPT_ACCM 2
#define LCPOPT_AP 3
#define LCPOPT_QP 4
#define LCPOPT_MN 5
#define LCPOPT_DEP6 6
#define LCPOPT_PFC 7
#define LCPOPT_ACFC 8
#define LCPOPT_FCSALT 9
#define LCPOPT_SDP 10
#define LCPOPT_NUMMODE 11
#define LCPOPT_DEP12 12
#define LCPOPT_CBACK 13
#define LCPOPT_DEP14 14
#define LCPOPT_DEP15 15
#define LCPOPT_DEP16 16
#define LCPOPT_MLMRRU 17
#define LCPOPT_MLSSNHF 18
#define LCPOPT_MLED 19
#define LCPOPT_PROP 20
#define LCPOPT_DCEID 21
#define LCPOPT_MPP 22
#define LCPOPT_LD 23
#define LCPOPT_LCPAOPT 24
#define LCPOPT_COBS 25
#define LCPOPT_PE 26
#define LCPOPT_MLHF 27
#define LCPOPT_I18N 28
#define LCPOPT_SDLOS 29
#define LCPOPT_PPPMUX 30
#define LCPOPT_MIN LCPOPT_VEXT
#define LCPOPT_MAX LCPOPT_PPPMUX
static const char *lcpconfopts[] = {
"Vend-Ext", /* (0) */
"MRU", /* (1) */
"ACCM", /* (2) */
"Auth-Prot", /* (3) */
"Qual-Prot", /* (4) */
"Magic-Num", /* (5) */
"deprecated(6)", /* used to be a Quality Protocol */
"PFC", /* (7) */
"ACFC", /* (8) */
"FCS-Alt", /* (9) */
"SDP", /* (10) */
"Num-Mode", /* (11) */
"deprecated(12)", /* used to be a Multi-Link-Procedure*/
"Call-Back", /* (13) */
"deprecated(14)", /* used to be a Connect-Time */
"deprecated(15)", /* used to be a Compund-Frames */
"deprecated(16)", /* used to be a Nominal-Data-Encap */
"MRRU", /* (17) */
"12-Bit seq #", /* (18) */
"End-Disc", /* (19) */
"Proprietary", /* (20) */
"DCE-Id", /* (21) */
"MP+", /* (22) */
"Link-Disc", /* (23) */
"LCP-Auth-Opt", /* (24) */
"COBS", /* (25) */
"Prefix-elision", /* (26) */
"Multilink-header-Form",/* (27) */
"I18N", /* (28) */
"SDL-over-SONET/SDH", /* (29) */
"PPP-Muxing", /* (30) */
};
/* ECP - to be supported */
/* CCP Config Options */
#define CCPOPT_OUI 0 /* RFC1962 */
#define CCPOPT_PRED1 1 /* RFC1962 */
#define CCPOPT_PRED2 2 /* RFC1962 */
#define CCPOPT_PJUMP 3 /* RFC1962 */
/* 4-15 unassigned */
#define CCPOPT_HPPPC 16 /* RFC1962 */
#define CCPOPT_STACLZS 17 /* RFC1974 */
#define CCPOPT_MPPC 18 /* RFC2118 */
#define CCPOPT_GFZA 19 /* RFC1962 */
#define CCPOPT_V42BIS 20 /* RFC1962 */
#define CCPOPT_BSDCOMP 21 /* RFC1977 */
/* 22 unassigned */
#define CCPOPT_LZSDCP 23 /* RFC1967 */
#define CCPOPT_MVRCA 24 /* RFC1975 */
#define CCPOPT_DEC 25 /* RFC1976 */
#define CCPOPT_DEFLATE 26 /* RFC1979 */
/* 27-254 unassigned */
#define CCPOPT_RESV 255 /* RFC1962 */
static const struct tok ccpconfopts_values[] = {
{ CCPOPT_OUI, "OUI" },
{ CCPOPT_PRED1, "Pred-1" },
{ CCPOPT_PRED2, "Pred-2" },
{ CCPOPT_PJUMP, "Puddle" },
{ CCPOPT_HPPPC, "HP-PPC" },
{ CCPOPT_STACLZS, "Stac-LZS" },
{ CCPOPT_MPPC, "MPPC" },
{ CCPOPT_GFZA, "Gand-FZA" },
{ CCPOPT_V42BIS, "V.42bis" },
{ CCPOPT_BSDCOMP, "BSD-Comp" },
{ CCPOPT_LZSDCP, "LZS-DCP" },
{ CCPOPT_MVRCA, "MVRCA" },
{ CCPOPT_DEC, "DEC" },
{ CCPOPT_DEFLATE, "Deflate" },
{ CCPOPT_RESV, "Reserved"},
{0, NULL}
};
/* BACP Config Options */
#define BACPOPT_FPEER 1 /* RFC2125 */
static const struct tok bacconfopts_values[] = {
{ BACPOPT_FPEER, "Favored-Peer" },
{0, NULL}
};
/* SDCP - to be supported */
/* IPCP Config Options */
#define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */
#define IPCPOPT_IPCOMP 2 /* RFC1332 */
#define IPCPOPT_ADDR 3 /* RFC1332 */
#define IPCPOPT_MOBILE4 4 /* RFC2290 */
#define IPCPOPT_PRIDNS 129 /* RFC1877 */
#define IPCPOPT_PRINBNS 130 /* RFC1877 */
#define IPCPOPT_SECDNS 131 /* RFC1877 */
#define IPCPOPT_SECNBNS 132 /* RFC1877 */
static const struct tok ipcpopt_values[] = {
{ IPCPOPT_2ADDR, "IP-Addrs" },
{ IPCPOPT_IPCOMP, "IP-Comp" },
{ IPCPOPT_ADDR, "IP-Addr" },
{ IPCPOPT_MOBILE4, "Home-Addr" },
{ IPCPOPT_PRIDNS, "Pri-DNS" },
{ IPCPOPT_PRINBNS, "Pri-NBNS" },
{ IPCPOPT_SECDNS, "Sec-DNS" },
{ IPCPOPT_SECNBNS, "Sec-NBNS" },
{ 0, NULL }
};
#define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */
#define IPCPOPT_IPCOMP_MINLEN 14
static const struct tok ipcpopt_compproto_values[] = {
{ PPP_VJC, "VJ-Comp" },
{ IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" },
{ 0, NULL }
};
static const struct tok ipcpopt_compproto_subopt_values[] = {
{ 1, "RTP-Compression" },
{ 2, "Enhanced RTP-Compression" },
{ 0, NULL }
};
/* IP6CP Config Options */
#define IP6CP_IFID 1
static const struct tok ip6cpopt_values[] = {
{ IP6CP_IFID, "Interface-ID" },
{ 0, NULL }
};
/* ATCP - to be supported */
/* OSINLCP - to be supported */
/* BVCP - to be supported */
/* BCP - to be supported */
/* IPXCP - to be supported */
/* MPLSCP - to be supported */
/* Auth Algorithms */
/* 0-4 Reserved (RFC1994) */
#define AUTHALG_CHAPMD5 5 /* RFC1994 */
#define AUTHALG_MSCHAP1 128 /* RFC2433 */
#define AUTHALG_MSCHAP2 129 /* RFC2795 */
static const struct tok authalg_values[] = {
{ AUTHALG_CHAPMD5, "MD5" },
{ AUTHALG_MSCHAP1, "MS-CHAPv1" },
{ AUTHALG_MSCHAP2, "MS-CHAPv2" },
{ 0, NULL }
};
/* FCS Alternatives - to be supported */
/* Multilink Endpoint Discriminator (RFC1717) */
#define MEDCLASS_NULL 0 /* Null Class */
#define MEDCLASS_LOCAL 1 /* Locally Assigned */
#define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */
#define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */
#define MEDCLASS_MNB 4 /* PPP Magic Number Block */
#define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */
/* PPP LCP Callback */
#define CALLBACK_AUTH 0 /* Location determined by user auth */
#define CALLBACK_DSTR 1 /* Dialing string */
#define CALLBACK_LID 2 /* Location identifier */
#define CALLBACK_E164 3 /* E.164 number */
#define CALLBACK_X500 4 /* X.500 distinguished name */
#define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */
static const struct tok ppp_callback_values[] = {
{ CALLBACK_AUTH, "UserAuth" },
{ CALLBACK_DSTR, "DialString" },
{ CALLBACK_LID, "LocalID" },
{ CALLBACK_E164, "E.164" },
{ CALLBACK_X500, "X.500" },
{ CALLBACK_CBCP, "CBCP" },
{ 0, NULL }
};
/* CHAP */
#define CHAP_CHAL 1
#define CHAP_RESP 2
#define CHAP_SUCC 3
#define CHAP_FAIL 4
static const struct tok chapcode_values[] = {
{ CHAP_CHAL, "Challenge" },
{ CHAP_RESP, "Response" },
{ CHAP_SUCC, "Success" },
{ CHAP_FAIL, "Fail" },
{ 0, NULL}
};
/* PAP */
#define PAP_AREQ 1
#define PAP_AACK 2
#define PAP_ANAK 3
static const struct tok papcode_values[] = {
{ PAP_AREQ, "Auth-Req" },
{ PAP_AACK, "Auth-ACK" },
{ PAP_ANAK, "Auth-NACK" },
{ 0, NULL }
};
/* BAP */
#define BAP_CALLREQ 1
#define BAP_CALLRES 2
#define BAP_CBREQ 3
#define BAP_CBRES 4
#define BAP_LDQREQ 5
#define BAP_LDQRES 6
#define BAP_CSIND 7
#define BAP_CSRES 8
static int print_lcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ipcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int);
static int print_ccp_config_options(netdissect_options *, const u_char *p, int);
static int print_bacp_config_options(netdissect_options *, const u_char *p, int);
static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length);
/* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */
static void
handle_ctrl_proto(netdissect_options *ndo,
u_int proto, const u_char *pptr, int length)
{
const char *typestr;
u_int code, len;
int (*pfunc)(netdissect_options *, const u_char *, int);
int x, j;
const u_char *tptr;
tptr=pptr;
typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto);
ND_PRINT((ndo, "%s, ", typestr));
if (length < 4) /* FIXME weak boundary checking */
goto trunc;
ND_TCHECK2(*tptr, 2);
code = *tptr++;
ND_PRINT((ndo, "%s (0x%02x), id %u, length %u",
tok2str(cpcodes, "Unknown Opcode",code),
code,
*tptr++, /* ID */
length + 2));
if (!ndo->ndo_vflag)
return;
if (length <= 4)
return; /* there may be a NULL confreq etc. */
ND_TCHECK2(*tptr, 2);
len = EXTRACT_16BITS(tptr);
tptr += 2;
ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr - 2, "\n\t", 6);
switch (code) {
case CPCODES_VEXT:
if (length < 11)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
tptr += 4;
ND_TCHECK2(*tptr, 3);
ND_PRINT((ndo, " Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)),
EXTRACT_24BITS(tptr)));
/* XXX: need to decode Kind and Value(s)? */
break;
case CPCODES_CONF_REQ:
case CPCODES_CONF_ACK:
case CPCODES_CONF_NAK:
case CPCODES_CONF_REJ:
x = len - 4; /* Code(1), Identifier(1) and Length(2) */
do {
switch (proto) {
case PPP_LCP:
pfunc = print_lcp_config_options;
break;
case PPP_IPCP:
pfunc = print_ipcp_config_options;
break;
case PPP_IPV6CP:
pfunc = print_ip6cp_config_options;
break;
case PPP_CCP:
pfunc = print_ccp_config_options;
break;
case PPP_BACP:
pfunc = print_bacp_config_options;
break;
default:
/*
* No print routine for the options for
* this protocol.
*/
pfunc = NULL;
break;
}
if (pfunc == NULL) /* catch the above null pointer if unknown CP */
break;
if ((j = (*pfunc)(ndo, tptr, len)) == 0)
break;
x -= j;
tptr += j;
} while (x > 0);
break;
case CPCODES_TERM_REQ:
case CPCODES_TERM_ACK:
/* XXX: need to decode Data? */
break;
case CPCODES_CODE_REJ:
/* XXX: need to decode Rejected-Packet? */
break;
case CPCODES_PROT_REJ:
if (length < 6)
break;
ND_TCHECK2(*tptr, 2);
ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)",
tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
/* XXX: need to decode Rejected-Information? - hexdump for now */
if (len > 6) {
ND_PRINT((ndo, "\n\t Rejected Packet"));
print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2);
}
break;
case CPCODES_ECHO_REQ:
case CPCODES_ECHO_RPL:
case CPCODES_DISC_REQ:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* XXX: need to decode Data? - hexdump for now */
if (len > 8) {
ND_PRINT((ndo, "\n\t -----trailing data-----"));
ND_TCHECK2(tptr[4], len - 8);
print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8);
}
break;
case CPCODES_ID:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* RFC 1661 says this is intended to be human readable */
if (len > 8) {
ND_PRINT((ndo, "\n\t Message\n\t "));
if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend))
goto trunc;
}
break;
case CPCODES_TIME_REM:
if (length < 12)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4)));
/* XXX: need to decode Message? */
break;
default:
/* XXX this is dirty but we do not get the
* original pointer passed to the begin
* the PPP packet */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2);
break;
}
return;
trunc:
ND_PRINT((ndo, "[|%s]", typestr));
}
/* LCP config options */
static int
print_lcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
lcpconfopts[opt], opt, len));
else
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return 0;
}
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len));
else {
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return len;
}
switch (opt) {
case LCPOPT_VEXT:
if (len < 6) {
ND_PRINT((ndo, " (length bogus, should be >= 6)"));
return len;
}
ND_TCHECK_24BITS(p + 2);
ND_PRINT((ndo, ": Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)),
EXTRACT_24BITS(p + 2)));
#if 0
ND_TCHECK(p[5]);
ND_PRINT((ndo, ", kind: 0x%02x", p[5]));
ND_PRINT((ndo, ", Value: 0x"));
for (i = 0; i < len - 6; i++) {
ND_TCHECK(p[6 + i]);
ND_PRINT((ndo, "%02x", p[6 + i]));
}
#endif
break;
case LCPOPT_MRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return len;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_ACCM:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK_32BITS(p + 2);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_AP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2))));
switch (EXTRACT_16BITS(p+2)) {
case PPP_CHAP:
ND_TCHECK(p[4]);
ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4])));
break;
case PPP_PAP: /* fall through */
case PPP_EAP:
case PPP_SPAP:
case PPP_SPAP_OLD:
break;
default:
print_unknown_data(ndo, p, "\n\t", len);
}
break;
case LCPOPT_QP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK_16BITS(p+2);
if (EXTRACT_16BITS(p+2) == PPP_LQM)
ND_PRINT((ndo, ": LQR"));
else
ND_PRINT((ndo, ": unknown"));
break;
case LCPOPT_MN:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK_32BITS(p + 2);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_PFC:
break;
case LCPOPT_ACFC:
break;
case LCPOPT_LD:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_CBACK:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_PRINT((ndo, ": "));
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Callback Operation %s (%u)",
tok2str(ppp_callback_values, "Unknown", p[2]),
p[2]));
break;
case LCPOPT_MLMRRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK_16BITS(p + 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_MLED:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_TCHECK(p[2]);
switch (p[2]) { /* class */
case MEDCLASS_NULL:
ND_PRINT((ndo, ": Null"));
break;
case MEDCLASS_LOCAL:
ND_PRINT((ndo, ": Local")); /* XXX */
break;
case MEDCLASS_IPV4:
if (len != 7) {
ND_PRINT((ndo, " (length bogus, should be = 7)"));
return 0;
}
ND_TCHECK2(*(p + 3), 4);
ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3)));
break;
case MEDCLASS_MAC:
if (len != 9) {
ND_PRINT((ndo, " (length bogus, should be = 9)"));
return 0;
}
ND_TCHECK2(*(p + 3), 6);
ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3)));
break;
case MEDCLASS_MNB:
ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */
break;
case MEDCLASS_PSNDN:
ND_PRINT((ndo, ": PSNDN")); /* XXX */
break;
default:
ND_PRINT((ndo, ": Unknown class %u", p[2]));
break;
}
break;
/* XXX: to be supported */
#if 0
case LCPOPT_DEP6:
case LCPOPT_FCSALT:
case LCPOPT_SDP:
case LCPOPT_NUMMODE:
case LCPOPT_DEP12:
case LCPOPT_DEP14:
case LCPOPT_DEP15:
case LCPOPT_DEP16:
case LCPOPT_MLSSNHF:
case LCPOPT_PROP:
case LCPOPT_DCEID:
case LCPOPT_MPP:
case LCPOPT_LCPAOPT:
case LCPOPT_COBS:
case LCPOPT_PE:
case LCPOPT_MLHF:
case LCPOPT_I18N:
case LCPOPT_SDLOS:
case LCPOPT_PPPMUX:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|lcp]"));
return 0;
}
/* ML-PPP*/
static const struct tok ppp_ml_flag_values[] = {
{ 0x80, "begin" },
{ 0x40, "end" },
{ 0, NULL }
};
static void
handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
if (length < 2) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
if (!ND_TTEST_16BITS(p)) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
/* CHAP */
static void
handle_chap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int val_size, name_size, msg_size;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|chap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|chap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "CHAP, %s (0x%02x)",
tok2str(chapcode_values,"unknown",code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
/*
* Note that this is a generic CHAP decoding routine. Since we
* don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1,
* MS-CHAPv2) is used at this point, we can't decode packet
* specifically to each algorithms. Instead, we simply decode
* the GCD (Gratest Common Denominator) for all algorithms.
*/
switch (code) {
case CHAP_CHAL:
case CHAP_RESP:
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
val_size = *p; /* value size */
p++;
if (length - (p - p0) < val_size)
return;
ND_PRINT((ndo, ", Value "));
for (i = 0; i < val_size; i++) {
ND_TCHECK(*p);
ND_PRINT((ndo, "%02x", *p++));
}
name_size = len - (p - p0);
ND_PRINT((ndo, ", Name "));
for (i = 0; i < name_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case CHAP_SUCC:
case CHAP_FAIL:
msg_size = len - (p - p0);
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|chap]"));
}
/* PAP (see RFC 1334) */
static void
handle_pap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int peerid_len, passwd_len, msg_len;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|pap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|pap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "PAP, %s (0x%02x)",
tok2str(papcode_values, "unknown", code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
if ((int)len > length) {
ND_PRINT((ndo, ", length %u > packet size", len));
return;
}
length = len;
if (length < (p - p0)) {
ND_PRINT((ndo, ", length %u < PAP header length", length));
return;
}
switch (code) {
case PAP_AREQ:
/* A valid Authenticate-Request is 6 or more octets long. */
if (len < 6)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
peerid_len = *p; /* Peer-ID Length */
p++;
if (length - (p - p0) < peerid_len)
return;
ND_PRINT((ndo, ", Peer "));
for (i = 0; i < peerid_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
passwd_len = *p; /* Password Length */
p++;
if (length - (p - p0) < passwd_len)
return;
ND_PRINT((ndo, ", Name "));
for (i = 0; i < passwd_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case PAP_AACK:
case PAP_ANAK:
/* Although some implementations ignore truncation at
* this point and at least one generates a truncated
* packet, RFC 1334 section 2.2.2 clearly states that
* both AACK and ANAK are at least 5 bytes long.
*/
if (len < 5)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
msg_len = *p; /* Msg-Length */
p++;
if (length - (p - p0) < msg_len)
return;
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pap]"));
}
/* BAP */
static void
handle_bap(netdissect_options *ndo _U_,
const u_char *p _U_, int length _U_)
{
/* XXX: to be supported!! */
}
/* IPCP config options */
static int
print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK_16BITS(p+2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
/* IP6CP config options */
static int
print_ip6cp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IP6CP_IFID:
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 2), 8);
ND_PRINT((ndo, ": %04x:%04x:%04x:%04x",
EXTRACT_16BITS(p + 2),
EXTRACT_16BITS(p + 4),
EXTRACT_16BITS(p + 6),
EXTRACT_16BITS(p + 8)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ip6cp]"));
return 0;
}
/* CCP config options */
static int
print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK(p[3]);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
/* BACP config options */
static int
print_bacp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case BACPOPT_FPEER:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK_32BITS(p + 2);
ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|bacp]"));
return 0;
}
/*
* Un-escape RFC 1662 PPP in HDLC-like framing, with octet escapes.
* The length argument is the on-the-wire length, not the captured
* length; we can only un-escape the captured part.
*/
static void
ppp_hdlc(netdissect_options *ndo,
const u_char *p, int length)
{
u_int caplen = ndo->ndo_snapend - p;
u_char *b, *t, c;
const u_char *s;
u_int i;
int proto;
const void *se;
if (caplen == 0)
return;
if (length <= 0)
return;
b = (u_char *)malloc(caplen);
if (b == NULL)
return;
/*
* Unescape all the data into a temporary, private, buffer.
* Do this so that we dont overwrite the original packet
* contents.
*/
for (s = p, t = b, i = caplen; i != 0; i--) {
c = *s++;
if (c == 0x7d) {
if (i <= 1)
break;
i--;
c = *s++ ^ 0x20;
}
*t++ = c;
}
se = ndo->ndo_snapend;
ndo->ndo_snapend = t;
length = t - b;
/* now lets guess about the payload codepoint format */
if (length < 1)
goto trunc;
proto = *b; /* start with a one-octet codepoint guess */
switch (proto) {
case PPP_IP:
ip_print(ndo, b + 1, length - 1);
goto cleanup;
case PPP_IPV6:
ip6_print(ndo, b + 1, length - 1);
goto cleanup;
default: /* no luck - try next guess */
break;
}
if (length < 2)
goto trunc;
proto = EXTRACT_16BITS(b); /* next guess - load two octets */
switch (proto) {
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */
if (length < 4)
goto trunc;
proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */
handle_ppp(ndo, proto, b + 4, length - 4);
break;
default: /* last guess - proto must be a PPP proto-id */
handle_ppp(ndo, proto, b + 2, length - 2);
break;
}
cleanup:
ndo->ndo_snapend = se;
free(b);
return;
trunc:
ndo->ndo_snapend = se;
free(b);
ND_PRINT((ndo, "[|ppp]"));
}
/* PPP */
static void
handle_ppp(netdissect_options *ndo,
u_int proto, const u_char *p, int length)
{
if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */
ppp_hdlc(ndo, p - 1, length);
return;
}
switch (proto) {
case PPP_LCP: /* fall through */
case PPP_IPCP:
case PPP_OSICP:
case PPP_MPLSCP:
case PPP_IPV6CP:
case PPP_CCP:
case PPP_BACP:
handle_ctrl_proto(ndo, proto, p, length);
break;
case PPP_ML:
handle_mlppp(ndo, p, length);
break;
case PPP_CHAP:
handle_chap(ndo, p, length);
break;
case PPP_PAP:
handle_pap(ndo, p, length);
break;
case PPP_BAP: /* XXX: not yet completed */
handle_bap(ndo, p, length);
break;
case ETHERTYPE_IP: /*XXX*/
case PPP_VJNC:
case PPP_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6: /*XXX*/
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case ETHERTYPE_IPX: /*XXX*/
case PPP_IPX:
ipx_print(ndo, p, length);
break;
case PPP_OSI:
isoclns_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
case PPP_COMP:
ND_PRINT((ndo, "compressed PPP data"));
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
/* Standard PPP printer */
u_int
ppp_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int proto,ppp_header;
u_int olen = length; /* _o_riginal length */
u_int hdr_len = 0;
/*
* Here, we assume that p points to the Address and Control
* field (if they present).
*/
if (length < 2)
goto trunc;
ND_TCHECK2(*p, 2);
ppp_header = EXTRACT_16BITS(p);
switch(ppp_header) {
case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "In "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "Out "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL):
p += 2; /* ACFC not used */
length -= 2;
hdr_len += 2;
break;
default:
break;
}
if (length < 2)
goto trunc;
ND_TCHECK(*p);
if (*p % 2) {
proto = *p; /* PFC is used */
p++;
length--;
hdr_len++;
} else {
ND_TCHECK2(*p, 2);
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdr_len += 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s (0x%04x), length %u: ",
tok2str(ppptype2str, "unknown", proto),
proto,
olen));
handle_ppp(ndo, proto, p, length);
return (hdr_len);
trunc:
ND_PRINT((ndo, "[|ppp]"));
return (0);
}
/* PPP I/F printer */
u_int
ppp_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
if (caplen < PPP_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
#if 0
/*
* XXX: seems to assume that there are 2 octets prepended to an
* actual PPP frame. The 1st octet looks like Input/Output flag
* while 2nd octet is unknown, at least to me
* (mshindo@mshindo.net).
*
* That was what the original tcpdump code did.
*
* FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound
* packets and 0 for inbound packets - but only if the
* protocol field has the 0x8000 bit set (i.e., it's a network
* control protocol); it does so before running the packet through
* "bpf_filter" to see if it should be discarded, and to see
* if we should update the time we sent the most recent packet...
*
* ...but it puts the original address field back after doing
* so.
*
* NetBSD's "if_ppp.c" doesn't set the first octet in that fashion.
*
* I don't know if any PPP implementation handed up to a BPF
* device packets with the first octet being 1 for outbound and
* 0 for inbound packets, so I (guy@alum.mit.edu) don't know
* whether that ever needs to be checked or not.
*
* Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP,
* and its tcpdump appears to assume that the frame always
* begins with an address field and a control field, and that
* the address field might be 0x0f or 0x8f, for Cisco
* point-to-point with HDLC framing as per section 4.3.1 of RFC
* 1547, as well as 0xff, for PPP in HDLC-like framing as per
* RFC 1662.
*
* (Is the Cisco framing in question what DLT_C_HDLC, in
* BSD/OS, is?)
*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1]));
#endif
ppp_print(ndo, p, length);
return (0);
}
/*
* PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like
* framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547,
* is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL,
* discard them *if* those are the first two octets, and parse the remaining
* packet as a PPP packet, as "ppp_print()" does).
*
* This handles, for example, DLT_PPP_SERIAL in NetBSD.
*/
u_int
ppp_hdlc_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
u_int proto;
u_int hdrlen = 0;
if (caplen < 2) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
switch (p[0]) {
case PPP_ADDRESS:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
length -= 2;
hdrlen += 2;
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdrlen += 2;
ND_PRINT((ndo, "%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
handle_ppp(ndo, proto, p, length);
break;
case CHDLC_UNICAST:
case CHDLC_BCAST:
return (chdlc_if_print(ndo, h, p));
default:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
hdrlen += 2;
/*
* XXX - NetBSD's "ppp_netbsd_serial_if_print()" treats
* the next two octets as an Ethernet type; does that
* ever happen?
*/
ND_PRINT((ndo, "unknown addr %02x; ctrl %02x", p[0], p[1]));
break;
}
return (hdrlen);
}
#define PPP_BSDI_HDRLEN 24
/* BSD/OS specific PPP printer */
u_int
ppp_bsdos_if_print(netdissect_options *ndo _U_,
const struct pcap_pkthdr *h _U_, register const u_char *p _U_)
{
register int hdrlength;
#ifdef __bsdi__
register u_int length = h->len;
register u_int caplen = h->caplen;
uint16_t ptype;
const u_char *q;
int i;
if (caplen < PPP_BSDI_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen)
}
hdrlength = 0;
#if 0
if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", p[0], p[1]));
p += 2;
hdrlength = 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
/* Retrieve the protocol type */
if (*p & 01) {
/* Compressed protocol field */
ptype = *p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x ", ptype));
p++;
hdrlength += 1;
} else {
/* Un-compressed protocol field */
ptype = EXTRACT_16BITS(p);
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%04x ", ptype));
p += 2;
hdrlength += 2;
}
#else
ptype = 0; /*XXX*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c ", p[SLC_DIR] ? 'O' : 'I'));
if (p[SLC_LLHL]) {
/* link level header */
struct ppp_header *ph;
q = p + SLC_BPFHDRLEN;
ph = (struct ppp_header *)q;
if (ph->phdr_addr == PPP_ADDRESS
&& ph->phdr_ctl == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", q[0], q[1]));
ptype = EXTRACT_16BITS(&ph->phdr_type);
if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) {
ND_PRINT((ndo, "%s ", tok2str(ppptype2str,
"proto-#%d", ptype)));
}
} else {
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "LLH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
}
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
if (p[SLC_CHL]) {
q = p + SLC_BPFHDRLEN + p[SLC_LLHL];
switch (ptype) {
case PPP_VJC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
case PPP_VJNC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
default:
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "CH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
break;
}
}
hdrlength = PPP_BSDI_HDRLEN;
#endif
length -= hdrlength;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype)));
}
printx:
#else /* __bsdi */
hdrlength = 0;
#endif /* __bsdi__ */
return (hdrlength);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-770/c/good_4653_0 |
crossvul-cpp_data_good_3143_1 | /* $OpenBSD: server_file.c,v 1.64 2017/01/31 14:39:47 reyk Exp $ */
/*
* Copyright (c) 2006 - 2017 Reyk Floeter <reyk@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* 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.
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <limits.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <time.h>
#include <event.h>
#include "httpd.h"
#include "http.h"
#define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
int server_file_access(struct httpd *, struct client *,
char *, size_t);
int server_file_request(struct httpd *, struct client *,
char *, struct stat *);
int server_partial_file_request(struct httpd *, struct client *,
char *, struct stat *, char *);
int server_file_index(struct httpd *, struct client *,
struct stat *);
int server_file_modified_since(struct http_descriptor *,
struct stat *);
int server_file_method(struct client *);
int parse_range_spec(char *, size_t, struct range *);
int parse_ranges(struct client *, char *, size_t);
int
server_file_access(struct httpd *env, struct client *clt,
char *path, size_t len)
{
struct http_descriptor *desc = clt->clt_descreq;
struct server_config *srv_conf = clt->clt_srv_conf;
struct stat st;
struct kv *r, key;
char *newpath, *encodedpath;
int ret;
errno = 0;
if (access(path, R_OK) == -1) {
goto fail;
} else if (stat(path, &st) == -1) {
goto fail;
} else if (S_ISDIR(st.st_mode)) {
/* Deny access if directory indexing is disabled */
if (srv_conf->flags & SRVFLAG_NO_INDEX) {
errno = EACCES;
goto fail;
}
if (desc->http_path_alias != NULL) {
/* Recursion - the index "file" is a directory? */
errno = EINVAL;
goto fail;
}
/* Redirect to path with trailing "/" */
if (path[strlen(path) - 1] != '/') {
if ((encodedpath = url_encode(desc->http_path)) == NULL)
return (500);
if (asprintf(&newpath, "http%s://%s%s/",
srv_conf->flags & SRVFLAG_TLS ? "s" : "",
desc->http_host, encodedpath) == -1) {
free(encodedpath);
return (500);
}
free(encodedpath);
/* Path alias will be used for the redirection */
desc->http_path_alias = newpath;
/* Indicate that the file has been moved */
return (301);
}
/* Append the default index file to the location */
if (asprintf(&newpath, "%s%s", desc->http_path,
srv_conf->index) == -1)
return (500);
desc->http_path_alias = newpath;
if (server_getlocation(clt, newpath) != srv_conf) {
/* The location has changed */
return (server_file(env, clt));
}
/* Otherwise append the default index file to the path */
if (strlcat(path, srv_conf->index, len) >= len) {
errno = EACCES;
goto fail;
}
ret = server_file_access(env, clt, path, len);
if (ret == 404) {
/*
* Index file not found; fail if auto-indexing is
* not enabled, otherwise return success but
* indicate directory with S_ISDIR of the previous
* stat.
*/
if ((srv_conf->flags & SRVFLAG_AUTO_INDEX) == 0) {
errno = EACCES;
goto fail;
}
return (server_file_index(env, clt, &st));
}
return (ret);
} else if (!S_ISREG(st.st_mode)) {
/* Don't follow symlinks and ignore special files */
errno = EACCES;
goto fail;
}
key.kv_key = "Range";
r = kv_find(&desc->http_headers, &key);
if (r != NULL)
return (server_partial_file_request(env, clt, path, &st,
r->kv_value));
else
return (server_file_request(env, clt, path, &st));
fail:
switch (errno) {
case ENOENT:
case ENOTDIR:
return (404);
case EACCES:
return (403);
default:
return (500);
}
/* NOTREACHED */
}
int
server_file(struct httpd *env, struct client *clt)
{
struct http_descriptor *desc = clt->clt_descreq;
struct server_config *srv_conf = clt->clt_srv_conf;
char path[PATH_MAX];
const char *stripped, *errstr = NULL;
int ret = 500;
if (srv_conf->flags & SRVFLAG_FCGI)
return (server_fcgi(env, clt));
/* Request path is already canonicalized */
stripped = server_root_strip(
desc->http_path_alias != NULL ?
desc->http_path_alias : desc->http_path,
srv_conf->strip);
if ((size_t)snprintf(path, sizeof(path), "%s%s",
srv_conf->root, stripped) >= sizeof(path)) {
errstr = desc->http_path;
goto abort;
}
/* Returns HTTP status code on error */
if ((ret = server_file_access(env, clt, path, sizeof(path))) > 0) {
errstr = desc->http_path_alias != NULL ?
desc->http_path_alias : desc->http_path;
goto abort;
}
return (ret);
abort:
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, ret, errstr);
return (-1);
}
int
server_file_method(struct client *clt)
{
struct http_descriptor *desc = clt->clt_descreq;
switch (desc->http_method) {
case HTTP_METHOD_GET:
case HTTP_METHOD_HEAD:
return (0);
default:
/* Other methods are not allowed */
errno = EACCES;
return (405);
}
/* NOTREACHED */
}
int
server_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct media_type *media;
const char *errstr = NULL;
int fd = -1, ret, code = 500;
if ((ret = server_file_method(clt)) != 0) {
code = ret;
goto abort;
}
if ((ret = server_file_modified_since(clt->clt_descreq, st)) != -1)
return (ret);
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
ret = server_response_http(clt, 200, media, st->st_size,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
close(fd);
goto done;
default:
break;
}
clt->clt_fd = fd;
if (clt->clt_srvbev != NULL)
bufferevent_free(clt->clt_srvbev);
clt->clt_srvbev_throttled = 0;
clt->clt_srvbev = bufferevent_new(clt->clt_fd, server_read,
server_write, server_file_error, clt);
if (clt->clt_srvbev == NULL) {
errstr = "failed to allocate file buffer event";
goto fail;
}
/* Adjust read watermark to the socket output buffer size */
bufferevent_setwatermark(clt->clt_srvbev, EV_READ, 0,
clt->clt_sndbufsiz);
bufferevent_settimeout(clt->clt_srvbev,
srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
bufferevent_enable(clt->clt_srvbev, EV_READ);
bufferevent_disable(clt->clt_bev, EV_READ);
done:
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
int
server_partial_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st, char *range_str)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct http_descriptor *resp = clt->clt_descresp;
struct http_descriptor *desc = clt->clt_descreq;
struct media_type *media, multipart_media;
struct range_data *r = &clt->clt_ranges;
struct range *range;
size_t content_length = 0;
int code = 500, fd = -1, i, nranges, ret;
char content_range[64];
const char *errstr = NULL;
/* Ignore range request for methods other than GET */
if (desc->http_method != HTTP_METHOD_GET)
return server_file_request(env, clt, path, st);
if ((nranges = parse_ranges(clt, range_str, st->st_size)) < 1) {
code = 416;
(void)snprintf(content_range, sizeof(content_range),
"bytes */%lld", st->st_size);
errstr = content_range;
goto abort;
}
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
r->range_media = media;
if (nranges == 1) {
range = &r->range[0];
(void)snprintf(content_range, sizeof(content_range),
"bytes %lld-%lld/%lld", range->start, range->end,
st->st_size);
if (kv_add(&resp->http_headers, "Content-Range",
content_range) == NULL)
goto abort;
range = &r->range[0];
content_length += range->end - range->start + 1;
} else {
/* Add boundary, all parts will be handled by the callback */
arc4random_buf(&clt->clt_boundary, sizeof(clt->clt_boundary));
/* Calculate Content-Length of the complete multipart body */
for (i = 0; i < nranges; i++) {
range = &r->range[i];
/* calculate Content-Length of the complete body */
if ((ret = snprintf(NULL, 0,
"\r\n--%llu\r\n"
"Content-Type: %s/%s\r\n"
"Content-Range: bytes %lld-%lld/%lld\r\n\r\n",
clt->clt_boundary,
media->media_type, media->media_subtype,
range->start, range->end, st->st_size)) < 0)
goto abort;
/* Add data length */
content_length += ret + range->end - range->start + 1;
}
if ((ret = snprintf(NULL, 0, "\r\n--%llu--\r\n",
clt->clt_boundary)) < 0)
goto abort;
content_length += ret;
/* prepare multipart/byteranges media type */
(void)strlcpy(multipart_media.media_type, "multipart",
sizeof(multipart_media.media_type));
(void)snprintf(multipart_media.media_subtype,
sizeof(multipart_media.media_subtype),
"byteranges; boundary=%llu", clt->clt_boundary);
media = &multipart_media;
}
/* Start with first range */
r->range_toread = TOREAD_HTTP_RANGE;
ret = server_response_http(clt, 206, media, content_length,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
close(fd);
goto done;
default:
break;
}
clt->clt_fd = fd;
if (clt->clt_srvbev != NULL)
bufferevent_free(clt->clt_srvbev);
clt->clt_srvbev_throttled = 0;
clt->clt_srvbev = bufferevent_new(clt->clt_fd, server_read_httprange,
server_write, server_file_error, clt);
if (clt->clt_srvbev == NULL) {
errstr = "failed to allocate file buffer event";
goto fail;
}
/* Adjust read watermark to the socket output buffer size */
bufferevent_setwatermark(clt->clt_srvbev, EV_READ, 0,
clt->clt_sndbufsiz);
bufferevent_settimeout(clt->clt_srvbev,
srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
bufferevent_enable(clt->clt_srvbev, EV_READ);
bufferevent_disable(clt->clt_bev, EV_READ);
done:
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
int
server_file_index(struct httpd *env, struct client *clt, struct stat *st)
{
char path[PATH_MAX];
char tmstr[21];
struct http_descriptor *desc = clt->clt_descreq;
struct server_config *srv_conf = clt->clt_srv_conf;
struct dirent **namelist, *dp;
int namesize, i, ret, fd = -1, namewidth, skip;
int code = 500;
struct evbuffer *evb = NULL;
struct media_type *media;
const char *stripped, *style;
char *escapeduri, *escapedhtml, *escapedpath;
struct tm tm;
time_t t, dir_mtime;
if ((ret = server_file_method(clt)) != 0) {
code = ret;
goto abort;
}
/* Request path is already canonicalized */
stripped = server_root_strip(desc->http_path, srv_conf->strip);
if ((size_t)snprintf(path, sizeof(path), "%s%s",
srv_conf->root, stripped) >= sizeof(path))
goto abort;
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
/* Save last modification time */
dir_mtime = MINIMUM(time(NULL), st->st_mtim.tv_sec);
if ((evb = evbuffer_new()) == NULL)
goto abort;
if ((namesize = scandir(path, &namelist, NULL, alphasort)) == -1)
goto abort;
/* Indicate failure but continue going through the list */
skip = 0;
if ((escapedpath = escape_html(desc->http_path)) == NULL)
goto fail;
/* A CSS stylesheet allows minimal customization by the user */
style = "body { background-color: white; color: black; font-family: "
"sans-serif; }\nhr { border: 0; border-bottom: 1px dashed; }\n";
/* Generate simple HTML index document */
if (evbuffer_add_printf(evb,
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; "
"charset=utf-8\"/>\n"
"<title>Index of %s</title>\n"
"<style type=\"text/css\"><!--\n%s\n--></style>\n"
"</head>\n"
"<body>\n"
"<h1>Index of %s</h1>\n"
"<hr>\n<pre>\n",
escapedpath, style, escapedpath) == -1)
skip = 1;
free(escapedpath);
for (i = 0; i < namesize; i++) {
dp = namelist[i];
if (skip ||
fstatat(fd, dp->d_name, st, 0) == -1) {
free(dp);
continue;
}
t = st->st_mtime;
localtime_r(&t, &tm);
strftime(tmstr, sizeof(tmstr), "%d-%h-%Y %R", &tm);
namewidth = 51 - strlen(dp->d_name);
if ((escapeduri = url_encode(dp->d_name)) == NULL)
goto fail;
if ((escapedhtml = escape_html(dp->d_name)) == NULL)
goto fail;
if (dp->d_name[0] == '.' &&
!(dp->d_name[1] == '.' && dp->d_name[2] == '\0')) {
/* ignore hidden files starting with a dot */
} else if (S_ISDIR(st->st_mode)) {
namewidth -= 1; /* trailing slash */
if (evbuffer_add_printf(evb,
"<a href=\"%s%s/\">%s/</a>%*s%s%20s\n",
strchr(escapeduri, ':') != NULL ? "./" : "",
escapeduri, escapedhtml,
MAXIMUM(namewidth, 0), " ", tmstr, "-") == -1)
skip = 1;
} else if (S_ISREG(st->st_mode)) {
if (evbuffer_add_printf(evb,
"<a href=\"%s%s\">%s</a>%*s%s%20llu\n",
strchr(escapeduri, ':') != NULL ? "./" : "",
escapeduri, escapedhtml,
MAXIMUM(namewidth, 0), " ",
tmstr, st->st_size) == -1)
skip = 1;
}
free(escapeduri);
free(escapedhtml);
free(dp);
}
free(namelist);
if (skip ||
evbuffer_add_printf(evb,
"</pre>\n<hr>\n</body>\n</html>\n") == -1)
goto abort;
close(fd);
fd = -1;
media = media_find_config(env, srv_conf, "index.html");
ret = server_response_http(clt, 200, media, EVBUFFER_LENGTH(evb),
dir_mtime);
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
evbuffer_free(evb);
goto done;
default:
break;
}
if (server_bufferevent_write_buffer(clt, evb) == -1)
goto fail;
evbuffer_free(evb);
evb = NULL;
bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
if (clt->clt_persist)
clt->clt_toread = TOREAD_HTTP_HEADER;
else
clt->clt_toread = TOREAD_HTTP_NONE;
clt->clt_done = 0;
done:
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (fd != -1)
close(fd);
if (evb != NULL)
evbuffer_free(evb);
server_abort_http(clt, code, desc->http_path);
return (-1);
}
void
server_file_error(struct bufferevent *bev, short error, void *arg)
{
struct client *clt = arg;
struct evbuffer *dst;
if (error & EVBUFFER_TIMEOUT) {
server_close(clt, "buffer event timeout");
return;
}
if (error & EVBUFFER_ERROR) {
if (errno == EFBIG) {
bufferevent_enable(bev, EV_READ);
return;
}
server_close(clt, "buffer event error");
return;
}
if (error & (EVBUFFER_READ|EVBUFFER_WRITE|EVBUFFER_EOF)) {
bufferevent_disable(bev, EV_READ|EV_WRITE);
clt->clt_done = 1;
if (clt->clt_persist) {
/* Close input file and wait for next HTTP request */
if (clt->clt_fd != -1)
close(clt->clt_fd);
clt->clt_fd = -1;
clt->clt_toread = TOREAD_HTTP_HEADER;
server_reset_http(clt);
bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
return;
}
dst = EVBUFFER_OUTPUT(clt->clt_bev);
if (EVBUFFER_LENGTH(dst)) {
/* Finish writing all data first */
bufferevent_enable(clt->clt_bev, EV_WRITE);
return;
}
server_close(clt, "done");
return;
}
server_close(clt, "unknown event error");
return;
}
int
server_file_modified_since(struct http_descriptor *desc, struct stat *st)
{
struct kv key, *since;
struct tm tm;
key.kv_key = "If-Modified-Since";
if ((since = kv_find(&desc->http_headers, &key)) != NULL &&
since->kv_value != NULL) {
memset(&tm, 0, sizeof(struct tm));
/*
* Return "Not modified" if the file hasn't changed since
* the requested time.
*/
if (strptime(since->kv_value,
"%a, %d %h %Y %T %Z", &tm) != NULL &&
timegm(&tm) >= st->st_mtim.tv_sec)
return (304);
}
return (-1);
}
int
parse_ranges(struct client *clt, char *str, size_t file_sz)
{
int i = 0;
char *p, *q;
struct range_data *r = &clt->clt_ranges;
memset(r, 0, sizeof(*r));
/* Extract range unit */
if ((p = strchr(str, '=')) == NULL)
return (-1);
*p++ = '\0';
/* Check if it's a bytes range spec */
if (strcmp(str, "bytes") != 0)
return (-1);
while ((q = strchr(p, ',')) != NULL) {
*q++ = '\0';
/* Extract start and end positions */
if (parse_range_spec(p, file_sz, &r->range[i]) == 0)
continue;
i++;
if (i == SERVER_MAX_RANGES)
return (-1);
p = q;
}
if (parse_range_spec(p, file_sz, &r->range[i]) != 0)
i++;
r->range_total = file_sz;
r->range_count = i;
return (i);
}
int
parse_range_spec(char *str, size_t size, struct range *r)
{
size_t start_str_len, end_str_len;
char *p, *start_str, *end_str;
const char *errstr;
if ((p = strchr(str, '-')) == NULL)
return (0);
*p++ = '\0';
start_str = str;
end_str = p;
start_str_len = strlen(start_str);
end_str_len = strlen(end_str);
/* Either 'start' or 'end' is optional but not both */
if ((start_str_len == 0) && (end_str_len == 0))
return (0);
if (end_str_len) {
r->end = strtonum(end_str, 0, LLONG_MAX, &errstr);
if (errstr)
return (0);
if ((size_t)r->end >= size)
r->end = size - 1;
} else
r->end = size - 1;
if (start_str_len) {
r->start = strtonum(start_str, 0, LLONG_MAX, &errstr);
if (errstr)
return (0);
if ((size_t)r->start >= size)
return (0);
} else {
r->start = size - r->end;
r->end = size - 1;
}
if (r->end < r->start)
return (0);
return (1);
}
| ./CrossVul/dataset_final_sorted/CWE-770/c/good_3143_1 |
crossvul-cpp_data_bad_2614_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N GGGG %
% P P NN N G %
% PPPP N N N G GG %
% P N NN G G %
% P N N GGG %
% %
% %
% Read/Write Portable Network Graphics Image Format %
% %
% Software Design %
% Cristy %
% Glenn Randers-Pehrson %
% November 1997 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/histogram.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/layer.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/transform.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_PNG_DELEGATE)
/* Suppress libpng pedantic warnings that were added in
* libpng-1.2.41 and libpng-1.4.0. If you are working on
* migration to libpng-1.5, remove these defines and then
* fix any code that generates warnings.
*/
/* #define PNG_DEPRECATED Use of this function is deprecated */
/* #define PNG_USE_RESULT The result of this function must be checked */
/* #define PNG_NORETURN This function does not return */
/* #define PNG_ALLOCATED The result of the function is new memory */
/* #define PNG_DEPSTRUCT Access to this struct member is deprecated */
/* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */
#define PNG_PTR_NORETURN
#include "png.h"
#include "zlib.h"
/* ImageMagick differences */
#define first_scene scene
#if PNG_LIBPNG_VER > 10011
/*
Optional declarations. Define or undefine them as you like.
*/
/* #define PNG_DEBUG -- turning this on breaks VisualC compiling */
/*
Features under construction. Define these to work on them.
*/
#undef MNG_OBJECT_BUFFERS
#undef MNG_BASI_SUPPORTED
#define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */
#define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */
#if defined(MAGICKCORE_JPEG_DELEGATE)
# define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */
#endif
#if !defined(RGBColorMatchExact)
#define IsPNGColorEqual(color,target) \
(((color).red == (target).red) && \
((color).green == (target).green) && \
((color).blue == (target).blue))
#endif
/* Table of recognized sRGB ICC profiles */
struct sRGB_info_struct
{
png_uint_32 len;
png_uint_32 crc;
png_byte intent;
};
const struct sRGB_info_struct sRGB_info[] =
{
/* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */
{ 3048, 0x3b8772b9UL, 0},
/* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */
{ 3052, 0x427ebb21UL, 1},
/* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */
{60988, 0x306fd8aeUL, 0},
/* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */
{60960, 0xbbef7812UL, 0},
/* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */
{ 3024, 0x5d5129ceUL, 1},
/* HP-Microsoft sRGB v2 perceptual */
{ 3144, 0x182ea552UL, 0},
/* HP-Microsoft sRGB v2 media-relative */
{ 3144, 0xf29e526dUL, 1},
/* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */
{ 524, 0xd4938c39UL, 0},
/* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */
{ 3212, 0x034af5a1UL, 0},
/* Not recognized */
{ 0, 0x00000000UL, 0},
};
/* Macros for left-bit-replication to ensure that pixels
* and PixelPackets all have the same image->depth, and for use
* in PNG8 quantization.
*/
/* LBR01: Replicate top bit */
#define LBR01PacketRed(pixelpacket) \
(pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketGreen(pixelpacket) \
(pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketBlue(pixelpacket) \
(pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketOpacity(pixelpacket) \
(pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \
0 : QuantumRange);
#define LBR01PacketRGB(pixelpacket) \
{ \
LBR01PacketRed((pixelpacket)); \
LBR01PacketGreen((pixelpacket)); \
LBR01PacketBlue((pixelpacket)); \
}
#define LBR01PacketRGBO(pixelpacket) \
{ \
LBR01PacketRGB((pixelpacket)); \
LBR01PacketOpacity((pixelpacket)); \
}
#define LBR01PixelRed(pixel) \
(SetPixelRed((pixel), \
ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelGreen(pixel) \
(SetPixelGreen((pixel), \
ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelBlue(pixel) \
(SetPixelBlue((pixel), \
ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelOpacity(pixel) \
(SetPixelOpacity((pixel), \
ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \
0 : QuantumRange));
#define LBR01PixelRGB(pixel) \
{ \
LBR01PixelRed((pixel)); \
LBR01PixelGreen((pixel)); \
LBR01PixelBlue((pixel)); \
}
#define LBR01PixelRGBO(pixel) \
{ \
LBR01PixelRGB((pixel)); \
LBR01PixelOpacity((pixel)); \
}
/* LBR02: Replicate top 2 bits */
#define LBR02PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketOpacity(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \
(pixelpacket).opacity=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \
}
#define LBR02PacketRGB(pixelpacket) \
{ \
LBR02PacketRed((pixelpacket)); \
LBR02PacketGreen((pixelpacket)); \
LBR02PacketBlue((pixelpacket)); \
}
#define LBR02PacketRGBO(pixelpacket) \
{ \
LBR02PacketRGB((pixelpacket)); \
LBR02PacketOpacity((pixelpacket)); \
}
#define LBR02PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xc0; \
SetPixelRed((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xc0; \
SetPixelGreen((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \
SetPixelBlue((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02Opacity(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \
SetPixelOpacity((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \
}
#define LBR02PixelRGB(pixel) \
{ \
LBR02PixelRed((pixel)); \
LBR02PixelGreen((pixel)); \
LBR02PixelBlue((pixel)); \
}
#define LBR02PixelRGBO(pixel) \
{ \
LBR02PixelRGB((pixel)); \
LBR02Opacity((pixel)); \
}
/* LBR03: Replicate top 3 bits (only used with opaque pixels during
PNG8 quantization) */
#define LBR03PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \
(pixelpacket).red=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \
(pixelpacket).green=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \
(pixelpacket).blue=ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \
}
#define LBR03PacketRGB(pixelpacket) \
{ \
LBR03PacketRed((pixelpacket)); \
LBR03PacketGreen((pixelpacket)); \
LBR03PacketBlue((pixelpacket)); \
}
#define LBR03PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xe0; \
SetPixelRed((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xe0; \
SetPixelGreen((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelBlue(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \
& 0xe0; \
SetPixelBlue((pixel), ScaleCharToQuantum( \
(lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \
}
#define LBR03PixelRGB(pixel) \
{ \
LBR03PixelRed((pixel)); \
LBR03PixelGreen((pixel)); \
LBR03PixelBlue((pixel)); \
}
/* LBR04: Replicate top 4 bits */
#define LBR04PacketRed(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \
(pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketGreen(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \
(pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketBlue(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \
(pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketOpacity(pixelpacket) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \
(pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \
}
#define LBR04PacketRGB(pixelpacket) \
{ \
LBR04PacketRed((pixelpacket)); \
LBR04PacketGreen((pixelpacket)); \
LBR04PacketBlue((pixelpacket)); \
}
#define LBR04PacketRGBO(pixelpacket) \
{ \
LBR04PacketRGB((pixelpacket)); \
LBR04PacketOpacity((pixelpacket)); \
}
#define LBR04PixelRed(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \
& 0xf0; \
SetPixelRed((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelGreen(pixel) \
{ \
unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\
& 0xf0; \
SetPixelGreen((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelBlue(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \
SetPixelBlue((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelOpacity(pixel) \
{ \
unsigned char lbr_bits= \
ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \
SetPixelOpacity((pixel),\
ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \
}
#define LBR04PixelRGB(pixel) \
{ \
LBR04PixelRed((pixel)); \
LBR04PixelGreen((pixel)); \
LBR04PixelBlue((pixel)); \
}
#define LBR04PixelRGBO(pixel) \
{ \
LBR04PixelRGB((pixel)); \
LBR04PixelOpacity((pixel)); \
}
/*
Establish thread safety.
setjmp/longjmp is claimed to be safe on these platforms:
setjmp/longjmp is alleged to be unsafe on these platforms:
*/
#ifdef PNG_SETJMP_SUPPORTED
# ifndef IMPNG_SETJMP_IS_THREAD_SAFE
# define IMPNG_SETJMP_NOT_THREAD_SAFE
# endif
# ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
static SemaphoreInfo
*ping_semaphore = (SemaphoreInfo *) NULL;
# endif
#endif
/*
This temporary until I set up malloc'ed object attributes array.
Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but
waste more memory.
*/
#define MNG_MAX_OBJECTS 256
/*
If this not defined, spec is interpreted strictly. If it is
defined, an attempt will be made to recover from some errors,
including
o global PLTE too short
*/
#undef MNG_LOOSE
/*
Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure
it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work
with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8,
PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in
libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here.
PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and
will be enabled by default in libpng-1.2.0.
*/
#ifdef PNG_MNG_FEATURES_SUPPORTED
# ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
# define PNG_READ_EMPTY_PLTE_SUPPORTED
# endif
# ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED
# define PNG_WRITE_EMPTY_PLTE_SUPPORTED
# endif
#endif
/*
Maximum valid size_t in PNG/MNG chunks is (2^31)-1
This macro is only defined in libpng-1.0.3 and later.
Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6
*/
#ifndef PNG_UINT_31_MAX
#define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL
#endif
/*
Constant strings for known chunk types. If you need to add a chunk,
add a string holding the name here. To make the code more
portable, we use ASCII numbers like this, not characters.
*/
/* until registration of eXIf */
static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'};
/* after registration of eXIf */
static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'};
static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'};
static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'};
static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'};
static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'};
static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'};
static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'};
static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'};
static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'};
static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'};
static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'};
static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'};
static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'};
static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'};
static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'};
static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'};
static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'};
static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'};
static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'};
static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'};
static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'};
static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'};
static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'};
static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'};
static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'};
static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'};
static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'};
static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'};
static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'};
static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'};
static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'};
static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'};
#if defined(JNG_SUPPORTED)
static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'};
static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'};
static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'};
static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'};
static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'};
#endif
#if 0
/* Other known chunks that are not yet supported by ImageMagick: */
static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'};
static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'};
static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'};
static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'};
static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'};
static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'};
static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'};
#endif
typedef struct _MngBox
{
long
left,
right,
top,
bottom;
} MngBox;
typedef struct _MngPair
{
volatile long
a,
b;
} MngPair;
#ifdef MNG_OBJECT_BUFFERS
typedef struct _MngBuffer
{
size_t
height,
width;
Image
*image;
png_color
plte[256];
int
reference_count;
unsigned char
alpha_sample_depth,
compression_method,
color_type,
concrete,
filter_method,
frozen,
image_type,
interlace_method,
pixel_sample_depth,
plte_length,
sample_depth,
viewable;
} MngBuffer;
#endif
typedef struct _MngInfo
{
#ifdef MNG_OBJECT_BUFFERS
MngBuffer
*ob[MNG_MAX_OBJECTS];
#endif
Image *
image;
RectangleInfo
page;
int
adjoin,
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
bytes_in_read_buffer,
found_empty_plte,
#endif
equal_backgrounds,
equal_chrms,
equal_gammas,
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
equal_palettes,
#endif
equal_physs,
equal_srgbs,
framing_mode,
have_global_bkgd,
have_global_chrm,
have_global_gama,
have_global_phys,
have_global_sbit,
have_global_srgb,
have_saved_bkgd_index,
have_write_global_chrm,
have_write_global_gama,
have_write_global_plte,
have_write_global_srgb,
need_fram,
object_id,
old_framing_mode,
saved_bkgd_index;
int
new_number_colors;
ssize_t
image_found,
loop_count[256],
loop_iteration[256],
scenes_found,
x_off[MNG_MAX_OBJECTS],
y_off[MNG_MAX_OBJECTS];
MngBox
clip,
frame,
image_box,
object_clip[MNG_MAX_OBJECTS];
unsigned char
/* These flags could be combined into one byte */
exists[MNG_MAX_OBJECTS],
frozen[MNG_MAX_OBJECTS],
loop_active[256],
invisible[MNG_MAX_OBJECTS],
viewable[MNG_MAX_OBJECTS];
MagickOffsetType
loop_jump[256];
png_colorp
global_plte;
png_color_8
global_sbit;
png_byte
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
read_buffer[8],
#endif
global_trns[256];
float
global_gamma;
ChromaticityInfo
global_chrm;
RenderingIntent
global_srgb_intent;
unsigned int
delay,
global_plte_length,
global_trns_length,
global_x_pixels_per_unit,
global_y_pixels_per_unit,
mng_width,
mng_height,
ticks_per_second;
MagickBooleanType
need_blob;
unsigned int
IsPalette,
global_phys_unit_type,
basi_warning,
clon_warning,
dhdr_warning,
jhdr_warning,
magn_warning,
past_warning,
phyg_warning,
phys_warning,
sbit_warning,
show_warning,
mng_type,
write_mng,
write_png_colortype,
write_png_depth,
write_png_compression_level,
write_png_compression_strategy,
write_png_compression_filter,
write_png8,
write_png24,
write_png32,
write_png48,
write_png64;
#ifdef MNG_BASI_SUPPORTED
size_t
basi_width,
basi_height;
unsigned int
basi_depth,
basi_color_type,
basi_compression_method,
basi_filter_type,
basi_interlace_method,
basi_red,
basi_green,
basi_blue,
basi_alpha,
basi_viewable;
#endif
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
PixelPacket
mng_global_bkgd;
/* Added at version 6.6.6-7 */
MagickBooleanType
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
ping_exclude_eXIf,
ping_exclude_EXIF,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tRNS,
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
/* Added at version 6.8.5-7 */
ping_preserve_iCCP,
/* Added at version 6.8.9-9 */
ping_exclude_tIME;
} MngInfo;
#endif /* VER */
/*
Forward declarations.
*/
static MagickBooleanType
WritePNGImage(const ImageInfo *,Image *);
static MagickBooleanType
WriteMNGImage(const ImageInfo *,Image *);
#if defined(JNG_SUPPORTED)
static MagickBooleanType
WriteJNGImage(const ImageInfo *,Image *);
#endif
#if PNG_LIBPNG_VER > 10011
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
static MagickBooleanType
LosslessReduceDepthOK(Image *image)
{
/* Reduce bit depth if it can be reduced losslessly from 16+ to 8.
*
* This is true if the high byte and the next highest byte of
* each sample of the image, the colormap, and the background color
* are equal to each other. We check this by seeing if the samples
* are unchanged when we scale them down to 8 and back up to Quantum.
*
* We don't use the method GetImageDepth() because it doesn't check
* background and doesn't handle PseudoClass specially.
*/
#define QuantumToCharToQuantumEqQuantum(quantum) \
((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum)
MagickBooleanType
ok_to_reduce=MagickFalse;
if (image->depth >= 16)
{
const PixelPacket
*p;
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(image->background_color.red) &&
QuantumToCharToQuantumEqQuantum(image->background_color.green) &&
QuantumToCharToQuantumEqQuantum(image->background_color.blue) ?
MagickTrue : MagickFalse;
if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass)
{
int indx;
for (indx=0; indx < (ssize_t) image->colors; indx++)
{
ok_to_reduce=(
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].red) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].green) &&
QuantumToCharToQuantumEqQuantum(
image->colormap[indx].blue)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
}
}
if ((ok_to_reduce != MagickFalse) &&
(image->storage_class != PseudoClass))
{
ssize_t
y;
register ssize_t
x;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
{
ok_to_reduce = MagickFalse;
break;
}
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
ok_to_reduce=
QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) &&
QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ?
MagickTrue : MagickFalse;
if (ok_to_reduce == MagickFalse)
break;
p++;
}
if (x >= 0)
break;
}
}
if (ok_to_reduce != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OK to reduce PNG bit depth to 8 without loss of info");
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Not OK to reduce PNG bit depth to 8 without loss of info");
}
}
return ok_to_reduce;
}
#endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */
static const char* PngColorTypeToString(const unsigned int color_type)
{
const char
*result = "Unknown";
switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
result = "Gray";
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
result = "Gray+Alpha";
break;
case PNG_COLOR_TYPE_PALETTE:
result = "Palette";
break;
case PNG_COLOR_TYPE_RGB:
result = "RGB";
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
result = "RGB+Alpha";
break;
}
return result;
}
static int
Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent)
{
switch (intent)
{
case PerceptualIntent:
return 0;
case RelativeIntent:
return 1;
case SaturationIntent:
return 2;
case AbsoluteIntent:
return 3;
default:
return -1;
}
}
static RenderingIntent
Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return PerceptualIntent;
case 1:
return RelativeIntent;
case 2:
return SaturationIntent;
case 3:
return AbsoluteIntent;
default:
return UndefinedIntent;
}
}
static const char *
Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent)
{
switch (ping_intent)
{
case 0:
return "Perceptual Intent";
case 1:
return "Relative Intent";
case 2:
return "Saturation Intent";
case 3:
return "Absolute Intent";
default:
return "Undefined Intent";
}
}
static const char *
Magick_ColorType_from_PNG_ColorType(const int ping_colortype)
{
switch (ping_colortype)
{
case 0:
return "Grayscale";
case 2:
return "Truecolor";
case 3:
return "Indexed";
case 4:
return "GrayAlpha";
case 6:
return "RGBA";
default:
return "UndefinedColorType";
}
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif /* MAGICKCORE_PNG_DELEGATE */
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMNG() returns MagickTrue if the image format type, identified by the
% magick string, is MNG.
%
% The format of the IsMNG method is:
%
% MagickBooleanType IsMNG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsMNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJNG() returns MagickTrue if the image format type, identified by the
% magick string, is JNG.
%
% The format of the IsJNG method is:
%
% MagickBooleanType IsJNG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsJNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNG() returns MagickTrue if the image format type, identified by the
% magick string, is PNG.
%
% The format of the IsPNG method is:
%
% MagickBooleanType IsPNG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPNG(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#if (PNG_LIBPNG_VER > 10011)
static size_t WriteBlobMSBULong(Image *image,const size_t value)
{
unsigned char
buffer[4];
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
return((size_t) WriteBlob(image,4,buffer));
}
static void PNGLong(png_bytep p,png_uint_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGsLong(png_bytep p,png_int_32 value)
{
*p++=(png_byte) ((value >> 24) & 0xff);
*p++=(png_byte) ((value >> 16) & 0xff);
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGShort(png_bytep p,png_uint_16 value)
{
*p++=(png_byte) ((value >> 8) & 0xff);
*p++=(png_byte) (value & 0xff);
}
static void PNGType(png_bytep p,const png_byte *type)
{
(void) CopyMagickMemory(p,type,4*sizeof(png_byte));
}
static void LogPNGChunk(MagickBooleanType logging, const png_byte *type,
size_t length)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing %c%c%c%c chunk, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
}
#endif /* PNG_LIBPNG_VER > 10011 */
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNGImage() reads a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image or set of images.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadPNGImage method is:
%
% Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
% To do, more or less in chronological order (as of version 5.5.2,
% November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage):
%
% Get 16-bit cheap transparency working.
%
% (At this point, PNG decoding is supposed to be in full MNG-LC compliance)
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% (At this point, PNG encoding should be in full MNG compliance)
%
% Provide options for choice of background to use when the MNG BACK
% chunk is not present or is not mandatory (i.e., leave transparent,
% user specified, MNG BACK, PNG bKGD)
%
% Implement LOOP/ENDL [done, but could do discretionary loops more
% efficiently by linking in the duplicate frames.].
%
% Decode and act on the MHDR simplicity profile (offer option to reject
% files or attempt to process them anyway when the profile isn't LC or VLC).
%
% Upgrade to full MNG without Delta-PNG.
%
% o BACK [done a while ago except for background image ID]
% o MOVE [done 15 May 1999]
% o CLIP [done 15 May 1999]
% o DISC [done 19 May 1999]
% o SAVE [partially done 19 May 1999 (marks objects frozen)]
% o SEEK [partially done 19 May 1999 (discard function only)]
% o SHOW
% o PAST
% o BASI
% o MNG-level tEXt/iTXt/zTXt
% o pHYg
% o pHYs
% o sBIT
% o bKGD
% o iTXt (wait for libpng implementation).
%
% Use the scene signature to discover when an identical scene is
% being reused, and just point to the original image->exception instead
% of storing another set of pixels. This not specific to MNG
% but could be applied generally.
%
% Upgrade to full MNG with Delta-PNG.
%
% JNG tEXt/iTXt/zTXt
%
% We will not attempt to read files containing the CgBI chunk.
% They are really Xcode files meant for display on the iPhone.
% These are not valid PNG files and it is impossible to recover
% the original PNG from files that have been converted to Xcode-PNG,
% since irretrievable loss of color data has occurred due to the
% use of premultiplied alpha.
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/*
This the function that does the actual reading of data. It is
the same as the one supplied in libpng, except that it receives the
datastream from the ReadBlob() function instead of standard input.
*/
static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) ReadBlob(image,(size_t) length,data);
if (check != length)
{
char
msg[MaxTextExtent];
(void) FormatLocaleString(msg,MaxTextExtent,
"Expected %.20g bytes; found %.20g bytes",(double) length,
(double) check);
png_warning(png_ptr,msg);
png_error(png_ptr,"Read Exception");
}
}
}
#if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \
!defined(PNG_MNG_FEATURES_SUPPORTED)
/* We use mng_get_data() instead of png_get_data() if we have a libpng
* older than libpng-1.0.3a, which was the first to allow the empty
* PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was
* ifdef'ed out. Earlier versions would crash if the bKGD chunk was
* encountered after an empty PLTE, so we have to look ahead for bKGD
* chunks and remove them from the datastream that is passed to libpng,
* and store their contents for later use.
*/
static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
MngInfo
*mng_info;
Image
*image;
png_size_t
check;
register ssize_t
i;
i=0;
mng_info=(MngInfo *) png_get_io_ptr(png_ptr);
image=(Image *) mng_info->image;
while (mng_info->bytes_in_read_buffer && length)
{
data[i]=mng_info->read_buffer[i];
mng_info->bytes_in_read_buffer--;
length--;
i++;
}
if (length != 0)
{
check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data);
if (check != length)
png_error(png_ptr,"Read Exception");
if (length == 4)
{
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 0))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0)
mng_info->found_empty_plte=MagickTrue;
if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0)
{
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
}
}
if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) &&
(data[3] == 1))
{
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->read_buffer[4]=0;
mng_info->bytes_in_read_buffer=4;
if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0)
if (mng_info->found_empty_plte)
{
/*
Skip the bKGD data byte and CRC.
*/
check=(png_size_t)
ReadBlob(image,5,(char *) mng_info->read_buffer);
check=(png_size_t) ReadBlob(image,(size_t) length,
(char *) mng_info->read_buffer);
mng_info->saved_bkgd_index=mng_info->read_buffer[0];
mng_info->have_saved_bkgd_index=MagickTrue;
mng_info->bytes_in_read_buffer=0;
}
}
}
}
}
#endif
static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
Image
*image;
image=(Image *) png_get_io_ptr(png_ptr);
if (length != 0)
{
png_size_t
check;
check=(png_size_t) WriteBlob(image,(size_t) length,data);
if (check != length)
png_error(png_ptr,"WriteBlob Failed");
}
}
static void png_flush_data(png_structp png_ptr)
{
(void) png_ptr;
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
static int PalettesAreEqual(Image *a,Image *b)
{
ssize_t
i;
if ((a == (Image *) NULL) || (b == (Image *) NULL))
return((int) MagickFalse);
if (a->storage_class != PseudoClass || b->storage_class != PseudoClass)
return((int) MagickFalse);
if (a->colors != b->colors)
return((int) MagickFalse);
for (i=0; i < (ssize_t) a->colors; i++)
{
if ((a->colormap[i].red != b->colormap[i].red) ||
(a->colormap[i].green != b->colormap[i].green) ||
(a->colormap[i].blue != b->colormap[i].blue))
return((int) MagickFalse);
}
return((int) MagickTrue);
}
#endif
static void MngInfoDiscardObject(MngInfo *mng_info,int i)
{
if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) &&
mng_info->exists[i] && !mng_info->frozen[i])
{
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
{
if (mng_info->ob[i]->reference_count > 0)
mng_info->ob[i]->reference_count--;
if (mng_info->ob[i]->reference_count == 0)
{
if (mng_info->ob[i]->image != (Image *) NULL)
mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image);
mng_info->ob[i]=DestroyString(mng_info->ob[i]);
}
}
mng_info->ob[i]=(MngBuffer *) NULL;
#endif
mng_info->exists[i]=MagickFalse;
mng_info->invisible[i]=MagickFalse;
mng_info->viewable[i]=MagickFalse;
mng_info->frozen[i]=MagickFalse;
mng_info->x_off[i]=0;
mng_info->y_off[i]=0;
mng_info->object_clip[i].left=0;
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].top=0;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
}
static MngInfo *MngInfoFreeStruct(MngInfo *mng_info)
{
register ssize_t
i;
if (mng_info == (MngInfo *) NULL)
return((MngInfo *) NULL);
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
if (mng_info->global_plte != (png_colorp) NULL)
mng_info->global_plte=(png_colorp)
RelinquishMagickMemory(mng_info->global_plte);
return((MngInfo *) RelinquishMagickMemory(mng_info));
}
static MngBox mng_minimum_box(MngBox box1,MngBox box2)
{
MngBox
box;
box=box1;
if (box.left < box2.left)
box.left=box2.left;
if (box.top < box2.top)
box.top=box2.top;
if (box.right > box2.right)
box.right=box2.right;
if (box.bottom > box2.bottom)
box.bottom=box2.bottom;
return box;
}
static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p)
{
MngBox
box;
/*
Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk.
*/
box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]);
box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]);
box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]);
if (delta_type != 0)
{
box.left+=previous_box.left;
box.right+=previous_box.right;
box.top+=previous_box.top;
box.bottom+=previous_box.bottom;
}
return(box);
}
static MngPair mng_read_pair(MngPair previous_pair,int delta_type,
unsigned char *p)
{
MngPair
pair;
/*
Read two ssize_ts from CLON, MOVE or PAST chunk
*/
pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]);
if (delta_type != 0)
{
pair.a+=previous_pair.a;
pair.b+=previous_pair.b;
}
return(pair);
}
static long mng_get_long(unsigned char *p)
{
return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]));
}
typedef struct _PNGErrorInfo
{
Image
*image;
ExceptionInfo
*exception;
} PNGErrorInfo;
static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message)
{
Image
*image;
image=(Image *) png_get_error_ptr(ping);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message);
(void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError,
message,"`%s'",image->filename);
#if (PNG_LIBPNG_VER < 10500)
/* A warning about deprecated use of jmpbuf here is unavoidable if you
* are building with libpng-1.4.x and can be ignored.
*/
longjmp(ping->jmpbuf,1);
#else
png_longjmp(ping,1);
#endif
}
static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message)
{
Image
*image;
if (LocaleCompare(message, "Missing PLTE before tRNS") == 0)
png_error(ping, message);
image=(Image *) png_get_error_ptr(ping);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message);
(void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning,
message,"`%s'",image->filename);
}
#ifdef PNG_USER_MEM_SUPPORTED
#if PNG_LIBPNG_VER >= 10400
static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size)
#else
static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size)
#endif
{
(void) png_ptr;
return((png_voidp) AcquireMagickMemory((size_t) size));
}
/*
Free a pointer. It is removed from the list at the same time.
*/
static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr)
{
(void) png_ptr;
ptr=RelinquishMagickMemory(ptr);
return((png_free_ptr) NULL);
}
#endif
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static int
Magick_png_read_raw_profile(png_struct *ping,Image *image,
const ImageInfo *image_info, png_textp text,int ii)
{
register ssize_t
i;
register unsigned char
*dp;
register png_charp
sp;
png_uint_32
length,
nibbles;
StringInfo
*profile;
const unsigned char
unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12,
13,14,15};
sp=text[ii].text+1;
/* look for newline */
while (*sp != '\n')
sp++;
/* look for length */
while (*sp == '\0' || *sp == ' ' || *sp == '\n')
sp++;
length=(png_uint_32) StringToLong(sp);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu",(unsigned long) length);
while (*sp != ' ' && *sp != '\n')
sp++;
/* allocate space */
if (length == 0)
{
png_warning(ping,"invalid profile length");
return(MagickFalse);
}
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "unable to copy profile");
return(MagickFalse);
}
/* copy profile, skipping white space and column 1 "=" signs */
dp=GetStringInfoDatum(profile);
nibbles=length*2;
for (i=0; i < (ssize_t) nibbles; i++)
{
while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f')
{
if (*sp == '\0')
{
png_warning(ping, "ran out of profile data");
return(MagickFalse);
}
sp++;
}
if (i%2 == 0)
*dp=(unsigned char) (16*unhex[(int) *sp++]);
else
(*dp++)+=unhex[(int) *sp++];
}
/*
We have already read "Raw profile type.
*/
(void) SetImageProfile(image,&text[ii].key[17],profile);
profile=DestroyStringInfo(profile);
if (image_info->verbose)
(void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]);
return MagickTrue;
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk)
{
Image
*image;
/* The unknown chunk structure contains the chunk data:
png_byte name[5];
png_byte *data;
png_size_t size;
Note that libpng has already taken care of the CRC handling.
*/
LogMagickEvent(CoderEvent,GetMagickModule(),
" read_user_chunk: found %c%c%c%c chunk",
chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]);
if (chunk->name[0] == 101 &&
(chunk->name[1] == 88 || chunk->name[1] == 120 ) &&
chunk->name[2] == 73 &&
chunk-> name[3] == 102)
{
/* process eXIf or exIf chunk */
PNGErrorInfo
*error_info;
StringInfo
*profile;
unsigned char
*p;
png_byte
*s;
int
i;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" recognized eXIf|exIf chunk");
image=(Image *) png_get_user_chunk_ptr(ping);
error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
profile=BlobToStringInfo((const void *) NULL,chunk->size+6);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(error_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1);
}
p=GetStringInfoDatum(profile);
/* Initialize profile with "Exif\0\0" */
*p++ ='E';
*p++ ='x';
*p++ ='i';
*p++ ='f';
*p++ ='\0';
*p++ ='\0';
/* copy chunk->data to profile */
s=chunk->data;
for (i=0; i < (ssize_t) chunk->size; i++)
*p++ = *s++;
(void) SetImageProfile(image,"exif",profile);
return(1);
}
/* vpAg (deprecated, replaced by caNv) */
if (chunk->name[0] == 118 &&
chunk->name[1] == 112 &&
chunk->name[2] == 65 &&
chunk->name[3] == 103)
{
/* recognized vpAg */
if (chunk->size != 9)
return(-1); /* Error return */
if (chunk->data[8] != 0)
return(0); /* ImageMagick requires pixel units */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) ((chunk->data[0] << 24) |
(chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);
image->page.height=(size_t) ((chunk->data[4] << 24) |
(chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);
return(1);
}
/* caNv */
if (chunk->name[0] == 99 &&
chunk->name[1] == 97 &&
chunk->name[2] == 78 &&
chunk->name[3] == 118)
{
/* recognized caNv */
if (chunk->size != 16)
return(-1); /* Error return */
image=(Image *) png_get_user_chunk_ptr(ping);
image->page.width=(size_t) ((chunk->data[0] << 24) |
(chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);
image->page.height=(size_t) ((chunk->data[4] << 24) |
(chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);
image->page.x=(size_t) ((chunk->data[8] << 24) |
(chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]);
image->page.y=(size_t) ((chunk->data[12] << 24) |
(chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]);
/* Return one of the following: */
/* return(-n); chunk had an error */
/* return(0); did not recognize */
/* return(n); success */
return(1);
}
return(0); /* Did not recognize */
}
#endif
#if defined(PNG_tIME_SUPPORTED)
static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info)
{
png_timep
time;
if (png_get_tIME(ping,info,&time))
{
char
timestamp[21];
FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ",
time->year,time->month,time->day,time->hour,time->minute,time->second);
SetImageProperty(image,"png:tIME",timestamp);
}
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file
% (minus the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the ReadOnePNGImage method is:
%
% Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
/* Read one PNG image */
/* To do: Read the tEXt/Creation Time chunk into the date:create property */
Image
*image;
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
int
intent, /* "PNG Rendering intent", which is ICC intent + 1 */
num_raw_profiles,
num_text,
num_text_total,
num_passes,
number_colors,
pass,
ping_bit_depth,
ping_color_type,
ping_file_depth,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans,
unit_type;
double
file_gamma;
LongPixelPacket
transparent_color;
MagickBooleanType
logging,
ping_found_cHRM,
ping_found_gAMA,
ping_found_iCCP,
ping_found_sRGB,
ping_found_sRGB_cHRM,
ping_preserve_iCCP,
status;
MemoryInfo
*volatile pixel_info;
png_bytep
ping_trans_alpha;
png_color_16p
ping_background,
ping_trans_color;
png_info
*end_info,
*ping_info;
png_struct
*ping;
png_textp
text;
png_uint_32
ping_height,
ping_width,
x_resolution,
y_resolution;
ssize_t
ping_rowbytes,
y;
register unsigned char
*p;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
size_t
length,
row_offset;
ssize_t
j;
unsigned char
*ping_pixels;
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
png_byte unused_chunks[]=
{
104, 73, 83, 84, (png_byte) '\0', /* hIST */
105, 84, 88, 116, (png_byte) '\0', /* iTXt */
112, 67, 65, 76, (png_byte) '\0', /* pCAL */
115, 67, 65, 76, (png_byte) '\0', /* sCAL */
115, 80, 76, 84, (png_byte) '\0', /* sPLT */
#if !defined(PNG_tIME_SUPPORTED)
116, 73, 77, 69, (png_byte) '\0', /* tIME */
#endif
#ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */
/* ignore the APNG chunks */
97, 99, 84, 76, (png_byte) '\0', /* acTL */
102, 99, 84, 76, (png_byte) '\0', /* fcTL */
102, 100, 65, 84, (png_byte) '\0', /* fdAT */
#endif
};
#endif
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,32);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,32);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOnePNGImage()\n"
" IM version = %s\n"
" Libpng version = %s",
im_vers, libpng_vers);
if (logging != MagickFalse)
{
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
#if (PNG_LIBPNG_VER >= 10400)
# ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */
if (image_info->verbose)
{
printf("Your PNG library (libpng-%s) is an old beta version.\n",
PNG_LIBPNG_VER_STRING);
printf("Please update it.\n");
}
# endif
#endif
image=mng_info->image;
if (logging != MagickFalse)
{
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" Before reading:\n"
" image->matte=%d\n"
" image->rendering_intent=%d\n"
" image->colorspace=%d\n"
" image->gamma=%f",
(int) image->matte, (int) image->rendering_intent,
(int) image->colorspace, image->gamma);
}
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent);
/* Set to an out-of-range color unless tRNS chunk is present */
transparent_color.red=65537;
transparent_color.green=65537;
transparent_color.blue=65537;
transparent_color.opacity=65537;
number_colors=0;
num_text = 0;
num_text_total = 0;
num_raw_profiles = 0;
ping_found_cHRM = MagickFalse;
ping_found_gAMA = MagickFalse;
ping_found_iCCP = MagickFalse;
ping_found_sRGB = MagickFalse;
ping_found_sRGB_cHRM = MagickFalse;
ping_preserve_iCCP = MagickFalse;
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image,
MagickPNGErrorHandler,MagickPNGWarningHandler, NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
end_info=png_create_info_struct(ping);
if (end_info == (png_info *) NULL)
{
png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG image is corrupt.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() with error.");
if (image != (Image *) NULL)
InheritException(exception,&image->exception);
return(GetFirstImageInList(image));
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for reading.
*/
mng_info->image_found++;
png_set_sig_bytes(ping,8);
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED)
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
png_set_read_fn(ping,image,png_get_data);
#else
#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED)
png_permit_empty_plte(ping,MagickTrue);
png_set_read_fn(ping,image,png_get_data);
#else
mng_info->image=image;
mng_info->bytes_in_read_buffer=0;
mng_info->found_empty_plte=MagickFalse;
mng_info->have_saved_bkgd_index=MagickFalse;
png_set_read_fn(ping,mng_info,mng_get_data);
#endif
#endif
}
else
png_set_read_fn(ping,image,png_get_data);
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember("ICC",value) == MagickFalse)
{
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
ping_preserve_iCCP=MagickTrue;
#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)
/* Don't let libpng check for ICC/sRGB profile because we're going
* to do that anyway. This feature was added at libpng-1.6.12.
* If logging, go ahead and check and issue a warning as appropriate.
*/
if (logging == MagickFalse)
png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
else
{
/* Ignore the iCCP chunk */
png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1);
}
#endif
}
#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
/* Ignore unused chunks and all unknown chunks except for exIf, caNv,
and vpAg */
# if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */
png_set_keep_unknown_chunks(ping, 2, NULL, 0);
# else
png_set_keep_unknown_chunks(ping, 1, NULL, 0);
# endif
png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1);
png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1);
png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1);
png_set_keep_unknown_chunks(ping, 1, unused_chunks,
(int)sizeof(unused_chunks)/5);
/* Callback for other unknown chunks */
png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
#if (PNG_LIBPNG_VER >= 10400)
/* Limit the size of the chunk storage cache used for sPLT, text,
* and unknown chunks.
*/
png_set_chunk_cache_max(ping, 32767);
#endif
#endif
#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature */
png_set_check_for_invalid_index (ping, 0);
#endif
#if (PNG_LIBPNG_VER < 10400)
# if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \
(PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__)
/* Disable thread-unsafe features of pnggccrd */
if (png_access_version_number() >= 10200)
{
png_uint_32 mmx_disable_mask=0;
png_uint_32 asm_flags;
mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
| PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
| PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
| PNG_ASM_FLAG_MMX_READ_FILTER_PAETH );
asm_flags=png_get_asm_flags(ping);
png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask);
}
# endif
#endif
png_read_info(ping,ping_info);
/* Read and check IHDR chunk data */
png_get_IHDR(ping,ping_info,&ping_width,&ping_height,
&ping_bit_depth,&ping_color_type,
&ping_interlace_method,&ping_compression_method,
&ping_filter_method);
ping_file_depth = ping_bit_depth;
/* Swap bytes if requested */
if (ping_file_depth == 16)
{
const char
*value;
value=GetImageOption(image_info,"png:swap-bytes");
if (value == NULL)
value=GetImageArtifact(image,"png:swap-bytes");
if (value != NULL)
png_set_swap(ping);
}
/* Save bit-depth and color-type in case we later want to write a PNG00 */
{
char
msg[MaxTextExtent];
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type);
(void) SetImageProperty(image,"png:IHDR.color-type-orig",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth);
(void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg);
}
(void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans,
&ping_trans_color);
(void) png_get_bKGD(ping, ping_info, &ping_background);
if (ping_bit_depth < 8)
{
png_set_packing(ping);
ping_bit_depth = 8;
}
image->depth=ping_bit_depth;
image->depth=GetImageQuantumDepth(image,MagickFalse);
image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace;
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
image->rendering_intent=UndefinedIntent;
intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent);
(void) ResetMagickMemory(&image->chromaticity,0,
sizeof(image->chromaticity));
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG width: %.20g, height: %.20g\n"
" PNG color_type: %d, bit_depth: %d\n"
" PNG compression_method: %d\n"
" PNG interlace_method: %d, filter_method: %d",
(double) ping_width, (double) ping_height,
ping_color_type, ping_bit_depth,
ping_compression_method,
ping_interlace_method,ping_filter_method);
}
if (png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_gAMA))
{
ping_found_gAMA=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG gAMA chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
ping_found_cHRM=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG cHRM chunk.");
}
if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
ping_found_sRGB=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG sRGB chunk.");
}
#ifdef PNG_READ_iCCP_SUPPORTED
if (ping_found_iCCP !=MagickTrue &&
ping_found_sRGB != MagickTrue &&
png_get_valid(ping,ping_info, PNG_INFO_iCCP))
{
ping_found_iCCP=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found PNG iCCP chunk.");
}
if (png_get_valid(ping,ping_info,PNG_INFO_iCCP))
{
int
compression;
#if (PNG_LIBPNG_VER < 10500)
png_charp
info;
#else
png_bytep
info;
#endif
png_charp
name;
png_uint_32
profile_length;
(void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info,
&profile_length);
if (profile_length != 0)
{
StringInfo
*profile;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG iCCP chunk.");
profile=BlobToStringInfo(info,profile_length);
if (profile == (StringInfo *) NULL)
{
png_warning(ping, "ICC profile is NULL");
profile=DestroyStringInfo(profile);
}
else
{
if (ping_preserve_iCCP == MagickFalse)
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
break;
}
}
}
if (sRGB_info[icheck].len == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
(void) SetImageProfile(image,"icc",profile);
}
}
else /* Preserve-iCCP */
{
(void) SetImageProfile(image,"icc",profile);
}
profile=DestroyStringInfo(profile);
}
}
}
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
{
if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info,
PNG_INFO_sRGB))
{
if (png_get_sRGB(ping,ping_info,&intent))
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent (intent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG sRGB chunk: rendering_intent: %d",intent);
}
}
else if (mng_info->have_global_srgb)
{
if (image->rendering_intent == UndefinedIntent)
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent
(mng_info->global_srgb_intent);
}
}
#endif
{
if (!png_get_gAMA(ping,ping_info,&file_gamma))
if (mng_info->have_global_gama)
png_set_gAMA(ping,ping_info,mng_info->global_gamma);
if (png_get_gAMA(ping,ping_info,&file_gamma))
{
image->gamma=(float) file_gamma;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG gAMA chunk: gamma: %f",file_gamma);
}
}
if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
if (mng_info->have_global_chrm != MagickFalse)
{
(void) png_set_cHRM(ping,ping_info,
mng_info->global_chrm.white_point.x,
mng_info->global_chrm.white_point.y,
mng_info->global_chrm.red_primary.x,
mng_info->global_chrm.red_primary.y,
mng_info->global_chrm.green_primary.x,
mng_info->global_chrm.green_primary.y,
mng_info->global_chrm.blue_primary.x,
mng_info->global_chrm.blue_primary.y);
}
}
if (png_get_valid(ping,ping_info,PNG_INFO_cHRM))
{
(void) png_get_cHRM(ping,ping_info,
&image->chromaticity.white_point.x,
&image->chromaticity.white_point.y,
&image->chromaticity.red_primary.x,
&image->chromaticity.red_primary.y,
&image->chromaticity.green_primary.x,
&image->chromaticity.green_primary.y,
&image->chromaticity.blue_primary.x,
&image->chromaticity.blue_primary.y);
ping_found_cHRM=MagickTrue;
if (image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f)
ping_found_sRGB_cHRM=MagickTrue;
}
if (image->rendering_intent != UndefinedIntent)
{
if (ping_found_sRGB != MagickTrue &&
(ping_found_gAMA != MagickTrue ||
(image->gamma > .45 && image->gamma < .46)) &&
(ping_found_cHRM != MagickTrue ||
ping_found_sRGB_cHRM != MagickFalse) &&
ping_found_iCCP != MagickTrue)
{
png_set_sRGB(ping,ping_info,
Magick_RenderingIntent_to_PNG_RenderingIntent
(image->rendering_intent));
file_gamma=1.000f/2.200f;
ping_found_sRGB=MagickTrue;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting sRGB as if in input");
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info);
image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info);
if (logging != MagickFalse)
if (image->page.x || image->page.y)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double)
image->page.x,(double) image->page.y);
}
#endif
#if defined(PNG_pHYs_SUPPORTED)
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
if (mng_info->have_global_phys)
{
png_set_pHYs(ping,ping_info,
mng_info->global_x_pixels_per_unit,
mng_info->global_y_pixels_per_unit,
mng_info->global_phys_unit_type);
}
}
x_resolution=0;
y_resolution=0;
unit_type=0;
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
/*
Set image resolution.
*/
(void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution,
&unit_type);
image->x_resolution=(double) x_resolution;
image->y_resolution=(double) y_resolution;
if (unit_type == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=(double) x_resolution/100.0;
image->y_resolution=(double) y_resolution/100.0;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) x_resolution,(double) y_resolution,unit_type);
}
#endif
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
if ((number_colors == 0) &&
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE))
{
if (mng_info->global_plte_length)
{
png_set_PLTE(ping,ping_info,mng_info->global_plte,
(int) mng_info->global_plte_length);
if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS))
if (mng_info->global_trns_length)
{
if (mng_info->global_trns_length >
mng_info->global_plte_length)
{
png_warning(ping,
"global tRNS has more entries than global PLTE");
}
else
{
png_set_tRNS(ping,ping_info,mng_info->global_trns,
(int) mng_info->global_trns_length,NULL);
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
mng_info->have_saved_bkgd_index ||
#endif
png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
png_color_16
background;
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
if (mng_info->have_saved_bkgd_index)
background.index=mng_info->saved_bkgd_index;
#endif
if (png_get_valid(ping, ping_info, PNG_INFO_bKGD))
background.index=ping_background->index;
background.red=(png_uint_16)
mng_info->global_plte[background.index].red;
background.green=(png_uint_16)
mng_info->global_plte[background.index].green;
background.blue=(png_uint_16)
mng_info->global_plte[background.index].blue;
background.gray=(png_uint_16)
mng_info->global_plte[background.index].green;
png_set_bKGD(ping,ping_info,&background);
}
#endif
}
else
png_error(ping,"No global PLTE in file");
}
}
#ifdef PNG_READ_bKGD_SUPPORTED
if (mng_info->have_global_bkgd &&
(!png_get_valid(ping,ping_info,PNG_INFO_bKGD)))
image->background_color=mng_info->mng_global_bkgd;
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
unsigned int
bkgd_scale;
/* Set image background color.
* Scale background components to 16-bit, then scale
* to quantum depth
*/
bkgd_scale = 1;
if (ping_file_depth == 1)
bkgd_scale = 255;
else if (ping_file_depth == 2)
bkgd_scale = 85;
else if (ping_file_depth == 4)
bkgd_scale = 17;
if (ping_file_depth <= 8)
bkgd_scale *= 257;
ping_background->red *= bkgd_scale;
ping_background->green *= bkgd_scale;
ping_background->blue *= bkgd_scale;
if (logging != MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n"
" bkgd_scale=%d. ping_background=(%d,%d,%d).",
ping_background->red,ping_background->green,
ping_background->blue,
bkgd_scale,ping_background->red,
ping_background->green,ping_background->blue);
}
image->background_color.red=
ScaleShortToQuantum(ping_background->red);
image->background_color.green=
ScaleShortToQuantum(ping_background->green);
image->background_color.blue=
ScaleShortToQuantum(ping_background->blue);
image->background_color.opacity=OpaqueOpacity;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->background_color=(%.20g,%.20g,%.20g).",
(double) image->background_color.red,
(double) image->background_color.green,
(double) image->background_color.blue);
}
#endif /* PNG_READ_bKGD_SUPPORTED */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
/*
Image has a tRNS chunk.
*/
int
max_sample;
size_t
one=1;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG tRNS chunk.");
max_sample = (int) ((one << ping_file_depth) - 1);
if ((ping_color_type == PNG_COLOR_TYPE_GRAY &&
(int)ping_trans_color->gray > max_sample) ||
(ping_color_type == PNG_COLOR_TYPE_RGB &&
((int)ping_trans_color->red > max_sample ||
(int)ping_trans_color->green > max_sample ||
(int)ping_trans_color->blue > max_sample)))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Ignoring PNG tRNS chunk with out-of-range sample.");
png_free_data(ping, ping_info, PNG_FREE_TRNS, 0);
png_set_invalid(ping,ping_info,PNG_INFO_tRNS);
image->matte=MagickFalse;
}
else
{
int
scale_to_short;
scale_to_short = 65535L/((1UL << ping_file_depth)-1);
/* Scale transparent_color to short */
transparent_color.red= scale_to_short*ping_trans_color->red;
transparent_color.green= scale_to_short*ping_trans_color->green;
transparent_color.blue= scale_to_short*ping_trans_color->blue;
transparent_color.opacity= scale_to_short*ping_trans_color->gray;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Raw tRNS graylevel = %d, scaled graylevel = %d.",
ping_trans_color->gray,transparent_color.opacity);
}
transparent_color.red=transparent_color.opacity;
transparent_color.green=transparent_color.opacity;
transparent_color.blue=transparent_color.opacity;
}
}
}
#if defined(PNG_READ_sBIT_SUPPORTED)
if (mng_info->have_global_sbit)
{
if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT))
png_set_sBIT(ping,ping_info,&mng_info->global_sbit);
}
#endif
num_passes=png_set_interlace_handling(ping);
png_read_update_info(ping,ping_info);
ping_rowbytes=png_get_rowbytes(ping,ping_info);
/*
Initialize image structure.
*/
mng_info->image_box.left=0;
mng_info->image_box.right=(ssize_t) ping_width;
mng_info->image_box.top=0;
mng_info->image_box.bottom=(ssize_t) ping_height;
if (mng_info->mng_type == 0)
{
mng_info->mng_width=ping_width;
mng_info->mng_height=ping_height;
mng_info->frame=mng_info->image_box;
mng_info->clip=mng_info->image_box;
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
image->compression=ZipCompression;
image->columns=ping_width;
image->rows=ping_height;
if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
((int) ping_bit_depth < 16 &&
(int) ping_color_type == PNG_COLOR_TYPE_GRAY))
{
size_t
one;
image->storage_class=PseudoClass;
one=1;
image->colors=one << ping_file_depth;
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->colors > 256)
image->colors=256;
#else
if (image->colors > 65536L)
image->colors=65536L;
#endif
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
image->colors=(size_t) number_colors;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG PLTE chunk: number_colors: %d.",number_colors);
}
}
if (image->storage_class == PseudoClass)
{
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
png_error(ping,"Memory allocation failed");
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
png_colorp
palette;
(void) png_get_PLTE(ping,ping_info,&palette,&number_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(palette[i].red);
image->colormap[i].green=ScaleCharToQuantum(palette[i].green);
image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue);
}
for ( ; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=0;
image->colormap[i].green=0;
image->colormap[i].blue=0;
}
}
else
{
Quantum
scale;
scale = 65535/((1UL << ping_file_depth)-1);
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
scale = ScaleShortToQuantum(scale);
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(Quantum) (i*scale);
image->colormap[i].green=(Quantum) (i*scale);
image->colormap[i].blue=(Quantum) (i*scale);
}
}
}
/* Set some properties for reporting by "identify" */
{
char
msg[MaxTextExtent];
/* encode ping_width, ping_height, ping_file_depth, ping_color_type,
ping_interlace_method in value */
(void) FormatLocaleString(msg,MaxTextExtent,
"%d, %d",(int) ping_width, (int) ping_height);
(void) SetImageProperty(image,"png:IHDR.width,height",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth);
(void) SetImageProperty(image,"png:IHDR.bit_depth",msg);
(void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)",
(int) ping_color_type,
Magick_ColorType_from_PNG_ColorType((int)ping_color_type));
(void) SetImageProperty(image,"png:IHDR.color_type",msg);
if (ping_interlace_method == 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)",
(int) ping_interlace_method);
}
else if (ping_interlace_method == 1)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)",
(int) ping_interlace_method);
}
else
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)",
(int) ping_interlace_method);
}
(void) SetImageProperty(image,"png:IHDR.interlace_method",msg);
if (number_colors != 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%d",
(int) number_colors);
(void) SetImageProperty(image,"png:PLTE.number_colors",msg);
}
}
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,ping_info);
#endif
/*
Read image scanlines.
*/
if (image->delay != 0)
mng_info->scenes_found++;
if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || (
(image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t)
(image_info->first_scene+image_info->number_scenes))))
{
/* This happens later in non-ping decodes */
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
image->storage_class=DirectClass;
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping PNG image data for scene %.20g",(double)
mng_info->scenes_found-1);
png_destroy_read_struct(&ping,&ping_info,&end_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage().");
return(image);
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG IDAT chunk(s)");
if (num_passes > 1)
pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes*
sizeof(*ping_pixels));
else
pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Memory allocation failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting PNG pixels to pixel packets");
/*
Convert PNG pixels to pixel packets.
*/
{
MagickBooleanType
found_transparent_pixel;
found_transparent_pixel=MagickFalse;
if (image->storage_class == DirectClass)
{
QuantumInfo
*quantum_info;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Failed to allocate quantum_info");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert image to DirectClass pixel packets.
*/
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
for (y=0; y < (ssize_t) image->rows; y++)
{
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
else
{
if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayAlphaQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBAQuantum,ping_pixels+row_offset,exception);
else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
IndexQuantum,ping_pixels+row_offset,exception);
else /* ping_color_type == PNG_COLOR_TYPE_RGB */
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
RGBQuantum,ping_pixels+row_offset,exception);
}
if (found_transparent_pixel == MagickFalse)
{
/* Is there a transparent pixel in the row? */
if (y== 0 && logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Looking for cheap transparent pixel");
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if ((ping_color_type == PNG_COLOR_TYPE_RGBA ||
ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) &&
(GetPixelOpacity(q) != OpaqueOpacity))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
if ((ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_GRAY) &&
(ScaleQuantumToShort(GetPixelRed(q))
== transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(q))
== transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(q))
== transparent_color.blue))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ...got one.");
found_transparent_pixel = MagickTrue;
break;
}
q++;
}
}
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,
(MagickOffsetType) y, image->rows);
if (status == MagickFalse)
break;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
else /* image->storage_class != DirectClass */
for (pass=0; pass < num_passes; pass++)
{
Quantum
*quantum_scanline;
register Quantum
*r;
/*
Convert grayscale image to PseudoClass pixel packets.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Converting grayscale pixels to pixel packets");
image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ?
MagickTrue : MagickFalse;
quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns,
(image->matte ? 2 : 1)*sizeof(*quantum_scanline));
if (quantum_scanline == (Quantum *) NULL)
png_error(ping,"Memory allocation failed");
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
alpha;
if (num_passes > 1)
row_offset=ping_rowbytes*y;
else
row_offset=0;
png_read_row(ping,ping_pixels+row_offset,NULL);
if (pass < num_passes-1)
continue;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=ping_pixels+row_offset;
r=quantum_scanline;
switch (ping_bit_depth)
{
case 8:
{
if (ping_color_type == 4)
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
*r++=*p++;
/* In image.h, OpaqueOpacity is 0
* TransparentOpacity is QuantumRange
* In a PNG datastream, Opaque is QuantumRange
* and Transparent is 0.
*/
alpha=ScaleCharToQuantum((unsigned char)*p++);
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
q++;
}
else
for (x=(ssize_t) image->columns-1; x >= 0; x--)
*r++=*p++;
break;
}
case 16:
{
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
#if (MAGICKCORE_QUANTUM_DEPTH >= 16)
size_t
quantum;
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
*r=ScaleShortToQuantum(quantum);
r++;
if (ping_color_type == 4)
{
if (image->colors > 256)
quantum=((*p++) << 8);
else
quantum=0;
quantum|=(*p++);
alpha=ScaleShortToQuantum(quantum);
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
q++;
}
#else /* MAGICKCORE_QUANTUM_DEPTH == 8 */
*r++=(*p++);
p++; /* strip low byte */
if (ping_color_type == 4)
{
alpha=*p++;
SetPixelAlpha(q,alpha);
if (alpha != QuantumRange-OpaqueOpacity)
found_transparent_pixel = MagickTrue;
p++;
q++;
}
#endif
}
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=quantum_scanline;
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*r++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (num_passes == 1)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (num_passes != 1)
{
status=SetImageProgress(image,LoadImageTag,pass,num_passes);
if (status == MagickFalse)
break;
}
quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline);
}
image->matte=found_transparent_pixel;
if (logging != MagickFalse)
{
if (found_transparent_pixel != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found transparent pixel");
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No transparent pixel was found");
ping_color_type&=0x03;
}
}
}
if (image->storage_class == PseudoClass)
{
MagickBooleanType
matte;
matte=image->matte;
image->matte=MagickFalse;
(void) SyncImage(image);
image->matte=matte;
}
png_read_end(ping,end_info);
if (image_info->number_scenes != 0 && mng_info->scenes_found-1 <
(ssize_t) image_info->first_scene && image->delay != 0)
{
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
image->colors=2;
(void) SetImageBackgroundColor(image);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage() early.");
return(image);
}
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
{
ClassType
storage_class;
/*
Image has a transparent background.
*/
storage_class=image->storage_class;
image->matte=MagickTrue;
/* Balfour fix from imagemagick discourse server, 5 Feb 2010 */
if (storage_class == PseudoClass)
{
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
for (x=0; x < ping_num_trans; x++)
{
image->colormap[x].opacity =
ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x]));
}
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
for (x=0; x < (int) image->colors; x++)
{
if (ScaleQuantumToShort(image->colormap[x].red) ==
transparent_color.opacity)
{
image->colormap[x].opacity = (Quantum) TransparentOpacity;
}
}
}
(void) SyncImage(image);
}
#if 1 /* Should have already been done above, but glennrp problem P10
* needs this.
*/
else
{
for (y=0; y < (ssize_t) image->rows; y++)
{
image->storage_class=storage_class;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
/* Caution: on a Q8 build, this does not distinguish between
* 16-bit colors that differ only in the low byte
*/
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
if (ScaleQuantumToShort(GetPixelRed(q))
== transparent_color.red &&
ScaleQuantumToShort(GetPixelGreen(q))
== transparent_color.green &&
ScaleQuantumToShort(GetPixelBlue(q))
== transparent_color.blue)
{
SetPixelOpacity(q,TransparentOpacity);
}
#if 0 /* I have not found a case where this is needed. */
else
{
SetPixelOpacity(q)=(Quantum) OpaqueOpacity;
}
#endif
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
image->storage_class=DirectClass;
}
if ((ping_color_type == PNG_COLOR_TYPE_GRAY) ||
(ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
double
image_gamma = image->gamma;
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->gamma=%f",(float) image_gamma);
if (image_gamma > 0.75)
{
/* Set image->rendering_intent to Undefined,
* image->colorspace to GRAY, and reset image->chromaticity.
*/
image->intensity = Rec709LuminancePixelIntensityMethod;
SetImageColorspace(image,GRAYColorspace);
}
else
{
RenderingIntent
save_rendering_intent = image->rendering_intent;
ChromaticityInfo
save_chromaticity = image->chromaticity;
SetImageColorspace(image,GRAYColorspace);
image->rendering_intent = save_rendering_intent;
image->chromaticity = save_chromaticity;
}
image->gamma = image_gamma;
}
(void)LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colorspace=%d",(int) image->colorspace);
for (j = 0; j < 2; j++)
{
if (j == 0)
status = png_get_text(ping,ping_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
else
status = png_get_text(ping,end_info,&text,&num_text) != 0 ?
MagickTrue : MagickFalse;
if (status != MagickFalse)
for (i=0; i < (ssize_t) num_text; i++)
{
/* Check for a profile */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading PNG text chunk");
if (strlen(text[i].key) > 16 &&
memcmp(text[i].key, "Raw profile type ",17) == 0)
{
const char
*value;
value=GetImageOption(image_info,"profile:skip");
if (IsOptionMember(text[i].key+17,value) == MagickFalse)
{
(void) Magick_png_read_raw_profile(ping,image,image_info,text,
(int) i);
num_raw_profiles++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Read raw profile %s",text[i].key+17);
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping raw profile %s",text[i].key+17);
}
}
else
{
char
*value;
length=text[i].text_length;
value=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*value));
if (value == (char *) NULL)
png_error(ping,"Memory allocation failed");
*value='\0';
(void) ConcatenateMagickString(value,text[i].text,length+2);
/* Don't save "density" or "units" property if we have a pHYs
* chunk
*/
if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) ||
(LocaleCompare(text[i].key,"density") != 0 &&
LocaleCompare(text[i].key,"units") != 0))
(void) SetImageProperty(image,text[i].key,value);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" length: %lu\n"
" Keyword: %s",
(unsigned long) length,
text[i].key);
}
value=DestroyString(value);
}
}
num_text_total += num_text;
}
#ifdef MNG_OBJECT_BUFFERS
/*
Store the object if necessary.
*/
if (object_id && !mng_info->frozen[object_id])
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
{
/*
create a new object buffer.
*/
mng_info->ob[object_id]=(MngBuffer *)
AcquireMagickMemory(sizeof(MngBuffer));
if (mng_info->ob[object_id] != (MngBuffer *) NULL)
{
mng_info->ob[object_id]->image=(Image *) NULL;
mng_info->ob[object_id]->reference_count=1;
}
}
if ((mng_info->ob[object_id] == (MngBuffer *) NULL) ||
mng_info->ob[object_id]->frozen)
{
if (mng_info->ob[object_id] == (MngBuffer *) NULL)
png_error(ping,"Memory allocation failed");
if (mng_info->ob[object_id]->frozen)
png_error(ping,"Cannot overwrite frozen MNG object buffer");
}
else
{
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image=DestroyImage
(mng_info->ob[object_id]->image);
mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue,
&image->exception);
if (mng_info->ob[object_id]->image != (Image *) NULL)
mng_info->ob[object_id]->image->file=(FILE *) NULL;
else
png_error(ping, "Cloning image for object buffer failed");
if (ping_width > 250000L || ping_height > 250000L)
png_error(ping,"PNG Image dimensions are too large.");
mng_info->ob[object_id]->width=ping_width;
mng_info->ob[object_id]->height=ping_height;
mng_info->ob[object_id]->color_type=ping_color_type;
mng_info->ob[object_id]->sample_depth=ping_bit_depth;
mng_info->ob[object_id]->interlace_method=ping_interlace_method;
mng_info->ob[object_id]->compression_method=
ping_compression_method;
mng_info->ob[object_id]->filter_method=ping_filter_method;
if (png_get_valid(ping,ping_info,PNG_INFO_PLTE))
{
png_colorp
plte;
/*
Copy the PLTE to the object buffer.
*/
png_get_PLTE(ping,ping_info,&plte,&number_colors);
mng_info->ob[object_id]->plte_length=number_colors;
for (i=0; i < number_colors; i++)
{
mng_info->ob[object_id]->plte[i]=plte[i];
}
}
else
mng_info->ob[object_id]->plte_length=0;
}
}
#endif
/* Set image->matte to MagickTrue if the input colortype supports
* alpha or if a valid tRNS chunk is present, no matter whether there
* is actual transparency present.
*/
image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ||
((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) ||
(png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ?
MagickTrue : MagickFalse;
#if 0 /* I'm not sure what's wrong here but it does not work. */
if (image->matte != MagickFalse)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
(void) SetImageType(image,GrayscaleMatteType);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteMatteType);
else
(void) SetImageType(image,TrueColorMatteType);
}
else
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
(void) SetImageType(image,GrayscaleType);
else if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
(void) SetImageType(image,PaletteType);
else
(void) SetImageType(image,TrueColorType);
}
#endif
/* Set more properties for identify to retrieve */
{
char
msg[MaxTextExtent];
if (num_text_total != 0)
{
/* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */
(void) FormatLocaleString(msg,MaxTextExtent,
"%d tEXt/zTXt/iTXt chunks were found", num_text_total);
(void) SetImageProperty(image,"png:text",msg);
}
if (num_raw_profiles != 0)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"%d were found", num_raw_profiles);
(void) SetImageProperty(image,"png:text-encoded profiles",msg);
}
/* cHRM chunk: */
if (ping_found_cHRM != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found (see Chromaticity, above)");
(void) SetImageProperty(image,"png:cHRM",msg);
}
/* bKGD chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_bKGD))
{
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found (see Background color, above)");
(void) SetImageProperty(image,"png:bKGD",msg);
}
(void) FormatLocaleString(msg,MaxTextExtent,"%s",
"chunk was found");
/* iCCP chunk: */
if (ping_found_iCCP != MagickFalse)
(void) SetImageProperty(image,"png:iCCP",msg);
if (png_get_valid(ping,ping_info,PNG_INFO_tRNS))
(void) SetImageProperty(image,"png:tRNS",msg);
#if defined(PNG_sRGB_SUPPORTED)
/* sRGB chunk: */
if (ping_found_sRGB != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"intent=%d (%s)",
(int) intent,
Magick_RenderingIntentString_from_PNG_RenderingIntent(intent));
(void) SetImageProperty(image,"png:sRGB",msg);
}
#endif
/* gAMA chunk: */
if (ping_found_gAMA != MagickFalse)
{
(void) FormatLocaleString(msg,MaxTextExtent,
"gamma=%.8g (See Gamma, above)", file_gamma);
(void) SetImageProperty(image,"png:gAMA",msg);
}
#if defined(PNG_pHYs_SUPPORTED)
/* pHYs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_pHYs))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"x_res=%.10g, y_res=%.10g, units=%d",
(double) x_resolution,(double) y_resolution, unit_type);
(void) SetImageProperty(image,"png:pHYs",msg);
}
#endif
#if defined(PNG_oFFs_SUPPORTED)
/* oFFs chunk: */
if (png_get_valid(ping,ping_info,PNG_INFO_oFFs))
{
(void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g",
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:oFFs",msg);
}
#endif
#if defined(PNG_tIME_SUPPORTED)
read_tIME_chunk(image,ping,end_info);
#endif
/* caNv chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
(image->page.x != 0 || image->page.y != 0))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
(void) SetImageProperty(image,"png:caNv",msg);
}
/* vpAg chunk: */
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
(void) FormatLocaleString(msg,MaxTextExtent,
"width=%.20g, height=%.20g",
(double) image->page.width,(double) image->page.height);
(void) SetImageProperty(image,"png:vpAg",msg);
}
}
/*
Relinquish resources.
*/
png_destroy_read_struct(&ping,&ping_info,&end_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block, revert to
* Throwing an Exception when an error occurs.
*/
return(image);
/* end of reading one PNG image */
}
static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
ThrowReaderException(FileOpenError,"UnableToOpenFile");
/*
Verify PNG signature.
*/
count=ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a PNG datastream.
*/
if (GetBlobSize(image) < 61)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOnePNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if ((image->columns == 0) || (image->rows == 0))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error.");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if ((IssRGBColorspace(image->colorspace) != MagickFalse) &&
((image->gamma < .45) || (image->gamma > .46)) &&
!(image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f))
SetImageColorspace(image,RGBColorspace);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()");
return(image);
}
#if defined(JNG_SUPPORTED)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d O n e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file
% (minus the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadOneJNGImage method is:
%
% Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o mng_info: Specifies a pointer to a MngInfo structure.
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJNGImage() reads a JPEG Network Graphics (JNG) image file
% (including the 8-byte signature) and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the ReadJNGImage method is:
%
% Image *ReadJNGImage(const ImageInfo *image_info, ExceptionInfo
% *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a JNG datastream.
*/
if (GetBlobSize(image) < 147)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
#endif
static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length+
MagickPathExtent,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length > 1)
{
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
(p[5] << 16) | (p[6] << 8) | p[7]);
mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
(p[9] << 16) | (p[10] << 8) | p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && (p-chunk) < (ssize_t) (length-4))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && (p-chunk) < (ssize_t) (length-4))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && (p-chunk) < (ssize_t) (length-17))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=17;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(p[12] << 8) & p[13];
else
basi_red=0;
if (length > 15)
basi_green=(p[14] << 8) & p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(p[16] << 8) & p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(p[18] << 8) & p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
}
static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/* Open image file. */
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneMNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadMNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()");
return(GetFirstImageInList(image));
}
#else /* PNG_LIBPNG_VER > 10011 */
static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"PNG library is too old","`%s'",image_info->filename);
return(Image *) NULL;
}
static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
return(ReadPNGImage(image_info,exception));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNGImage() adds properties for the PNG image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPNGImage method is:
%
% size_t RegisterPNGImage(void)
%
*/
ModuleExport size_t RegisterPNGImage(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
static const char
*PNGNote=
{
"See http://www.libpng.org/ for details about the PNG format."
},
*JNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the JNG\n"
"format."
},
*MNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the MNG\n"
"format."
};
*version='\0';
#if defined(PNG_LIBPNG_VER_STRING)
(void) ConcatenateMagickString(version,"libpng ",MaxTextExtent);
(void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent);
if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,png_get_libpng_ver(NULL),
MaxTextExtent);
}
#endif
entry=SetMagickInfo("MNG");
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadMNGImage;
entry->encoder=(EncodeImageHandler *) WriteMNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsMNG;
entry->description=ConstantString("Multiple-image Network Graphics");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("video/x-mng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(MNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Portable Network Graphics");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
if (*version != '\0')
entry->version=ConstantString(version);
entry->note=ConstantString(PNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG8");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"8-bit indexed with optional binary transparency");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG24");
*version='\0';
#if defined(ZLIB_VERSION)
(void) ConcatenateMagickString(version,"zlib ",MaxTextExtent);
(void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent);
if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,zlib_version,MaxTextExtent);
}
#endif
if (*version != '\0')
entry->version=ConstantString(version);
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 24-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG32");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 32-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG48");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 48-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG64");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 64-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG00");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"PNG inheriting bit-depth, color-type from original if possible");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JNG");
#if defined(JNG_SUPPORTED)
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJNGImage;
entry->encoder=(EncodeImageHandler *) WriteJNGImage;
#endif
#endif
entry->magick=(IsImageFormatHandler *) IsJNG;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->description=ConstantString("JPEG Network Graphics");
entry->mime_type=ConstantString("image/x-jng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(JNGNote);
(void) RegisterMagickInfo(entry);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
ping_semaphore=AllocateSemaphoreInfo();
#endif
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNGImage() removes format registrations made by the
% PNG module from the list of supported formats.
%
% The format of the UnregisterPNGImage method is:
%
% UnregisterPNGImage(void)
%
*/
ModuleExport void UnregisterPNGImage(void)
{
(void) UnregisterMagickInfo("MNG");
(void) UnregisterMagickInfo("PNG");
(void) UnregisterMagickInfo("PNG8");
(void) UnregisterMagickInfo("PNG24");
(void) UnregisterMagickInfo("PNG32");
(void) UnregisterMagickInfo("PNG48");
(void) UnregisterMagickInfo("PNG64");
(void) UnregisterMagickInfo("PNG00");
(void) UnregisterMagickInfo("JNG");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
if (ping_semaphore != (SemaphoreInfo *) NULL)
DestroySemaphoreInfo(&ping_semaphore);
#endif
}
#if defined(MAGICKCORE_PNG_DELEGATE)
#if PNG_LIBPNG_VER > 10011
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMNGImage() writes an image in the Portable Network Graphics
% Group's "Multiple-image Network Graphics" encoded image format.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteMNGImage method is:
%
% MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
% To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also
% "To do" under ReadPNGImage):
%
% Preserve all unknown and not-yet-handled known chunks found in input
% PNG file and copy them into output PNG files according to the PNG
% copying rules.
%
% Write the iCCP chunk at MNG level when (icc profile length > 0)
%
% Improve selection of color type (use indexed-colour or indexed-colour
% with tRNS when 256 or fewer unique RGBA values are present).
%
% Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3)
% This will be complicated if we limit ourselves to generating MNG-LC
% files. For now we ignore disposal method 3 and simply overlay the next
% image on it.
%
% Check for identical PLTE's or PLTE/tRNS combinations and use a
% global MNG PLTE or PLTE/tRNS combination when appropriate.
% [mostly done 15 June 1999 but still need to take care of tRNS]
%
% Check for identical sRGB and replace with a global sRGB (and remove
% gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and
% replace with global gAMA/cHRM (or with sRGB if appropriate; replace
% local gAMA/cHRM with local sRGB if appropriate).
%
% Check for identical sBIT chunks and write global ones.
%
% Provide option to skip writing the signature tEXt chunks.
%
% Use signatures to detect identical objects and reuse the first
% instance of such objects instead of writing duplicate objects.
%
% Use a smaller-than-32k value of compression window size when
% appropriate.
%
% Encode JNG datastreams. Mostly done as of 5.5.2; need to write
% ancillary text chunks and save profiles.
%
% Provide an option to force LC files (to ensure exact framing rate)
% instead of VLC.
%
% Provide an option to force VLC files instead of LC, even when offsets
% are present. This will involve expanding the embedded images with a
% transparent region at the top and/or left.
*/
static void
Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping,
png_info *ping_info, unsigned char *profile_type, unsigned char
*profile_description, unsigned char *profile_data, png_uint_32 length)
{
png_textp
text;
register ssize_t
i;
unsigned char
*sp;
png_charp
dp;
png_uint_32
allocated_length,
description_length;
unsigned char
hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0)
return;
if (image_info->verbose)
{
(void) printf("writing raw profile: type=%s, length=%.20g\n",
(char *) profile_type, (double) length);
}
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
description_length=(png_uint_32) strlen((const char *) profile_description);
allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20
+ description_length);
#if PNG_LIBPNG_VER >= 10400
text[0].text=(png_charp) png_malloc(ping,
(png_alloc_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80);
#else
text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length);
text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80);
#endif
text[0].key[0]='\0';
(void) ConcatenateMagickString(text[0].key,
"Raw profile type ",MaxTextExtent);
(void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62);
sp=profile_data;
dp=text[0].text;
*dp++='\n';
(void) CopyMagickString(dp,(const char *) profile_description,
allocated_length);
dp+=description_length;
*dp++='\n';
(void) FormatLocaleString(dp,allocated_length-
(png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length);
dp+=8;
for (i=0; i < (ssize_t) length; i++)
{
if (i%36 == 0)
*dp++='\n';
*(dp++)=(char) hex[((*sp >> 4) & 0x0f)];
*(dp++)=(char) hex[((*sp++ ) & 0x0f)];
}
*dp++='\n';
*dp='\0';
text[0].text_length=(png_size_t) (dp-text[0].text);
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? -1 : 0;
if (text[0].text_length <= allocated_length)
png_set_text(ping,ping_info,text,1);
png_free(ping,text[0].text);
png_free(ping,text[0].key);
png_free(ping,text);
}
static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image,
const char *string, MagickBooleanType logging)
{
char
*name;
const StringInfo
*profile;
unsigned char
*data;
png_uint_32 length;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (const StringInfo *) NULL)
{
StringInfo
*ping_profile;
if (LocaleNCompare(name,string,11) == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Found %s profile",name);
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
data[4]=data[3];
data[3]=data[2];
data[2]=data[1];
data[1]=data[0];
(void) WriteBlobMSBULong(image,length-5); /* data length */
(void) WriteBlob(image,length-1,data+1);
(void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1));
ping_profile=DestroyStringInfo(ping_profile);
}
}
name=GetNextImageProfile(image);
}
return(MagickTrue);
}
#if defined(PNG_tIME_SUPPORTED)
static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info,
const char *date)
{
unsigned int
day,
hour,
minute,
month,
second,
year;
png_time
ptime;
time_t
ttime;
if (date != (const char *) NULL)
{
if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute,
&second) != 6)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,
"Invalid date format specified for png:tIME","`%s'",
image->filename);
return;
}
ptime.year=(png_uint_16) year;
ptime.month=(png_byte) month;
ptime.day=(png_byte) day;
ptime.hour=(png_byte) hour;
ptime.minute=(png_byte) minute;
ptime.second=(png_byte) second;
}
else
{
time(&ttime);
png_convert_from_time_t(&ptime,ttime);
}
png_set_tIME(ping,info,&ptime);
}
#endif
/* Write one PNG image */
static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *image_info,Image *image)
{
char
s[2];
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MaxTextExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MaxTextExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s",
im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s",
libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
/* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_vpAg=mng_info->ping_exclude_vpAg;
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
property=(const char *) NULL;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->magick= %s",image_info->magick);
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register PixelPacket
*r;
ExceptionInfo
*exception;
exception=(&image->exception);
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBO(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 && image->matte == MagickFalse)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
number_opaque = (int) image->colors;
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
else
ping_have_color=MagickTrue;
ping_have_non_bw=MagickFalse;
if (image->matte != MagickFalse)
{
number_transparent = 2;
number_semitransparent = 1;
}
else
{
number_transparent = 0;
number_semitransparent = 0;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->matte is MagickFalse, we ignore the opacity channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
ExceptionInfo
*exception;
int
n;
PixelPacket
opaque[260],
semitransparent[260],
transparent[260];
register IndexPacket
*indexes;
register const PixelPacket
*s,
*q;
register PixelPacket
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->matte=%.20g",(double) image->matte);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,opacity)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
exception=(&image->exception);
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->matte == MagickFalse ||
GetPixelOpacity(q) == OpaqueOpacity)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelRGB(q, opaque);
opaque[0].opacity=OpaqueOpacity;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (IsColorEqual(q, opaque+i))
break;
}
if (i == (ssize_t) number_opaque &&
number_opaque < 259)
{
number_opaque++;
GetPixelRGB(q, opaque+i);
opaque[i].opacity=OpaqueOpacity;
}
}
}
else if (q->opacity == TransparentOpacity)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelRGBO(q, transparent);
ping_trans_color.red=
(unsigned short) GetPixelRed(q);
ping_trans_color.green=
(unsigned short) GetPixelGreen(q);
ping_trans_color.blue=
(unsigned short) GetPixelBlue(q);
ping_trans_color.gray=
(unsigned short) GetPixelRed(q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (IsColorEqual(q, transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelRGBO(q, transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelRGBO(q, semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (IsColorEqual(q, semitransparent+i)
&& GetPixelOpacity(q) ==
semitransparent[i].opacity)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelRGBO(q, semitransparent+i);
}
}
}
q++;
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(s) != GetPixelGreen(s) ||
GetPixelRed(s) != GetPixelBlue(s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s++;
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(s) != 0 &&
GetPixelRed(s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s++;
}
}
}
}
}
if (image_colors < 257)
{
PixelPacket
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors) ==
MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->matte == MagickFalse ||
image->colormap[i].opacity ==
GetPixelOpacity(q)) &&
image->colormap[i].red ==
GetPixelRed(q) &&
image->colormap[i].green ==
GetPixelGreen(q) &&
image->colormap[i].blue ==
GetPixelBlue(q))
{
SetPixelIndex(indexes+x,i);
break;
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,opacity)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].opacity);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) > TransparentOpacity/2)
{
SetPixelOpacity(r,TransparentOpacity);
SetPixelRgb(r,&image->background_color);
}
else
SetPixelOpacity(r,OpaqueOpacity);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].opacity =
(image->colormap[i].opacity > TransparentOpacity/2 ?
TransparentOpacity : OpaqueOpacity);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR04PixelRGB(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR03PixelRGB(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelOpacity(r) == OpaqueOpacity)
LBR02PixelBlue(r);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 &&
GetPixelOpacity(r) == OpaqueOpacity)
{
SetPixelRed(r,ScaleCharToQuantum(0x24));
}
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
ExceptionInfo
*exception;
register const PixelPacket
*q;
exception=(&image->exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (q->opacity != TransparentOpacity &&
(unsigned short) GetPixelRed(q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q++;
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->matte;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",image->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->matte);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->x_resolution != 0) && (image->y_resolution != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->x_resolution+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->y_resolution+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->x_resolution;
ping_pHYs_y_resolution=(png_uint_32) image->y_resolution;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorMatteType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteMatteType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image,
image->colormap))) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte) (255-
ScaleQuantumToChar(image->colormap[i].opacity));
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16)
((maxval/65535.)*(ScaleQuantumToShort((Quantum)
GetPixelLuma(image,&image->background_color)))+.5);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_background.index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_background.gray is %d",
(int) ping_background.gray);
}
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This is addressed by using
"-define png:compression-strategy", etc., which takes precedence
over -quality.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->matte == MagickFalse)
{
/* Add an opaque matte channel */
image->matte = MagickTrue;
(void) SetImageOpacity(image,0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
if (mng_info->have_write_global_plte && matte == MagickFalse)
{
png_set_PLTE(ping,ping_info,NULL,0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up empty PLTE chunk");
}
else
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(const png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
ping_have_iCCP = MagickTrue;
}
}
else
#endif
if (ping_exclude_zCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXT chunk with uuencoded ICC");
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
ping_have_iCCP = MagickTrue;
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk with %s profile",name);
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME");
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify");
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
(void) ping_have_blob;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
/* write any png-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging);
png_write_info(ping,ping_info);
/* write any PNG-chunk-m profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging);
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
/* write vpAg chunk (deprecated, replaced by caNv) */
if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
unsigned char
chunk[14];
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
}
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const PixelPacket
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const PixelPacket
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const PixelPacket
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,&image->exception);
else
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass);
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,&image->exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
&image->exception);
}
else
{
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,&image->exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write any PNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging);
/* write exIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
#if 0 /* eXIf chunk is registered */
PNGType(chunk,mng_eXIf);
#else /* eXIf chunk not yet registered; write exIf instead */
PNGType(chunk,mng_exIf);
#endif
if (length < 7)
break; /* othewise crashes */
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data+6);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),
data+6, (uInt) length));
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(image,"png:bit-depth-written",s);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNGImage() writes a Portable Network Graphics (PNG) or
% Multiple-image Network Graphics (MNG) image file.
%
% MNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WritePNGImage method is:
%
% MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
% Returns MagickTrue on success, MagickFalse on failure.
%
% Communicating with the PNG encoder:
%
% While the datastream written is always in PNG format and normally would
% be given the "png" file extension, this method also writes the following
% pseudo-formats which are subsets of png:
%
% o PNG8: An 8-bit indexed PNG datastream is written. If the image has
% a depth greater than 8, the depth is reduced. If transparency
% is present, the tRNS chunk must only have values 0 and 255
% (i.e., transparency is binary: fully opaque or fully
% transparent). If other values are present they will be
% 50%-thresholded to binary transparency. If more than 256
% colors are present, they will be quantized to the 4-4-4-1,
% 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color
% of any resulting fully-transparent pixels is changed to
% the image's background color.
%
% If you want better quantization or dithering of the colors
% or alpha than that, you need to do it before calling the
% PNG encoder. The pixels contain 8-bit indices even if
% they could be represented with 1, 2, or 4 bits. Grayscale
% images will be written as indexed PNG files even though the
% PNG grayscale type might be slightly more efficient. Please
% note that writing to the PNG8 format may result in loss
% of color and alpha data.
%
% o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. The only loss incurred
% is reduction of sample depth to 8. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG32: An 8-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 255. The alpha
% channel is present even if the image is fully opaque.
% The only loss in data is the reduction of the sample depth
% to 8.
%
% o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS
% chunk can be present to convey binary transparency by naming
% one of the colors as transparent. If the image has more
% than one transparent color, has semitransparent pixels, or
% has an opaque pixel with the same RGB components as the
% transparent color, an image is not written.
%
% o PNG64: A 16-bit per sample RGBA PNG is written. Partial
% transparency is permitted, i.e., the alpha sample for
% each pixel can have any value from 0 to 65535. The alpha
% channel is present even if the image is fully opaque.
%
% o PNG00: A PNG that inherits its colortype and bit-depth from the input
% image, if the input was a PNG, is written. If these values
% cannot be found, or if the pixels have been changed in a way
% that makes this impossible, then "PNG00" falls back to the
% regular "PNG" format.
%
% o -define: For more precise control of the PNG output, you can use the
% Image options "png:bit-depth" and "png:color-type". These
% can be set from the commandline with "-define" and also
% from the application programming interfaces. The options
% are case-independent and are converted to lowercase before
% being passed to this encoder.
%
% png:color-type can be 0, 2, 3, 4, or 6.
%
% When png:color-type is 0 (Grayscale), png:bit-depth can
% be 1, 2, 4, 8, or 16.
%
% When png:color-type is 2 (RGB), png:bit-depth can
% be 8 or 16.
%
% When png:color-type is 3 (Indexed), png:bit-depth can
% be 1, 2, 4, or 8. This refers to the number of bits
% used to store the index. The color samples always have
% bit-depth 8 in indexed PNG files.
%
% When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte),
% png:bit-depth can be 8 or 16.
%
% If the image cannot be written without loss with the
% requested bit-depth and color-type, a PNG file will not
% be written, a warning will be issued, and the encoder will
% return MagickFalse.
%
% Since image encoders should not be responsible for the "heavy lifting",
% the user should make sure that ImageMagick has already reduced the
% image depth and number of colors and limit transparency to binary
% transparency prior to attempting to write the image with depth, color,
% or transparency limitations.
%
% To do: Enforce the previous paragraph.
%
% Note that another definition, "png:bit-depth-written" exists, but it
% is not intended for external use. It is only used internally by the
% PNG encoder to inform the JNG encoder of the depth of the alpha channel.
%
% It is possible to request that the PNG encoder write previously-formatted
% ancillary chunks in the output PNG file, using the "-profile" commandline
% option as shown below or by setting the profile via a programming
% interface:
%
% -profile PNG-chunk-x:<file>
%
% where x is a location flag and <file> is a file containing the chunk
% name in the first 4 bytes, then a colon (":"), followed by the chunk data.
% This encoder will compute the chunk length and CRC, so those must not
% be included in the file.
%
% "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT),
% or "e" (end, i.e., after IDAT). If you want to write multiple chunks
% of the same type, then add a short unique string after the "x" to prevent
% subsequent profiles from overwriting the preceding ones, e.g.,
%
% -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02
%
% As of version 6.6.6 the following optimizations are always done:
%
% o 32-bit depth is reduced to 16.
% o 16-bit depth is reduced to 8 if all pixels contain samples whose
% high byte and low byte are identical.
% o Palette is sorted to remove unused entries and to put a
% transparent color first, if BUILD_PNG_PALETTE is defined.
% o Opaque matte channel is removed when writing an indexed PNG.
% o Grayscale images are reduced to 1, 2, or 4 bit depth if
% this can be done without loss and a larger bit depth N was not
% requested via the "-define png:bit-depth=N" option.
% o If matte channel is present but only one transparent color is
% present, RGB+tRNS is written instead of RGBA
% o Opaque matte channel is removed (or added, if color-type 4 or 6
% was requested when converting an opaque image).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
excluding,
logging,
status;
MngInfo
*mng_info;
const char
*value;
int
source;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
mng_info->equal_backgrounds=MagickTrue;
/* See if user has requested a specific PNG subformat */
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0;
mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0;
value=GetImageOption(image_info,"png:format");
if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0)
{
mng_info->write_png8 = MagickFalse;
mng_info->write_png24 = MagickFalse;
mng_info->write_png32 = MagickFalse;
mng_info->write_png48 = MagickFalse;
mng_info->write_png64 = MagickFalse;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",value);
if (LocaleCompare(value,"png8") == 0)
mng_info->write_png8 = MagickTrue;
else if (LocaleCompare(value,"png24") == 0)
mng_info->write_png24 = MagickTrue;
else if (LocaleCompare(value,"png32") == 0)
mng_info->write_png32 = MagickTrue;
else if (LocaleCompare(value,"png48") == 0)
mng_info->write_png48 = MagickTrue;
else if (LocaleCompare(value,"png64") == 0)
mng_info->write_png64 = MagickTrue;
else if ((LocaleCompare(value,"png00") == 0) ||
LocaleCompare(image_info->magick,"PNG00") == 0)
{
/* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */
value=GetImageProperty(image,"png:IHDR.bit-depth-orig");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited bit depth=%s",value);
if (value != (char *) NULL)
{
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
}
value=GetImageProperty(image,"png:IHDR.color-type-orig");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png00 inherited color type=%s",value);
if (value != (char *) NULL)
{
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
}
}
}
if (mng_info->write_png8)
{
mng_info->write_png_colortype = /* 3 */ 4;
mng_info->write_png_depth = 8;
image->depth = 8;
}
if (mng_info->write_png24)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 8;
image->depth = 8;
if (image->matte != MagickFalse)
(void) SetImageType(image,TrueColorMatteType);
else
(void) SetImageType(image,TrueColorType);
(void) SyncImage(image);
}
if (mng_info->write_png32)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 8;
image->depth = 8;
image->matte = MagickTrue;
(void) SetImageType(image,TrueColorMatteType);
(void) SyncImage(image);
}
if (mng_info->write_png48)
{
mng_info->write_png_colortype = /* 2 */ 3;
mng_info->write_png_depth = 16;
image->depth = 16;
if (image->matte != MagickFalse)
(void) SetImageType(image,TrueColorMatteType);
else
(void) SetImageType(image,TrueColorType);
(void) SyncImage(image);
}
if (mng_info->write_png64)
{
mng_info->write_png_colortype = /* 6 */ 7;
mng_info->write_png_depth = 16;
image->depth = 16;
image->matte = MagickTrue;
(void) SetImageType(image,TrueColorMatteType);
(void) SyncImage(image);
}
value=GetImageOption(image_info,"png:bit-depth");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"1") == 0)
mng_info->write_png_depth = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_depth = 2;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_depth = 4;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_depth = 8;
else if (LocaleCompare(value,"16") == 0)
mng_info->write_png_depth = 16;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:bit-depth",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:bit-depth=%d was defined.\n",mng_info->write_png_depth);
}
value=GetImageOption(image_info,"png:color-type");
if (value != (char *) NULL)
{
/* We must store colortype+1 because 0 is a valid colortype */
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_colortype = 1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_colortype = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_colortype = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_colortype = 5;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_colortype = 7;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:color-type",
"=%s",value);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:color-type=%d was defined.\n",mng_info->write_png_colortype-1);
}
/* Check for chunks to be excluded:
*
* The default is to not exclude any known chunks except for any
* listed in the "unused_chunks" array, above.
*
* Chunks can be listed for exclusion via a "png:exclude-chunk"
* define (in the image properties or in the image artifacts)
* or via a mng_info member. For convenience, in addition
* to or instead of a comma-separated list of chunks, the
* "exclude-chunk" string can be simply "all" or "none".
*
* The exclude-chunk define takes priority over the mng_info.
*
* A "png:include-chunk" define takes priority over both the
* mng_info and the "png:exclude-chunk" define. Like the
* "exclude-chunk" string, it can define "all" or "none" as
* well as a comma-separated list. Chunks that are unknown to
* ImageMagick are always excluded, regardless of their "copy-safe"
* status according to the PNG specification, and even if they
* appear in the "include-chunk" list. Such defines appearing among
* the image options take priority over those found among the image
* artifacts.
*
* Finally, all chunks listed in the "unused_chunks" array are
* automatically excluded, regardless of the other instructions
* or lack thereof.
*
* if you exclude sRGB but not gAMA (recommended), then sRGB chunk
* will not be written and the gAMA chunk will only be written if it
* is not between .45 and .46, or approximately (1.0/2.2).
*
* If you exclude tRNS and the image has transparency, the colortype
* is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA).
*
* The -strip option causes StripImage() to set the png:include-chunk
* artifact to "none,trns,gama".
*/
mng_info->ping_exclude_bKGD=MagickFalse;
mng_info->ping_exclude_caNv=MagickFalse;
mng_info->ping_exclude_cHRM=MagickFalse;
mng_info->ping_exclude_date=MagickFalse;
mng_info->ping_exclude_eXIf=MagickFalse;
mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */
mng_info->ping_exclude_gAMA=MagickFalse;
mng_info->ping_exclude_iCCP=MagickFalse;
/* mng_info->ping_exclude_iTXt=MagickFalse; */
mng_info->ping_exclude_oFFs=MagickFalse;
mng_info->ping_exclude_pHYs=MagickFalse;
mng_info->ping_exclude_sRGB=MagickFalse;
mng_info->ping_exclude_tEXt=MagickFalse;
mng_info->ping_exclude_tIME=MagickFalse;
mng_info->ping_exclude_tRNS=MagickFalse;
mng_info->ping_exclude_vpAg=MagickFalse;
mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */
mng_info->ping_exclude_zTXt=MagickFalse;
mng_info->ping_preserve_colormap=MagickFalse;
value=GetImageOption(image_info,"png:preserve-colormap");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-colormap");
if (value != NULL)
mng_info->ping_preserve_colormap=MagickTrue;
mng_info->ping_preserve_iCCP=MagickFalse;
value=GetImageOption(image_info,"png:preserve-iCCP");
if (value == NULL)
value=GetImageArtifact(image,"png:preserve-iCCP");
if (value != NULL)
mng_info->ping_preserve_iCCP=MagickTrue;
/* These compression-level, compression-strategy, and compression-filter
* defines take precedence over values from the -quality option.
*/
value=GetImageOption(image_info,"png:compression-level");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-level");
if (value != NULL)
{
/* To do: use a "LocaleInteger:()" function here. */
/* We have to add 1 to everything because 0 is a valid input,
* and we want to use 0 (the default) to mean undefined.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_level = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_level = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_level = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_level = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_level = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_level = 6;
else if (LocaleCompare(value,"6") == 0)
mng_info->write_png_compression_level = 7;
else if (LocaleCompare(value,"7") == 0)
mng_info->write_png_compression_level = 8;
else if (LocaleCompare(value,"8") == 0)
mng_info->write_png_compression_level = 9;
else if (LocaleCompare(value,"9") == 0)
mng_info->write_png_compression_level = 10;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-level",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-strategy");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-strategy");
if (value != NULL)
{
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_strategy = Z_FILTERED+1;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
else if (LocaleCompare(value,"3") == 0)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy = Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else if (LocaleCompare(value,"4") == 0)
#ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */
mng_info->write_png_compression_strategy = Z_FIXED+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-strategy",
"=%s",value);
}
value=GetImageOption(image_info,"png:compression-filter");
if (value == NULL)
value=GetImageArtifact(image,"png:compression-filter");
if (value != NULL)
{
/* To do: combinations of filters allowed by libpng
* masks 0x08 through 0xf8
*
* Implement this as a comma-separated list of 0,1,2,3,4,5
* where 5 is a special case meaning PNG_ALL_FILTERS.
*/
if (LocaleCompare(value,"0") == 0)
mng_info->write_png_compression_filter = 1;
else if (LocaleCompare(value,"1") == 0)
mng_info->write_png_compression_filter = 2;
else if (LocaleCompare(value,"2") == 0)
mng_info->write_png_compression_filter = 3;
else if (LocaleCompare(value,"3") == 0)
mng_info->write_png_compression_filter = 4;
else if (LocaleCompare(value,"4") == 0)
mng_info->write_png_compression_filter = 5;
else if (LocaleCompare(value,"5") == 0)
mng_info->write_png_compression_filter = 6;
else
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"ignoring invalid defined png:compression-filter",
"=%s",value);
}
for (source=0; source<8; source++)
{
value = NULL;
if (source == 0)
value=GetImageOption(image_info,"png:exclude-chunks");
if (source == 1)
value=GetImageArtifact(image,"png:exclude-chunks");
if (source == 2)
value=GetImageOption(image_info,"png:exclude-chunk");
if (source == 3)
value=GetImageArtifact(image,"png:exclude-chunk");
if (source == 4)
value=GetImageOption(image_info,"png:include-chunks");
if (source == 5)
value=GetImageArtifact(image,"png:include-chunks");
if (source == 6)
value=GetImageOption(image_info,"png:include-chunk");
if (source == 7)
value=GetImageArtifact(image,"png:include-chunk");
if (value == NULL)
continue;
if (source < 4)
excluding = MagickTrue;
else
excluding = MagickFalse;
if (logging != MagickFalse)
{
if (source == 0 || source == 2)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image options.\n", value);
else if (source == 1 || source == 3)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:exclude-chunk=%s found in image artifacts.\n", value);
else if (source == 4 || source == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image options.\n", value);
else /* if (source == 5 || source == 7) */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" png:include-chunk=%s found in image artifacts.\n", value);
}
if (IsOptionMember("all",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding;
mng_info->ping_exclude_caNv=excluding;
mng_info->ping_exclude_cHRM=excluding;
mng_info->ping_exclude_date=excluding;
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
mng_info->ping_exclude_gAMA=excluding;
mng_info->ping_exclude_iCCP=excluding;
/* mng_info->ping_exclude_iTXt=excluding; */
mng_info->ping_exclude_oFFs=excluding;
mng_info->ping_exclude_pHYs=excluding;
mng_info->ping_exclude_sRGB=excluding;
mng_info->ping_exclude_tIME=excluding;
mng_info->ping_exclude_tEXt=excluding;
mng_info->ping_exclude_tRNS=excluding;
mng_info->ping_exclude_vpAg=excluding;
mng_info->ping_exclude_zCCP=excluding;
mng_info->ping_exclude_zTXt=excluding;
}
if (IsOptionMember("none",value) != MagickFalse)
{
mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
/* mng_info->ping_exclude_iTXt=!excluding; */
mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse :
MagickTrue;
mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse :
MagickTrue;
}
if (IsOptionMember("bkgd",value) != MagickFalse)
mng_info->ping_exclude_bKGD=excluding;
if (IsOptionMember("caNv",value) != MagickFalse)
mng_info->ping_exclude_caNv=excluding;
if (IsOptionMember("chrm",value) != MagickFalse)
mng_info->ping_exclude_cHRM=excluding;
if (IsOptionMember("date",value) != MagickFalse)
mng_info->ping_exclude_date=excluding;
if (IsOptionMember("exif",value) != MagickFalse)
{
mng_info->ping_exclude_EXIF=excluding;
mng_info->ping_exclude_eXIf=excluding;
}
if (IsOptionMember("gama",value) != MagickFalse)
mng_info->ping_exclude_gAMA=excluding;
if (IsOptionMember("iccp",value) != MagickFalse)
mng_info->ping_exclude_iCCP=excluding;
#if 0
if (IsOptionMember("itxt",value) != MagickFalse)
mng_info->ping_exclude_iTXt=excluding;
#endif
if (IsOptionMember("offs",value) != MagickFalse)
mng_info->ping_exclude_oFFs=excluding;
if (IsOptionMember("phys",value) != MagickFalse)
mng_info->ping_exclude_pHYs=excluding;
if (IsOptionMember("srgb",value) != MagickFalse)
mng_info->ping_exclude_sRGB=excluding;
if (IsOptionMember("text",value) != MagickFalse)
mng_info->ping_exclude_tEXt=excluding;
if (IsOptionMember("time",value) != MagickFalse)
mng_info->ping_exclude_tIME=excluding;
if (IsOptionMember("trns",value) != MagickFalse)
mng_info->ping_exclude_tRNS=excluding;
if (IsOptionMember("vpag",value) != MagickFalse)
mng_info->ping_exclude_vpAg=excluding;
if (IsOptionMember("zccp",value) != MagickFalse)
mng_info->ping_exclude_zCCP=excluding;
if (IsOptionMember("ztxt",value) != MagickFalse)
mng_info->ping_exclude_zTXt=excluding;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Chunks to be excluded from the output png:");
if (mng_info->ping_exclude_bKGD != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" bKGD");
if (mng_info->ping_exclude_caNv != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" caNv");
if (mng_info->ping_exclude_cHRM != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" cHRM");
if (mng_info->ping_exclude_date != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" date");
if (mng_info->ping_exclude_EXIF != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" EXIF");
if (mng_info->ping_exclude_eXIf != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" eXIf");
if (mng_info->ping_exclude_gAMA != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" gAMA");
if (mng_info->ping_exclude_iCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iCCP");
#if 0
if (mng_info->ping_exclude_iTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" iTXt");
#endif
if (mng_info->ping_exclude_oFFs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" oFFs");
if (mng_info->ping_exclude_pHYs != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pHYs");
if (mng_info->ping_exclude_sRGB != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" sRGB");
if (mng_info->ping_exclude_tEXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tEXt");
if (mng_info->ping_exclude_tIME != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tIME");
if (mng_info->ping_exclude_tRNS != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS");
if (mng_info->ping_exclude_vpAg != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" vpAg");
if (mng_info->ping_exclude_zCCP != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zCCP");
if (mng_info->ping_exclude_zTXt != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" zTXt");
}
mng_info->need_blob = MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image);
(void) CloseBlob(image);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()");
return(status);
}
#if defined(JNG_SUPPORTED)
/* Write one JNG image */
static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info,Image *image)
{
Image
*jpeg_image;
ImageInfo
*jpeg_image_info;
int
unique_filenames;
MagickBooleanType
logging,
status;
size_t
length;
unsigned char
*blob,
chunk[80],
*p;
unsigned int
jng_alpha_compression_method,
jng_alpha_sample_depth,
jng_color_type,
transparent;
size_t
jng_alpha_quality,
jng_quality;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOneJNGImage()");
blob=(unsigned char *) NULL;
jpeg_image=(Image *) NULL;
jpeg_image_info=(ImageInfo *) NULL;
length=0;
unique_filenames=0;
status=MagickTrue;
transparent=image_info->type==GrayscaleMatteType ||
image_info->type==TrueColorMatteType || image->matte != MagickFalse;
jng_alpha_sample_depth = 0;
jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000;
jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0;
jng_alpha_quality=image_info->quality == 0UL ? 75UL :
image_info->quality;
if (jng_alpha_quality >= 1000)
jng_alpha_quality /= 1000;
if (transparent != 0)
{
jng_color_type=14;
/* Create JPEG blob, image, and image_info */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info for opacity.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
status=SeparateImageChannel(jpeg_image,OpacityChannel);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=NegateImage(jpeg_image,MagickFalse);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
jpeg_image->matte=MagickFalse;
jpeg_image_info->type=GrayscaleType;
jpeg_image->quality=jng_alpha_quality;
(void) SetImageType(jpeg_image,GrayscaleType);
(void) AcquireUniqueFilename(jpeg_image->filename);
unique_filenames++;
(void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,
"%s",jpeg_image->filename);
}
else
{
jng_alpha_compression_method=0;
jng_color_type=10;
jng_alpha_sample_depth=0;
}
/* To do: check bit depth of PNG alpha channel */
/* Check if image is grayscale. */
if (image_info->type != TrueColorMatteType && image_info->type !=
TrueColorType && SetImageGray(image,&image->exception))
jng_color_type-=2;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Quality = %d",(int) jng_quality);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Color Type = %d",jng_color_type);
if (transparent != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Compression = %d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Depth = %d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG Alpha Quality = %d",(int) jng_alpha_quality);
}
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
const char
*value;
/* Encode opacity as a grayscale PNG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating PNG blob for alpha.");
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
length=0;
(void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent);
jpeg_image_info->interlace=NoInterlace;
/* Exclude all ancillary chunks */
(void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all");
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,
&image->exception);
/* Retrieve sample depth used */
value=GetImageProperty(jpeg_image,"png:bit-depth-written");
if (value != (char *) NULL)
jng_alpha_sample_depth= (unsigned int) value[0];
}
else
{
/* Encode opacity as a grayscale JPEG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating JPEG blob for alpha.");
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
jpeg_image_info->interlace=NoInterlace;
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,
&image->exception);
jng_alpha_sample_depth=8;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
}
/* Destroy JPEG image and image_info */
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
unique_filenames--;
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
}
/* Write JHDR chunk */
(void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */
PNGType(chunk,mng_JHDR);
LogPNGChunk(logging,mng_JHDR,16L);
PNGLong(chunk+4,(png_uint_32) image->columns);
PNGLong(chunk+8,(png_uint_32) image->rows);
chunk[12]=jng_color_type;
chunk[13]=8; /* sample depth */
chunk[14]=8; /*jng_image_compression_method */
chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8);
chunk[16]=jng_alpha_sample_depth;
chunk[17]=jng_alpha_compression_method;
chunk[18]=0; /*jng_alpha_filter_method */
chunk[19]=0; /*jng_alpha_interlace_method */
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG width:%15lu",(unsigned long) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG height:%14lu",(unsigned long) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG color type:%10d",jng_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG sample depth:%8d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG compression:%9d",8);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG interlace:%11d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha depth:%9d",jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha compression:%3d",jng_alpha_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha filter:%8d",0);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG alpha interlace:%5d",0);
}
/* Write any JNG-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging);
/*
Write leading ancillary chunks
*/
if (transparent != 0)
{
/*
Write JNG bKGD chunk
*/
unsigned char
blue,
green,
red;
ssize_t
num_bytes;
if (jng_color_type == 8 || jng_color_type == 12)
num_bytes=6L;
else
num_bytes=10L;
(void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L));
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L));
red=ScaleQuantumToChar(image->background_color.red);
green=ScaleQuantumToChar(image->background_color.green);
blue=ScaleQuantumToChar(image->background_color.blue);
*(chunk+4)=0;
*(chunk+5)=red;
*(chunk+6)=0;
*(chunk+7)=green;
*(chunk+8)=0;
*(chunk+9)=blue;
(void) WriteBlob(image,(size_t) num_bytes,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes));
}
if ((image->colorspace == sRGBColorspace || image->rendering_intent))
{
/*
Write JNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
if (image->gamma != 0.0)
{
/*
Write JNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
}
if ((mng_info->equal_chrms == MagickFalse) &&
(image->chromaticity.red_primary.x != 0.0))
{
PrimaryInfo
primary;
/*
Write JNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
}
}
if (image->x_resolution && image->y_resolution && !mng_info->equal_physs)
{
/*
Write JNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5));
PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.x || image->page.y))
{
/*
Write JNG oFFs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_oFFs);
LogPNGChunk(logging,mng_oFFs,9L);
PNGsLong(chunk+4,(ssize_t) (image->page.x));
PNGsLong(chunk+8,(ssize_t) (image->page.y));
chunk[12]=0;
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (mng_info->write_mng == 0 && (image->page.width || image->page.height))
{
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
if (transparent != 0)
{
if (jng_alpha_compression_method==0)
{
register ssize_t
i;
size_t
len;
/* Write IDAT chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write IDAT chunks from blob, length=%.20g.",(double)
length);
/* Copy IDAT chunks */
len=0;
p=blob+8;
for (i=8; i<(ssize_t) length; i+=len+12)
{
len=(size_t) (*p) << 24;
len|=(size_t) (*(p+1)) << 16;
len|=(size_t) (*(p+2)) << 8;
len|=(size_t) (*(p+3));
p+=4;
if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */
{
/* Found an IDAT chunk. */
(void) WriteBlobMSBULong(image,len);
LogPNGChunk(logging,mng_IDAT,len);
(void) WriteBlob(image,len+4,p);
(void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4));
}
else
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping %c%c%c%c chunk, length=%.20g.",
*(p),*(p+1),*(p+2),*(p+3),(double) len);
}
p+=(8+len);
}
}
else if (length != 0)
{
/* Write JDAA chunk header */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAA chunk, length=%.20g.",(double) length);
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAA);
LogPNGChunk(logging,mng_JDAA,length);
/* Write JDAT chunk(s) data */
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,
(uInt) length));
}
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/* Encode image as a JPEG blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image_info.");
jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);
if (jpeg_image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating jpeg_image.");
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
(void) AcquireUniqueFilename(jpeg_image->filename);
unique_filenames++;
(void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s",
jpeg_image->filename);
status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,
&image->exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns,
(double) jpeg_image->rows);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (jng_color_type == 8 || jng_color_type == 12)
jpeg_image_info->type=GrayscaleType;
jpeg_image_info->quality=jng_quality;
jpeg_image->quality=jng_quality;
(void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent);
(void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating blob.");
blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Successfully read jpeg_image into a blob, length=%.20g.",
(double) length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JDAT chunk, length=%.20g.",(double) length);
}
/* Write JDAT chunk(s) */
(void) WriteBlobMSBULong(image,(size_t) length);
PNGType(chunk,mng_JDAT);
LogPNGChunk(logging,mng_JDAT,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,blob);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length));
jpeg_image=DestroyImage(jpeg_image);
(void) RelinquishUniqueFileResource(jpeg_image_info->filename);
unique_filenames--;
jpeg_image_info=DestroyImageInfo(jpeg_image_info);
blob=(unsigned char *) RelinquishMagickMemory(blob);
/* Write any JNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging);
/* Write IEND chunk */
(void) WriteBlobMSBULong(image,0L);
PNGType(chunk,mng_IEND);
LogPNGChunk(logging,mng_IEND,0);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J N G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJNGImage() writes a JPEG Network Graphics (JNG) image file.
%
% JNG support written by Glenn Randers-Pehrson, glennrp@image...
%
% The format of the WriteJNGImage method is:
%
% MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
(void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n");
status=WriteOneJNGImage(mng_info,image_info,image);
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
(void) CatchImageException(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteJNGImage()");
return(status);
}
#endif
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
{
const char
*option;
Image
*next_image;
MagickBooleanType
status;
volatile MagickBooleanType
logging;
MngInfo
*mng_info;
int
image_count,
need_iterations,
need_matte;
volatile int
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
need_local_plte,
#endif
all_images_are_gray,
need_defi,
use_global_plte;
register ssize_t
i;
unsigned char
chunk[800];
volatile unsigned int
write_jng,
write_mng;
volatile size_t
scene;
size_t
final_delay=0,
initial_delay;
#if (PNG_LIBPNG_VER < 10200)
if (image_info->verbose)
printf("Your PNG library (libpng-%s) is rather old.\n",
PNG_LIBPNG_VER_STRING);
#endif
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
write_mng=LocaleCompare(image_info->magick,"MNG") == 0;
/*
* See if user has requested a specific PNG subformat to be used
* for all of the PNGs in the MNG being written, e.g.,
*
* convert *.png png8:animation.mng
*
* To do: check -define png:bit_depth and png:color_type as well,
* or perhaps use mng:bit_depth and mng:color_type instead for
* global settings.
*/
mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0;
mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0;
mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0;
write_jng=MagickFalse;
if (image_info->compression == JPEGCompression)
write_jng=MagickTrue;
mng_info->adjoin=image_info->adjoin &&
(GetNextImageInList(image) != (Image *) NULL) && write_mng;
if (logging != MagickFalse)
{
/* Log some info about the input */
Image
*p;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Checking input image(s)\n"
" Image_info depth: %.20g, Type: %d",
(double) image_info->depth, image_info->type);
scene=0;
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scene: %.20g\n, Image depth: %.20g",
(double) scene++, (double) p->depth);
if (p->matte)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: True");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte: False");
if (p->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: PseudoClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class: DirectClass");
if (p->colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) p->colors);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: unspecified");
if (mng_info->adjoin == MagickFalse)
break;
}
}
use_global_plte=MagickFalse;
all_images_are_gray=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_defi=MagickFalse;
need_matte=MagickFalse;
mng_info->framing_mode=1;
mng_info->old_framing_mode=1;
if (write_mng)
if (image_info->page != (char *) NULL)
{
/*
Determine image bounding box.
*/
SetGeometry(image,&mng_info->page);
(void) ParseMetaGeometry(image_info->page,&mng_info->page.x,
&mng_info->page.y,&mng_info->page.width,&mng_info->page.height);
}
if (write_mng)
{
unsigned int
need_geom;
unsigned short
red,
green,
blue;
mng_info->page=image->page;
need_geom=MagickTrue;
if (mng_info->page.width || mng_info->page.height)
need_geom=MagickFalse;
/*
Check all the scenes.
*/
initial_delay=image->delay;
need_iterations=MagickFalse;
mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0;
mng_info->equal_physs=MagickTrue,
mng_info->equal_gammas=MagickTrue;
mng_info->equal_srgbs=MagickTrue;
mng_info->equal_backgrounds=MagickTrue;
image_count=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
all_images_are_gray=MagickTrue;
mng_info->equal_palettes=MagickFalse;
need_local_plte=MagickFalse;
#endif
for (next_image=image; next_image != (Image *) NULL; )
{
if (need_geom)
{
if ((next_image->columns+next_image->page.x) > mng_info->page.width)
mng_info->page.width=next_image->columns+next_image->page.x;
if ((next_image->rows+next_image->page.y) > mng_info->page.height)
mng_info->page.height=next_image->rows+next_image->page.y;
}
if (next_image->page.x || next_image->page.y)
need_defi=MagickTrue;
if (next_image->matte)
need_matte=MagickTrue;
if ((int) next_image->dispose >= BackgroundDispose)
if (next_image->matte || next_image->page.x || next_image->page.y ||
((next_image->columns < mng_info->page.width) &&
(next_image->rows < mng_info->page.height)))
mng_info->need_fram=MagickTrue;
if (next_image->iterations)
need_iterations=MagickTrue;
final_delay=next_image->delay;
if (final_delay != initial_delay || final_delay > 1UL*
next_image->ticks_per_second)
mng_info->need_fram=1;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
check for global palette possibility.
*/
if (image->matte != MagickFalse)
need_local_plte=MagickTrue;
if (need_local_plte == 0)
{
if (SetImageGray(image,&image->exception) == MagickFalse)
all_images_are_gray=MagickFalse;
mng_info->equal_palettes=PalettesAreEqual(image,next_image);
if (use_global_plte == 0)
use_global_plte=mng_info->equal_palettes;
need_local_plte=!mng_info->equal_palettes;
}
#endif
if (GetNextImageInList(next_image) != (Image *) NULL)
{
if (next_image->background_color.red !=
next_image->next->background_color.red ||
next_image->background_color.green !=
next_image->next->background_color.green ||
next_image->background_color.blue !=
next_image->next->background_color.blue)
mng_info->equal_backgrounds=MagickFalse;
if (next_image->gamma != next_image->next->gamma)
mng_info->equal_gammas=MagickFalse;
if (next_image->rendering_intent !=
next_image->next->rendering_intent)
mng_info->equal_srgbs=MagickFalse;
if ((next_image->units != next_image->next->units) ||
(next_image->x_resolution != next_image->next->x_resolution) ||
(next_image->y_resolution != next_image->next->y_resolution))
mng_info->equal_physs=MagickFalse;
if (mng_info->equal_chrms)
{
if (next_image->chromaticity.red_primary.x !=
next_image->next->chromaticity.red_primary.x ||
next_image->chromaticity.red_primary.y !=
next_image->next->chromaticity.red_primary.y ||
next_image->chromaticity.green_primary.x !=
next_image->next->chromaticity.green_primary.x ||
next_image->chromaticity.green_primary.y !=
next_image->next->chromaticity.green_primary.y ||
next_image->chromaticity.blue_primary.x !=
next_image->next->chromaticity.blue_primary.x ||
next_image->chromaticity.blue_primary.y !=
next_image->next->chromaticity.blue_primary.y ||
next_image->chromaticity.white_point.x !=
next_image->next->chromaticity.white_point.x ||
next_image->chromaticity.white_point.y !=
next_image->next->chromaticity.white_point.y)
mng_info->equal_chrms=MagickFalse;
}
}
image_count++;
next_image=GetNextImageInList(next_image);
}
if (image_count < 2)
{
mng_info->equal_backgrounds=MagickFalse;
mng_info->equal_chrms=MagickFalse;
mng_info->equal_gammas=MagickFalse;
mng_info->equal_srgbs=MagickFalse;
mng_info->equal_physs=MagickFalse;
use_global_plte=MagickFalse;
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
need_local_plte=MagickTrue;
#endif
need_iterations=MagickFalse;
}
if (mng_info->need_fram == MagickFalse)
{
/*
Only certain framing rates 100/n are exactly representable without
the FRAM chunk but we'll allow some slop in VLC files
*/
if (final_delay == 0)
{
if (need_iterations != MagickFalse)
{
/*
It's probably a GIF with loop; don't run it *too* fast.
*/
if (mng_info->adjoin)
{
final_delay=10;
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderWarning,
"input has zero delay between all frames; assuming",
" 10 cs `%s'","");
}
}
else
mng_info->ticks_per_second=0;
}
if (final_delay != 0)
mng_info->ticks_per_second=(png_uint_32)
(image->ticks_per_second/final_delay);
if (final_delay > 50)
mng_info->ticks_per_second=2;
if (final_delay > 75)
mng_info->ticks_per_second=1;
if (final_delay > 125)
mng_info->need_fram=MagickTrue;
if (need_defi && final_delay > 2 && (final_delay != 4) &&
(final_delay != 5) && (final_delay != 10) && (final_delay != 20) &&
(final_delay != 25) && (final_delay != 50) &&
(final_delay != (size_t) image->ticks_per_second))
mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */
}
if (mng_info->need_fram != MagickFalse)
mng_info->ticks_per_second=1UL*image->ticks_per_second;
/*
If pseudocolor, we should also check to see if all the
palettes are identical and write a global PLTE if they are.
../glennrp Feb 99.
*/
/*
Write the MNG version 1.0 signature and MHDR chunk.
*/
(void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n");
(void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */
PNGType(chunk,mng_MHDR);
LogPNGChunk(logging,mng_MHDR,28L);
PNGLong(chunk+4,(png_uint_32) mng_info->page.width);
PNGLong(chunk+8,(png_uint_32) mng_info->page.height);
PNGLong(chunk+12,mng_info->ticks_per_second);
PNGLong(chunk+16,0L); /* layer count=unknown */
PNGLong(chunk+20,0L); /* frame count=unknown */
PNGLong(chunk+24,0L); /* play time=unknown */
if (write_jng)
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,27L); /* simplicity=LC+JNG */
else
PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */
else
PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */
}
}
else
{
if (need_matte)
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,11L); /* simplicity=LC */
else
PNGLong(chunk+28,9L); /* simplicity=VLC */
}
else
{
if (need_defi || mng_info->need_fram || use_global_plte)
PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */
else
PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */
}
}
(void) WriteBlob(image,32,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,32));
option=GetImageOption(image_info,"mng:need-cacheoff");
if (option != (const char *) NULL)
{
size_t
length;
/*
Write "nEED CACHEOFF" to turn playback caching off for streaming MNG.
*/
PNGType(chunk,mng_nEED);
length=CopyMagickString((char *) chunk+4,"CACHEOFF",20);
(void) WriteBlobMSBULong(image,(size_t) length);
LogPNGChunk(logging,mng_nEED,(size_t) length);
length+=4;
(void) WriteBlob(image,length,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length));
}
if ((GetPreviousImageInList(image) == (Image *) NULL) &&
(GetNextImageInList(image) != (Image *) NULL) &&
(image->iterations != 1))
{
/*
Write MNG TERM chunk
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_TERM);
LogPNGChunk(logging,mng_TERM,10L);
chunk[4]=3; /* repeat animation */
chunk[5]=0; /* show last frame when done */
PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
PNGLong(chunk+10,PNG_UINT_31_MAX);
else
PNGLong(chunk+10,(png_uint_32) image->iterations);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM delay: %.20g",(double) (mng_info->ticks_per_second*
final_delay/MagickMax(image->ticks_per_second,1)));
if (image->iterations == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" TERM iterations: %.20g",(double) PNG_UINT_31_MAX);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image iterations: %.20g",(double) image->iterations);
}
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
}
/*
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if ((image->colorspace == sRGBColorspace || image->rendering_intent) &&
mng_info->equal_srgbs)
{
/*
Write MNG sRGB chunk
*/
(void) WriteBlobMSBULong(image,1L);
PNGType(chunk,mng_sRGB);
LogPNGChunk(logging,mng_sRGB,1L);
if (image->rendering_intent != UndefinedIntent)
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(image->rendering_intent));
else
chunk[4]=(unsigned char)
Magick_RenderingIntent_to_PNG_RenderingIntent(
(PerceptualIntent));
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
mng_info->have_write_global_srgb=MagickTrue;
}
else
{
if (image->gamma && mng_info->equal_gammas)
{
/*
Write MNG gAMA chunk
*/
(void) WriteBlobMSBULong(image,4L);
PNGType(chunk,mng_gAMA);
LogPNGChunk(logging,mng_gAMA,4L);
PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));
(void) WriteBlob(image,8,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,8));
mng_info->have_write_global_gama=MagickTrue;
}
if (mng_info->equal_chrms)
{
PrimaryInfo
primary;
/*
Write MNG cHRM chunk
*/
(void) WriteBlobMSBULong(image,32L);
PNGType(chunk,mng_cHRM);
LogPNGChunk(logging,mng_cHRM,32L);
primary=image->chromaticity.white_point;
PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.red_primary;
PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.green_primary;
PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));
primary=image->chromaticity.blue_primary;
PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));
PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));
(void) WriteBlob(image,36,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,36));
mng_info->have_write_global_chrm=MagickTrue;
}
}
if (image->x_resolution && image->y_resolution && mng_info->equal_physs)
{
/*
Write MNG pHYs chunk
*/
(void) WriteBlobMSBULong(image,9L);
PNGType(chunk,mng_pHYs);
LogPNGChunk(logging,mng_pHYs,9L);
if (image->units == PixelsPerInchResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0/2.54+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0/2.54+0.5));
chunk[12]=1;
}
else
{
if (image->units == PixelsPerCentimeterResolution)
{
PNGLong(chunk+4,(png_uint_32)
(image->x_resolution*100.0+0.5));
PNGLong(chunk+8,(png_uint_32)
(image->y_resolution*100.0+0.5));
chunk[12]=1;
}
else
{
PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5));
PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5));
chunk[12]=0;
}
}
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
/*
Write MNG BACK chunk and global bKGD chunk, if the image is transparent
or does not cover the entire frame.
*/
if (write_mng && (image->matte || image->page.x > 0 ||
image->page.y > 0 || (image->page.width &&
(image->page.width+image->page.x < mng_info->page.width))
|| (image->page.height && (image->page.height+image->page.y
< mng_info->page.height))))
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_BACK);
LogPNGChunk(logging,mng_BACK,6L);
red=ScaleQuantumToShort(image->background_color.red);
green=ScaleQuantumToShort(image->background_color.green);
blue=ScaleQuantumToShort(image->background_color.blue);
PNGShort(chunk+4,red);
PNGShort(chunk+6,green);
PNGShort(chunk+8,blue);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
if (mng_info->equal_backgrounds)
{
(void) WriteBlobMSBULong(image,6L);
PNGType(chunk,mng_bKGD);
LogPNGChunk(logging,mng_bKGD,6L);
(void) WriteBlob(image,10,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,10));
}
}
#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if ((need_local_plte == MagickFalse) &&
(image->storage_class == PseudoClass) &&
(all_images_are_gray == MagickFalse))
{
size_t
data_length;
/*
Write MNG PLTE chunk
*/
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff;
chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff;
chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff;
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
#endif
}
scene=0;
mng_info->delay=0;
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
mng_info->equal_palettes=MagickFalse;
#endif
do
{
if (mng_info->adjoin)
{
#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \
defined(PNG_MNG_FEATURES_SUPPORTED)
/*
If we aren't using a global palette for the entire MNG, check to
see if we can use one for two or more consecutive images.
*/
if (need_local_plte && use_global_plte && !all_images_are_gray)
{
if (mng_info->IsPalette)
{
/*
When equal_palettes is true, this image has the same palette
as the previous PseudoClass image
*/
mng_info->have_write_global_plte=mng_info->equal_palettes;
mng_info->equal_palettes=PalettesAreEqual(image,image->next);
if (mng_info->equal_palettes && !mng_info->have_write_global_plte)
{
/*
Write MNG PLTE chunk
*/
size_t
data_length;
data_length=3*image->colors;
(void) WriteBlobMSBULong(image,data_length);
PNGType(chunk,mng_PLTE);
LogPNGChunk(logging,mng_PLTE,data_length);
for (i=0; i < (ssize_t) image->colors; i++)
{
chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red);
chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green);
chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue);
}
(void) WriteBlob(image,data_length+4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,
(uInt) (data_length+4)));
mng_info->have_write_global_plte=MagickTrue;
}
}
else
mng_info->have_write_global_plte=MagickFalse;
}
#endif
if (need_defi)
{
ssize_t
previous_x,
previous_y;
if (scene != 0)
{
previous_x=mng_info->page.x;
previous_y=mng_info->page.y;
}
else
{
previous_x=0;
previous_y=0;
}
mng_info->page=image->page;
if ((mng_info->page.x != previous_x) ||
(mng_info->page.y != previous_y))
{
(void) WriteBlobMSBULong(image,12L); /* data length=12 */
PNGType(chunk,mng_DEFI);
LogPNGChunk(logging,mng_DEFI,12L);
chunk[4]=0; /* object 0 MSB */
chunk[5]=0; /* object 0 LSB */
chunk[6]=0; /* visible */
chunk[7]=0; /* abstract */
PNGLong(chunk+8,(png_uint_32) mng_info->page.x);
PNGLong(chunk+12,(png_uint_32) mng_info->page.y);
(void) WriteBlob(image,16,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,16));
}
}
}
mng_info->write_mng=write_mng;
if ((int) image->dispose >= 3)
mng_info->framing_mode=3;
if (mng_info->need_fram && mng_info->adjoin &&
((image->delay != mng_info->delay) ||
(mng_info->framing_mode != mng_info->old_framing_mode)))
{
if (image->delay == mng_info->delay)
{
/*
Write a MNG FRAM chunk with the new framing mode.
*/
(void) WriteBlobMSBULong(image,1L); /* data length=1 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,1L);
chunk[4]=(unsigned char) mng_info->framing_mode;
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
else
{
/*
Write a MNG FRAM chunk with the delay.
*/
(void) WriteBlobMSBULong(image,10L); /* data length=10 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,10L);
chunk[4]=(unsigned char) mng_info->framing_mode;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=2; /* flag for changing default delay */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=0; /* flag for changing frame clipping */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32)
((mng_info->ticks_per_second*
image->delay)/MagickMax(image->ticks_per_second,1)));
(void) WriteBlob(image,14,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,14));
mng_info->delay=(png_uint_32) image->delay;
}
mng_info->old_framing_mode=mng_info->framing_mode;
}
#if defined(JNG_SUPPORTED)
if (image_info->compression == JPEGCompression)
{
ImageInfo
*write_info;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing JNG object.");
/* To do: specify the desired alpha compression method. */
write_info=CloneImageInfo(image_info);
write_info->compression=UndefinedCompression;
status=WriteOneJNGImage(mng_info,write_info,image);
write_info=DestroyImageInfo(write_info);
}
else
#endif
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG object.");
mng_info->need_blob = MagickFalse;
mng_info->ping_preserve_colormap = MagickFalse;
/* We don't want any ancillary chunks written */
mng_info->ping_exclude_bKGD=MagickTrue;
mng_info->ping_exclude_caNv=MagickTrue;
mng_info->ping_exclude_cHRM=MagickTrue;
mng_info->ping_exclude_date=MagickTrue;
mng_info->ping_exclude_EXIF=MagickTrue;
mng_info->ping_exclude_eXIf=MagickTrue;
mng_info->ping_exclude_gAMA=MagickTrue;
mng_info->ping_exclude_iCCP=MagickTrue;
/* mng_info->ping_exclude_iTXt=MagickTrue; */
mng_info->ping_exclude_oFFs=MagickTrue;
mng_info->ping_exclude_pHYs=MagickTrue;
mng_info->ping_exclude_sRGB=MagickTrue;
mng_info->ping_exclude_tEXt=MagickTrue;
mng_info->ping_exclude_tRNS=MagickTrue;
mng_info->ping_exclude_vpAg=MagickTrue;
mng_info->ping_exclude_zCCP=MagickTrue;
mng_info->ping_exclude_zTXt=MagickTrue;
status=WriteOnePNGImage(mng_info,image_info,image);
}
if (status == MagickFalse)
{
mng_info=MngInfoFreeStruct(mng_info);
(void) CloseBlob(image);
return(MagickFalse);
}
(void) CatchImageException(image);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (mng_info->adjoin);
if (write_mng)
{
while (GetPreviousImageInList(image) != (Image *) NULL)
image=GetPreviousImageInList(image);
/*
Write the MEND chunk.
*/
(void) WriteBlobMSBULong(image,0x00000000L);
PNGType(chunk,mng_MEND);
LogPNGChunk(logging,mng_MEND,0L);
(void) WriteBlob(image,4,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,4));
}
/*
Relinquish resources.
*/
(void) CloseBlob(image);
mng_info=MngInfoFreeStruct(mng_info);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()");
return(MagickTrue);
}
#else /* PNG_LIBPNG_VER > 10011 */
static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image)
{
(void) image;
printf("Your PNG library is too old: You have libpng-%s\n",
PNG_LIBPNG_VER_STRING);
ThrowBinaryException(CoderError,"PNG library is too old",
image_info->filename);
}
static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image)
{
return(WritePNGImage(image_info,image));
}
#endif /* PNG_LIBPNG_VER > 10011 */
#endif
| ./CrossVul/dataset_final_sorted/CWE-770/c/bad_2614_0 |
crossvul-cpp_data_bad_367_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-2018 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/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.
*/
if (bmp_info.ba_offset == 0)
start_position=TellBlob(image)-2;
bmp_info.ba_offset=0;
while (LocaleNCompare((char *) magick,"BA",2) == 0)
{
bmp_info.file_size=ReadBlobLSBLong(image);
bmp_info.ba_offset=ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
count=ReadBlob(image,2,magick);
if (count != 2)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c",
magick[0],magick[1]);
if ((count != 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);
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 (((MagickSizeType) length/8) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
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-770/c/bad_367_0 |
crossvul-cpp_data_bad_1054_0 | /* 69df5be70289a11fb834869ce4a91c23c1d9dd04baffcbd10e86742d149a080c (2.2.7+)
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000-2017 Expat development team
Licensed under the MIT license:
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.
*/
#if ! defined(_GNU_SOURCE)
# define _GNU_SOURCE 1 /* syscall prototype */
#endif
#ifdef _WIN32
/* force stdlib to define rand_s() */
# define _CRT_RAND_S
#endif
#include <stddef.h>
#include <string.h> /* memset(), memcpy() */
#include <assert.h>
#include <limits.h> /* UINT_MAX */
#include <stdio.h> /* fprintf */
#include <stdlib.h> /* getenv, rand_s */
#ifdef _WIN32
# define getpid GetCurrentProcessId
#else
# include <sys/time.h> /* gettimeofday() */
# include <sys/types.h> /* getpid() */
# include <unistd.h> /* getpid() */
# include <fcntl.h> /* O_RDONLY */
# include <errno.h>
#endif
#define XML_BUILDING_EXPAT 1
#ifdef _WIN32
# include "winconfig.h"
#elif defined(HAVE_EXPAT_CONFIG_H)
# include <expat_config.h>
#endif /* ndef _WIN32 */
#include "ascii.h"
#include "expat.h"
#include "siphash.h"
#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
# if defined(HAVE_GETRANDOM)
# include <sys/random.h> /* getrandom */
# else
# include <unistd.h> /* syscall */
# include <sys/syscall.h> /* SYS_getrandom */
# endif
# if ! defined(GRND_NONBLOCK)
# define GRND_NONBLOCK 0x0001
# endif /* defined(GRND_NONBLOCK) */
#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
#if defined(HAVE_LIBBSD) \
&& (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
# include <bsd/stdlib.h>
#endif
#if defined(_WIN32) && ! defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
#if ! defined(HAVE_GETRANDOM) && ! defined(HAVE_SYSCALL_GETRANDOM) \
&& ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) \
&& ! defined(XML_DEV_URANDOM) && ! defined(_WIN32) \
&& ! defined(XML_POOR_ENTROPY)
# error You do not have support for any sources of high quality entropy \
enabled. For end user security, that is probably not what you want. \
\
Your options include: \
* Linux + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
* Linux + glibc <2.25 (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
* BSD / macOS >=10.7 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
* BSD / macOS <10.7 (arc4random): HAVE_ARC4RANDOM, \
* libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
* libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
* Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \
* Windows (rand_s): _WIN32. \
\
If insist on not using any of these, bypass this error by defining \
XML_POOR_ENTROPY; you have been warned. \
\
If you have reasons to patch this detection code away or need changes \
to the build system, please open a bug. Thank you!
#endif
#ifdef XML_UNICODE
# define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
# define XmlConvert XmlUtf16Convert
# define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
# define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
# define XmlEncode XmlUtf16Encode
/* Using pointer subtraction to convert to integer type. */
# define MUST_CONVERT(enc, s) \
(! (enc)->isUtf16 || (((char *)(s) - (char *)NULL) & 1))
typedef unsigned short ICHAR;
#else
# define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
# define XmlConvert XmlUtf8Convert
# define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
# define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
# define XmlEncode XmlUtf8Encode
# define MUST_CONVERT(enc, s) (! (enc)->isUtf8)
typedef char ICHAR;
#endif
#ifndef XML_NS
# define XmlInitEncodingNS XmlInitEncoding
# define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
# undef XmlGetInternalEncodingNS
# define XmlGetInternalEncodingNS XmlGetInternalEncoding
# define XmlParseXmlDeclNS XmlParseXmlDecl
#endif
#ifdef XML_UNICODE
# ifdef XML_UNICODE_WCHAR_T
# define XML_T(x) (const wchar_t) x
# define XML_L(x) L##x
# else
# define XML_T(x) (const unsigned short)x
# define XML_L(x) x
# endif
#else
# define XML_T(x) x
# define XML_L(x) x
#endif
/* Round up n to be a multiple of sz, where sz is a power of 2. */
#define ROUND_UP(n, sz) (((n) + ((sz)-1)) & ~((sz)-1))
/* Do safe (NULL-aware) pointer arithmetic */
#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
#include "internal.h"
#include "xmltok.h"
#include "xmlrole.h"
typedef const XML_Char *KEY;
typedef struct {
KEY name;
} NAMED;
typedef struct {
NAMED **v;
unsigned char power;
size_t size;
size_t used;
const XML_Memory_Handling_Suite *mem;
} HASH_TABLE;
static size_t keylen(KEY s);
static void copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key);
/* For probing (after a collision) we need a step size relative prime
to the hash table size, which is a power of 2. We use double-hashing,
since we can calculate a second hash value cheaply by taking those bits
of the first hash value that were discarded (masked out) when the table
index was calculated: index = hash & mask, where mask = table->size - 1.
We limit the maximum step size to table->size / 4 (mask >> 2) and make
it odd, since odd numbers are always relative prime to a power of 2.
*/
#define SECOND_HASH(hash, mask, power) \
((((hash) & ~(mask)) >> ((power)-1)) & ((mask) >> 2))
#define PROBE_STEP(hash, mask, power) \
((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
typedef struct {
NAMED **p;
NAMED **end;
} HASH_TABLE_ITER;
#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
#define INIT_DATA_BUF_SIZE 1024
#define INIT_ATTS_SIZE 16
#define INIT_ATTS_VERSION 0xFFFFFFFF
#define INIT_BLOCK_SIZE 1024
#define INIT_BUFFER_SIZE 1024
#define EXPAND_SPARE 24
typedef struct binding {
struct prefix *prefix;
struct binding *nextTagBinding;
struct binding *prevPrefixBinding;
const struct attribute_id *attId;
XML_Char *uri;
int uriLen;
int uriAlloc;
} BINDING;
typedef struct prefix {
const XML_Char *name;
BINDING *binding;
} PREFIX;
typedef struct {
const XML_Char *str;
const XML_Char *localPart;
const XML_Char *prefix;
int strLen;
int uriLen;
int prefixLen;
} TAG_NAME;
/* TAG represents an open element.
The name of the element is stored in both the document and API
encodings. The memory buffer 'buf' is a separately-allocated
memory area which stores the name. During the XML_Parse()/
XMLParseBuffer() when the element is open, the memory for the 'raw'
version of the name (in the document encoding) is shared with the
document buffer. If the element is open across calls to
XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to
contain the 'raw' name as well.
A parser re-uses these structures, maintaining a list of allocated
TAG objects in a free list.
*/
typedef struct tag {
struct tag *parent; /* parent of this element */
const char *rawName; /* tagName in the original encoding */
int rawNameLength;
TAG_NAME name; /* tagName in the API encoding */
char *buf; /* buffer for name components */
char *bufEnd; /* end of the buffer */
BINDING *bindings;
} TAG;
typedef struct {
const XML_Char *name;
const XML_Char *textPtr;
int textLen; /* length in XML_Chars */
int processed; /* # of processed bytes - when suspended */
const XML_Char *systemId;
const XML_Char *base;
const XML_Char *publicId;
const XML_Char *notation;
XML_Bool open;
XML_Bool is_param;
XML_Bool is_internal; /* true if declared in internal subset outside PE */
} ENTITY;
typedef struct {
enum XML_Content_Type type;
enum XML_Content_Quant quant;
const XML_Char *name;
int firstchild;
int lastchild;
int childcnt;
int nextsib;
} CONTENT_SCAFFOLD;
#define INIT_SCAFFOLD_ELEMENTS 32
typedef struct block {
struct block *next;
int size;
XML_Char s[1];
} BLOCK;
typedef struct {
BLOCK *blocks;
BLOCK *freeBlocks;
const XML_Char *end;
XML_Char *ptr;
XML_Char *start;
const XML_Memory_Handling_Suite *mem;
} STRING_POOL;
/* The XML_Char before the name is used to determine whether
an attribute has been specified. */
typedef struct attribute_id {
XML_Char *name;
PREFIX *prefix;
XML_Bool maybeTokenized;
XML_Bool xmlns;
} ATTRIBUTE_ID;
typedef struct {
const ATTRIBUTE_ID *id;
XML_Bool isCdata;
const XML_Char *value;
} DEFAULT_ATTRIBUTE;
typedef struct {
unsigned long version;
unsigned long hash;
const XML_Char *uriName;
} NS_ATT;
typedef struct {
const XML_Char *name;
PREFIX *prefix;
const ATTRIBUTE_ID *idAtt;
int nDefaultAtts;
int allocDefaultAtts;
DEFAULT_ATTRIBUTE *defaultAtts;
} ELEMENT_TYPE;
typedef struct {
HASH_TABLE generalEntities;
HASH_TABLE elementTypes;
HASH_TABLE attributeIds;
HASH_TABLE prefixes;
STRING_POOL pool;
STRING_POOL entityValuePool;
/* false once a parameter entity reference has been skipped */
XML_Bool keepProcessing;
/* true once an internal or external PE reference has been encountered;
this includes the reference to an external subset */
XML_Bool hasParamEntityRefs;
XML_Bool standalone;
#ifdef XML_DTD
/* indicates if external PE has been read */
XML_Bool paramEntityRead;
HASH_TABLE paramEntities;
#endif /* XML_DTD */
PREFIX defaultPrefix;
/* === scaffolding for building content model === */
XML_Bool in_eldecl;
CONTENT_SCAFFOLD *scaffold;
unsigned contentStringLen;
unsigned scaffSize;
unsigned scaffCount;
int scaffLevel;
int *scaffIndex;
} DTD;
typedef struct open_internal_entity {
const char *internalEventPtr;
const char *internalEventEndPtr;
struct open_internal_entity *next;
ENTITY *entity;
int startTagLevel;
XML_Bool betweenDecl; /* WFC: PE Between Declarations */
} OPEN_INTERNAL_ENTITY;
typedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,
const char *end, const char **endPtr);
static Processor prologProcessor;
static Processor prologInitProcessor;
static Processor contentProcessor;
static Processor cdataSectionProcessor;
#ifdef XML_DTD
static Processor ignoreSectionProcessor;
static Processor externalParEntProcessor;
static Processor externalParEntInitProcessor;
static Processor entityValueProcessor;
static Processor entityValueInitProcessor;
#endif /* XML_DTD */
static Processor epilogProcessor;
static Processor errorProcessor;
static Processor externalEntityInitProcessor;
static Processor externalEntityInitProcessor2;
static Processor externalEntityInitProcessor3;
static Processor externalEntityContentProcessor;
static Processor internalEntityProcessor;
static enum XML_Error handleUnknownEncoding(XML_Parser parser,
const XML_Char *encodingName);
static enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
const char *s, const char *next);
static enum XML_Error initializeEncoding(XML_Parser parser);
static enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,
const char *s, const char *end, int tok,
const char *next, const char **nextPtr,
XML_Bool haveMore);
static enum XML_Error processInternalEntity(XML_Parser parser, ENTITY *entity,
XML_Bool betweenDecl);
static enum XML_Error doContent(XML_Parser parser, int startTagLevel,
const ENCODING *enc, const char *start,
const char *end, const char **endPtr,
XML_Bool haveMore);
static enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *,
const char **startPtr, const char *end,
const char **nextPtr, XML_Bool haveMore);
#ifdef XML_DTD
static enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *,
const char **startPtr, const char *end,
const char **nextPtr, XML_Bool haveMore);
#endif /* XML_DTD */
static void freeBindings(XML_Parser parser, BINDING *bindings);
static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *,
const char *s, TAG_NAME *tagNamePtr,
BINDING **bindingsPtr);
static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,
const ATTRIBUTE_ID *attId, const XML_Char *uri,
BINDING **bindingsPtr);
static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata,
XML_Bool isId, const XML_Char *dfltValue,
XML_Parser parser);
static enum XML_Error storeAttributeValue(XML_Parser parser, const ENCODING *,
XML_Bool isCdata, const char *,
const char *, STRING_POOL *);
static enum XML_Error appendAttributeValue(XML_Parser parser, const ENCODING *,
XML_Bool isCdata, const char *,
const char *, STRING_POOL *);
static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *);
static enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int reportComment(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static void reportDefault(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static const XML_Char *getContext(XML_Parser parser);
static XML_Bool setContext(XML_Parser parser, const XML_Char *context);
static void FASTCALL normalizePublicId(XML_Char *s);
static DTD *dtdCreate(const XML_Memory_Handling_Suite *ms);
/* do not call if m_parentParser != NULL */
static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
static void dtdDestroy(DTD *p, XML_Bool isDocEntity,
const XML_Memory_Handling_Suite *ms);
static int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
const XML_Memory_Handling_Suite *ms);
static int copyEntityTable(XML_Parser oldParser, HASH_TABLE *, STRING_POOL *,
const HASH_TABLE *);
static NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,
size_t createSize);
static void FASTCALL hashTableInit(HASH_TABLE *,
const XML_Memory_Handling_Suite *ms);
static void FASTCALL hashTableClear(HASH_TABLE *);
static void FASTCALL hashTableDestroy(HASH_TABLE *);
static void FASTCALL hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *);
static NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *);
static void FASTCALL poolInit(STRING_POOL *,
const XML_Memory_Handling_Suite *ms);
static void FASTCALL poolClear(STRING_POOL *);
static void FASTCALL poolDestroy(STRING_POOL *);
static XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
static const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,
const XML_Char *s);
static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,
int n);
static const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,
const XML_Char *s);
static int FASTCALL nextScaffoldPart(XML_Parser parser);
static XML_Content *build_model(XML_Parser parser);
static ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *copyString(const XML_Char *s,
const XML_Memory_Handling_Suite *memsuite);
static unsigned long generate_hash_secret_salt(XML_Parser parser);
static XML_Bool startParsing(XML_Parser parser);
static XML_Parser parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep, DTD *dtd);
static void parserInit(XML_Parser parser, const XML_Char *encodingName);
#define poolStart(pool) ((pool)->start)
#define poolEnd(pool) ((pool)->ptr)
#define poolLength(pool) ((pool)->ptr - (pool)->start)
#define poolChop(pool) ((void)--(pool->ptr))
#define poolLastChar(pool) (((pool)->ptr)[-1])
#define poolDiscard(pool) ((pool)->ptr = (pool)->start)
#define poolFinish(pool) ((pool)->start = (pool)->ptr)
#define poolAppendChar(pool, c) \
(((pool)->ptr == (pool)->end && ! poolGrow(pool)) \
? 0 \
: ((*((pool)->ptr)++ = c), 1))
struct XML_ParserStruct {
/* The first member must be m_userData so that the XML_GetUserData
macro works. */
void *m_userData;
void *m_handlerArg;
char *m_buffer;
const XML_Memory_Handling_Suite m_mem;
/* first character to be parsed */
const char *m_bufferPtr;
/* past last character to be parsed */
char *m_bufferEnd;
/* allocated end of m_buffer */
const char *m_bufferLim;
XML_Index m_parseEndByteIndex;
const char *m_parseEndPtr;
XML_Char *m_dataBuf;
XML_Char *m_dataBufEnd;
XML_StartElementHandler m_startElementHandler;
XML_EndElementHandler m_endElementHandler;
XML_CharacterDataHandler m_characterDataHandler;
XML_ProcessingInstructionHandler m_processingInstructionHandler;
XML_CommentHandler m_commentHandler;
XML_StartCdataSectionHandler m_startCdataSectionHandler;
XML_EndCdataSectionHandler m_endCdataSectionHandler;
XML_DefaultHandler m_defaultHandler;
XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
XML_NotationDeclHandler m_notationDeclHandler;
XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
XML_NotStandaloneHandler m_notStandaloneHandler;
XML_ExternalEntityRefHandler m_externalEntityRefHandler;
XML_Parser m_externalEntityRefHandlerArg;
XML_SkippedEntityHandler m_skippedEntityHandler;
XML_UnknownEncodingHandler m_unknownEncodingHandler;
XML_ElementDeclHandler m_elementDeclHandler;
XML_AttlistDeclHandler m_attlistDeclHandler;
XML_EntityDeclHandler m_entityDeclHandler;
XML_XmlDeclHandler m_xmlDeclHandler;
const ENCODING *m_encoding;
INIT_ENCODING m_initEncoding;
const ENCODING *m_internalEncoding;
const XML_Char *m_protocolEncodingName;
XML_Bool m_ns;
XML_Bool m_ns_triplets;
void *m_unknownEncodingMem;
void *m_unknownEncodingData;
void *m_unknownEncodingHandlerData;
void(XMLCALL *m_unknownEncodingRelease)(void *);
PROLOG_STATE m_prologState;
Processor *m_processor;
enum XML_Error m_errorCode;
const char *m_eventPtr;
const char *m_eventEndPtr;
const char *m_positionPtr;
OPEN_INTERNAL_ENTITY *m_openInternalEntities;
OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
XML_Bool m_defaultExpandInternalEntities;
int m_tagLevel;
ENTITY *m_declEntity;
const XML_Char *m_doctypeName;
const XML_Char *m_doctypeSysid;
const XML_Char *m_doctypePubid;
const XML_Char *m_declAttributeType;
const XML_Char *m_declNotationName;
const XML_Char *m_declNotationPublicId;
ELEMENT_TYPE *m_declElementType;
ATTRIBUTE_ID *m_declAttributeId;
XML_Bool m_declAttributeIsCdata;
XML_Bool m_declAttributeIsId;
DTD *m_dtd;
const XML_Char *m_curBase;
TAG *m_tagStack;
TAG *m_freeTagList;
BINDING *m_inheritedBindings;
BINDING *m_freeBindingList;
int m_attsSize;
int m_nSpecifiedAtts;
int m_idAttIndex;
ATTRIBUTE *m_atts;
NS_ATT *m_nsAtts;
unsigned long m_nsAttsVersion;
unsigned char m_nsAttsPower;
#ifdef XML_ATTR_INFO
XML_AttrInfo *m_attInfo;
#endif
POSITION m_position;
STRING_POOL m_tempPool;
STRING_POOL m_temp2Pool;
char *m_groupConnector;
unsigned int m_groupSize;
XML_Char m_namespaceSeparator;
XML_Parser m_parentParser;
XML_ParsingStatus m_parsingStatus;
#ifdef XML_DTD
XML_Bool m_isParamEntity;
XML_Bool m_useForeignDTD;
enum XML_ParamEntityParsing m_paramEntityParsing;
#endif
unsigned long m_hash_secret_salt;
};
#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))
#define FREE(parser, p) (parser->m_mem.free_fcn((p)))
XML_Parser XMLCALL
XML_ParserCreate(const XML_Char *encodingName) {
return XML_ParserCreate_MM(encodingName, NULL, NULL);
}
XML_Parser XMLCALL
XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {
XML_Char tmp[2];
*tmp = nsSep;
return XML_ParserCreate_MM(encodingName, NULL, tmp);
}
static const XML_Char implicitContext[]
= {ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h,
ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD,
ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r,
ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,
ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8,
ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,
ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e,
'\0'};
/* To avoid warnings about unused functions: */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
# if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
/* Obtain entropy on Linux 3.17+ */
static int
writeRandomBytes_getrandom_nonblock(void *target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const unsigned int getrandomFlags = GRND_NONBLOCK;
do {
void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const int bytesWrittenMore =
# if defined(HAVE_GETRANDOM)
getrandom(currentTarget, bytesToWrite, getrandomFlags);
# else
syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
# endif
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
return success;
}
# endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
# if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
/* Extract entropy from /dev/urandom */
static int
writeRandomBytes_dev_urandom(void *target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
return 0;
}
do {
void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
close(fd);
return success;
}
# endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
static void
writeRandomBytes_arc4random(void *target, size_t count) {
size_t bytesWrittenTotal = 0;
while (bytesWrittenTotal < count) {
const uint32_t random32 = arc4random();
size_t i = 0;
for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
i++, bytesWrittenTotal++) {
const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
((uint8_t *)target)[bytesWrittenTotal] = random8;
}
}
}
#endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
#ifdef _WIN32
/* Obtain entropy on Windows using the rand_s() function which
* generates cryptographically secure random numbers. Internally it
* uses RtlGenRandom API which is present in Windows XP and later.
*/
static int
writeRandomBytes_rand_s(void *target, size_t count) {
size_t bytesWrittenTotal = 0;
while (bytesWrittenTotal < count) {
unsigned int random32 = 0;
size_t i = 0;
if (rand_s(&random32))
return 0; /* failure */
for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
i++, bytesWrittenTotal++) {
const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
((uint8_t *)target)[bytesWrittenTotal] = random8;
}
}
return 1; /* success */
}
#endif /* _WIN32 */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
static unsigned long
gather_time_entropy(void) {
# ifdef _WIN32
FILETIME ft;
GetSystemTimeAsFileTime(&ft); /* never fails */
return ft.dwHighDateTime ^ ft.dwLowDateTime;
# else
struct timeval tv;
int gettimeofday_res;
gettimeofday_res = gettimeofday(&tv, NULL);
# if defined(NDEBUG)
(void)gettimeofday_res;
# else
assert(gettimeofday_res == 0);
# endif /* defined(NDEBUG) */
/* Microseconds time is <20 bits entropy */
return tv.tv_usec;
# endif
}
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
static unsigned long
ENTROPY_DEBUG(const char *label, unsigned long entropy) {
const char *const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) {
fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n", label,
(int)sizeof(entropy) * 2, entropy, (unsigned long)sizeof(entropy));
}
return entropy;
}
static unsigned long
generate_hash_secret_salt(XML_Parser parser) {
unsigned long entropy;
(void)parser;
/* "Failproof" high quality providers: */
#if defined(HAVE_ARC4RANDOM_BUF)
arc4random_buf(&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random_buf", entropy);
#elif defined(HAVE_ARC4RANDOM)
writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random", entropy);
#else
/* Try high quality providers first .. */
# ifdef _WIN32
if (writeRandomBytes_rand_s((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("rand_s", entropy);
}
# elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("getrandom", entropy);
}
# endif
# if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("/dev/urandom", entropy);
}
# endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
/* .. and self-made low quality for backup: */
/* Process ID is 0 bits entropy if attacker has local access */
entropy = gather_time_entropy() ^ getpid();
/* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
if (sizeof(unsigned long) == 4) {
return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
} else {
return ENTROPY_DEBUG("fallback(8)",
entropy * (unsigned long)2305843009213693951ULL);
}
#endif
}
static unsigned long
get_hash_secret_salt(XML_Parser parser) {
if (parser->m_parentParser != NULL)
return get_hash_secret_salt(parser->m_parentParser);
return parser->m_hash_secret_salt;
}
static XML_Bool /* only valid for root parser */
startParsing(XML_Parser parser) {
/* hash functions must be initialized before setContext() is called */
if (parser->m_hash_secret_salt == 0)
parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
if (parser->m_ns) {
/* implicit context only set for root parser, since child
parsers (i.e. external entity parsers) will inherit it
*/
return setContext(parser, implicitContext);
}
return XML_TRUE;
}
XML_Parser XMLCALL
XML_ParserCreate_MM(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep) {
return parserCreate(encodingName, memsuite, nameSep, NULL);
}
static XML_Parser
parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,
DTD *dtd) {
XML_Parser parser;
if (memsuite) {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = memsuite->malloc_fcn;
mtemp->realloc_fcn = memsuite->realloc_fcn;
mtemp->free_fcn = memsuite->free_fcn;
}
} else {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = malloc;
mtemp->realloc_fcn = realloc;
mtemp->free_fcn = free;
}
}
if (! parser)
return parser;
parser->m_buffer = NULL;
parser->m_bufferLim = NULL;
parser->m_attsSize = INIT_ATTS_SIZE;
parser->m_atts
= (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
if (parser->m_atts == NULL) {
FREE(parser, parser);
return NULL;
}
#ifdef XML_ATTR_INFO
parser->m_attInfo = (XML_AttrInfo *)MALLOC(
parser, parser->m_attsSize * sizeof(XML_AttrInfo));
if (parser->m_attInfo == NULL) {
FREE(parser, parser->m_atts);
FREE(parser, parser);
return NULL;
}
#endif
parser->m_dataBuf
= (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
if (parser->m_dataBuf == NULL) {
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
if (dtd)
parser->m_dtd = dtd;
else {
parser->m_dtd = dtdCreate(&parser->m_mem);
if (parser->m_dtd == NULL) {
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
}
parser->m_freeBindingList = NULL;
parser->m_freeTagList = NULL;
parser->m_freeInternalEntities = NULL;
parser->m_groupSize = 0;
parser->m_groupConnector = NULL;
parser->m_unknownEncodingHandler = NULL;
parser->m_unknownEncodingHandlerData = NULL;
parser->m_namespaceSeparator = ASCII_EXCL;
parser->m_ns = XML_FALSE;
parser->m_ns_triplets = XML_FALSE;
parser->m_nsAtts = NULL;
parser->m_nsAttsVersion = 0;
parser->m_nsAttsPower = 0;
parser->m_protocolEncodingName = NULL;
poolInit(&parser->m_tempPool, &(parser->m_mem));
poolInit(&parser->m_temp2Pool, &(parser->m_mem));
parserInit(parser, encodingName);
if (encodingName && ! parser->m_protocolEncodingName) {
XML_ParserFree(parser);
return NULL;
}
if (nameSep) {
parser->m_ns = XML_TRUE;
parser->m_internalEncoding = XmlGetInternalEncodingNS();
parser->m_namespaceSeparator = *nameSep;
} else {
parser->m_internalEncoding = XmlGetInternalEncoding();
}
return parser;
}
static void
parserInit(XML_Parser parser, const XML_Char *encodingName) {
parser->m_processor = prologInitProcessor;
XmlPrologStateInit(&parser->m_prologState);
if (encodingName != NULL) {
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
}
parser->m_curBase = NULL;
XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
parser->m_userData = NULL;
parser->m_handlerArg = NULL;
parser->m_startElementHandler = NULL;
parser->m_endElementHandler = NULL;
parser->m_characterDataHandler = NULL;
parser->m_processingInstructionHandler = NULL;
parser->m_commentHandler = NULL;
parser->m_startCdataSectionHandler = NULL;
parser->m_endCdataSectionHandler = NULL;
parser->m_defaultHandler = NULL;
parser->m_startDoctypeDeclHandler = NULL;
parser->m_endDoctypeDeclHandler = NULL;
parser->m_unparsedEntityDeclHandler = NULL;
parser->m_notationDeclHandler = NULL;
parser->m_startNamespaceDeclHandler = NULL;
parser->m_endNamespaceDeclHandler = NULL;
parser->m_notStandaloneHandler = NULL;
parser->m_externalEntityRefHandler = NULL;
parser->m_externalEntityRefHandlerArg = parser;
parser->m_skippedEntityHandler = NULL;
parser->m_elementDeclHandler = NULL;
parser->m_attlistDeclHandler = NULL;
parser->m_entityDeclHandler = NULL;
parser->m_xmlDeclHandler = NULL;
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer;
parser->m_parseEndByteIndex = 0;
parser->m_parseEndPtr = NULL;
parser->m_declElementType = NULL;
parser->m_declAttributeId = NULL;
parser->m_declEntity = NULL;
parser->m_doctypeName = NULL;
parser->m_doctypeSysid = NULL;
parser->m_doctypePubid = NULL;
parser->m_declAttributeType = NULL;
parser->m_declNotationName = NULL;
parser->m_declNotationPublicId = NULL;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeIsId = XML_FALSE;
memset(&parser->m_position, 0, sizeof(POSITION));
parser->m_errorCode = XML_ERROR_NONE;
parser->m_eventPtr = NULL;
parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
parser->m_openInternalEntities = NULL;
parser->m_defaultExpandInternalEntities = XML_TRUE;
parser->m_tagLevel = 0;
parser->m_tagStack = NULL;
parser->m_inheritedBindings = NULL;
parser->m_nSpecifiedAtts = 0;
parser->m_unknownEncodingMem = NULL;
parser->m_unknownEncodingRelease = NULL;
parser->m_unknownEncodingData = NULL;
parser->m_parentParser = NULL;
parser->m_parsingStatus.parsing = XML_INITIALIZED;
#ifdef XML_DTD
parser->m_isParamEntity = XML_FALSE;
parser->m_useForeignDTD = XML_FALSE;
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif
parser->m_hash_secret_salt = 0;
}
/* moves list of bindings to m_freeBindingList */
static void FASTCALL
moveToFreeBindingList(XML_Parser parser, BINDING *bindings) {
while (bindings) {
BINDING *b = bindings;
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
}
}
XML_Bool XMLCALL
XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
TAG *tStk;
OPEN_INTERNAL_ENTITY *openEntityList;
if (parser == NULL)
return XML_FALSE;
if (parser->m_parentParser)
return XML_FALSE;
/* move m_tagStack to m_freeTagList */
tStk = parser->m_tagStack;
while (tStk) {
TAG *tag = tStk;
tStk = tStk->parent;
tag->parent = parser->m_freeTagList;
moveToFreeBindingList(parser, tag->bindings);
tag->bindings = NULL;
parser->m_freeTagList = tag;
}
/* move m_openInternalEntities to m_freeInternalEntities */
openEntityList = parser->m_openInternalEntities;
while (openEntityList) {
OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
openEntityList = openEntity->next;
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
moveToFreeBindingList(parser, parser->m_inheritedBindings);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
poolClear(&parser->m_tempPool);
poolClear(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
parser->m_protocolEncodingName = NULL;
parserInit(parser, encodingName);
dtdReset(parser->m_dtd, &parser->m_mem);
return XML_TRUE;
}
enum XML_Status XMLCALL
XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {
if (parser == NULL)
return XML_STATUS_ERROR;
/* Block after XML_Parse()/XML_ParseBuffer() has been called.
XXX There's no way for the caller to determine which of the
XXX possible error cases caused the XML_STATUS_ERROR return.
*/
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_STATUS_ERROR;
/* Get rid of any previous encoding name */
FREE(parser, (void *)parser->m_protocolEncodingName);
if (encodingName == NULL)
/* No new encoding name */
parser->m_protocolEncodingName = NULL;
else {
/* Copy the new encoding name into allocated memory */
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
if (! parser->m_protocolEncodingName)
return XML_STATUS_ERROR;
}
return XML_STATUS_OK;
}
XML_Parser XMLCALL
XML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,
const XML_Char *encodingName) {
XML_Parser parser = oldParser;
DTD *newDtd = NULL;
DTD *oldDtd;
XML_StartElementHandler oldStartElementHandler;
XML_EndElementHandler oldEndElementHandler;
XML_CharacterDataHandler oldCharacterDataHandler;
XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
XML_CommentHandler oldCommentHandler;
XML_StartCdataSectionHandler oldStartCdataSectionHandler;
XML_EndCdataSectionHandler oldEndCdataSectionHandler;
XML_DefaultHandler oldDefaultHandler;
XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
XML_NotationDeclHandler oldNotationDeclHandler;
XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
XML_NotStandaloneHandler oldNotStandaloneHandler;
XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
XML_SkippedEntityHandler oldSkippedEntityHandler;
XML_UnknownEncodingHandler oldUnknownEncodingHandler;
XML_ElementDeclHandler oldElementDeclHandler;
XML_AttlistDeclHandler oldAttlistDeclHandler;
XML_EntityDeclHandler oldEntityDeclHandler;
XML_XmlDeclHandler oldXmlDeclHandler;
ELEMENT_TYPE *oldDeclElementType;
void *oldUserData;
void *oldHandlerArg;
XML_Bool oldDefaultExpandInternalEntities;
XML_Parser oldExternalEntityRefHandlerArg;
#ifdef XML_DTD
enum XML_ParamEntityParsing oldParamEntityParsing;
int oldInEntityValue;
#endif
XML_Bool oldns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
unsigned long oldhash_secret_salt;
/* Validate the oldParser parameter before we pull everything out of it */
if (oldParser == NULL)
return NULL;
/* Stash the original parser contents on the stack */
oldDtd = parser->m_dtd;
oldStartElementHandler = parser->m_startElementHandler;
oldEndElementHandler = parser->m_endElementHandler;
oldCharacterDataHandler = parser->m_characterDataHandler;
oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
oldCommentHandler = parser->m_commentHandler;
oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
oldDefaultHandler = parser->m_defaultHandler;
oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
oldNotationDeclHandler = parser->m_notationDeclHandler;
oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
oldNotStandaloneHandler = parser->m_notStandaloneHandler;
oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
oldSkippedEntityHandler = parser->m_skippedEntityHandler;
oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
oldElementDeclHandler = parser->m_elementDeclHandler;
oldAttlistDeclHandler = parser->m_attlistDeclHandler;
oldEntityDeclHandler = parser->m_entityDeclHandler;
oldXmlDeclHandler = parser->m_xmlDeclHandler;
oldDeclElementType = parser->m_declElementType;
oldUserData = parser->m_userData;
oldHandlerArg = parser->m_handlerArg;
oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
#ifdef XML_DTD
oldParamEntityParsing = parser->m_paramEntityParsing;
oldInEntityValue = parser->m_prologState.inEntityValue;
#endif
oldns_triplets = parser->m_ns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
oldhash_secret_salt = parser->m_hash_secret_salt;
#ifdef XML_DTD
if (! context)
newDtd = oldDtd;
#endif /* XML_DTD */
/* Note that the magical uses of the pre-processor to make field
access look more like C++ require that `parser' be overwritten
here. This makes this function more painful to follow than it
would be otherwise.
*/
if (parser->m_ns) {
XML_Char tmp[2];
*tmp = parser->m_namespaceSeparator;
parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
} else {
parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
}
if (! parser)
return NULL;
parser->m_startElementHandler = oldStartElementHandler;
parser->m_endElementHandler = oldEndElementHandler;
parser->m_characterDataHandler = oldCharacterDataHandler;
parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
parser->m_commentHandler = oldCommentHandler;
parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
parser->m_defaultHandler = oldDefaultHandler;
parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
parser->m_notationDeclHandler = oldNotationDeclHandler;
parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
parser->m_notStandaloneHandler = oldNotStandaloneHandler;
parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
parser->m_skippedEntityHandler = oldSkippedEntityHandler;
parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
parser->m_elementDeclHandler = oldElementDeclHandler;
parser->m_attlistDeclHandler = oldAttlistDeclHandler;
parser->m_entityDeclHandler = oldEntityDeclHandler;
parser->m_xmlDeclHandler = oldXmlDeclHandler;
parser->m_declElementType = oldDeclElementType;
parser->m_userData = oldUserData;
if (oldUserData == oldHandlerArg)
parser->m_handlerArg = parser->m_userData;
else
parser->m_handlerArg = parser;
if (oldExternalEntityRefHandlerArg != oldParser)
parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
parser->m_ns_triplets = oldns_triplets;
parser->m_hash_secret_salt = oldhash_secret_salt;
parser->m_parentParser = oldParser;
#ifdef XML_DTD
parser->m_paramEntityParsing = oldParamEntityParsing;
parser->m_prologState.inEntityValue = oldInEntityValue;
if (context) {
#endif /* XML_DTD */
if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
|| ! setContext(parser, context)) {
XML_ParserFree(parser);
return NULL;
}
parser->m_processor = externalEntityInitProcessor;
#ifdef XML_DTD
} else {
/* The DTD instance referenced by parser->m_dtd is shared between the
document's root parser and external PE parsers, therefore one does not
need to call setContext. In addition, one also *must* not call
setContext, because this would overwrite existing prefix->binding
pointers in parser->m_dtd with ones that get destroyed with the external
PE parser. This would leave those prefixes with dangling pointers.
*/
parser->m_isParamEntity = XML_TRUE;
XmlPrologStateInitExternalEntity(&parser->m_prologState);
parser->m_processor = externalParEntInitProcessor;
}
#endif /* XML_DTD */
return parser;
}
static void FASTCALL
destroyBindings(BINDING *bindings, XML_Parser parser) {
for (;;) {
BINDING *b = bindings;
if (! b)
break;
bindings = b->nextTagBinding;
FREE(parser, b->uri);
FREE(parser, b);
}
}
void XMLCALL
XML_ParserFree(XML_Parser parser) {
TAG *tagList;
OPEN_INTERNAL_ENTITY *entityList;
if (parser == NULL)
return;
/* free m_tagStack and m_freeTagList */
tagList = parser->m_tagStack;
for (;;) {
TAG *p;
if (tagList == NULL) {
if (parser->m_freeTagList == NULL)
break;
tagList = parser->m_freeTagList;
parser->m_freeTagList = NULL;
}
p = tagList;
tagList = tagList->parent;
FREE(parser, p->buf);
destroyBindings(p->bindings, parser);
FREE(parser, p);
}
/* free m_openInternalEntities and m_freeInternalEntities */
entityList = parser->m_openInternalEntities;
for (;;) {
OPEN_INTERNAL_ENTITY *openEntity;
if (entityList == NULL) {
if (parser->m_freeInternalEntities == NULL)
break;
entityList = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = NULL;
}
openEntity = entityList;
entityList = entityList->next;
FREE(parser, openEntity);
}
destroyBindings(parser->m_freeBindingList, parser);
destroyBindings(parser->m_inheritedBindings, parser);
poolDestroy(&parser->m_tempPool);
poolDestroy(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
#ifdef XML_DTD
/* external parameter entity parsers share the DTD structure
parser->m_dtd with the root parser, so we must not destroy it
*/
if (! parser->m_isParamEntity && parser->m_dtd)
#else
if (parser->m_dtd)
#endif /* XML_DTD */
dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser,
&parser->m_mem);
FREE(parser, (void *)parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, (void *)parser->m_attInfo);
#endif
FREE(parser, parser->m_groupConnector);
FREE(parser, parser->m_buffer);
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_nsAtts);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
FREE(parser, parser);
}
void XMLCALL
XML_UseParserAsHandlerArg(XML_Parser parser) {
if (parser != NULL)
parser->m_handlerArg = parser;
}
enum XML_Error XMLCALL
XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
#ifdef XML_DTD
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
parser->m_useForeignDTD = useDTD;
return XML_ERROR_NONE;
#else
return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
#endif
}
void XMLCALL
XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {
if (parser == NULL)
return;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return;
parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
}
void XMLCALL
XML_SetUserData(XML_Parser parser, void *p) {
if (parser == NULL)
return;
if (parser->m_handlerArg == parser->m_userData)
parser->m_handlerArg = parser->m_userData = p;
else
parser->m_userData = p;
}
enum XML_Status XMLCALL
XML_SetBase(XML_Parser parser, const XML_Char *p) {
if (parser == NULL)
return XML_STATUS_ERROR;
if (p) {
p = poolCopyString(&parser->m_dtd->pool, p);
if (! p)
return XML_STATUS_ERROR;
parser->m_curBase = p;
} else
parser->m_curBase = NULL;
return XML_STATUS_OK;
}
const XML_Char *XMLCALL
XML_GetBase(XML_Parser parser) {
if (parser == NULL)
return NULL;
return parser->m_curBase;
}
int XMLCALL
XML_GetSpecifiedAttributeCount(XML_Parser parser) {
if (parser == NULL)
return -1;
return parser->m_nSpecifiedAtts;
}
int XMLCALL
XML_GetIdAttributeIndex(XML_Parser parser) {
if (parser == NULL)
return -1;
return parser->m_idAttIndex;
}
#ifdef XML_ATTR_INFO
const XML_AttrInfo *XMLCALL
XML_GetAttributeInfo(XML_Parser parser) {
if (parser == NULL)
return NULL;
return parser->m_attInfo;
}
#endif
void XMLCALL
XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
XML_EndElementHandler end) {
if (parser == NULL)
return;
parser->m_startElementHandler = start;
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {
if (parser != NULL)
parser->m_startElementHandler = start;
}
void XMLCALL
XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {
if (parser != NULL)
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetCharacterDataHandler(XML_Parser parser,
XML_CharacterDataHandler handler) {
if (parser != NULL)
parser->m_characterDataHandler = handler;
}
void XMLCALL
XML_SetProcessingInstructionHandler(XML_Parser parser,
XML_ProcessingInstructionHandler handler) {
if (parser != NULL)
parser->m_processingInstructionHandler = handler;
}
void XMLCALL
XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {
if (parser != NULL)
parser->m_commentHandler = handler;
}
void XMLCALL
XML_SetCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start,
XML_EndCdataSectionHandler end) {
if (parser == NULL)
return;
parser->m_startCdataSectionHandler = start;
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetStartCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start) {
if (parser != NULL)
parser->m_startCdataSectionHandler = start;
}
void XMLCALL
XML_SetEndCdataSectionHandler(XML_Parser parser,
XML_EndCdataSectionHandler end) {
if (parser != NULL)
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_FALSE;
}
void XMLCALL
XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_TRUE;
}
void XMLCALL
XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
XML_EndDoctypeDeclHandler end) {
if (parser == NULL)
return;
parser->m_startDoctypeDeclHandler = start;
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetStartDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start) {
if (parser != NULL)
parser->m_startDoctypeDeclHandler = start;
}
void XMLCALL
XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {
if (parser != NULL)
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
XML_UnparsedEntityDeclHandler handler) {
if (parser != NULL)
parser->m_unparsedEntityDeclHandler = handler;
}
void XMLCALL
XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {
if (parser != NULL)
parser->m_notationDeclHandler = handler;
}
void XMLCALL
XML_SetNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start,
XML_EndNamespaceDeclHandler end) {
if (parser == NULL)
return;
parser->m_startNamespaceDeclHandler = start;
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetStartNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start) {
if (parser != NULL)
parser->m_startNamespaceDeclHandler = start;
}
void XMLCALL
XML_SetEndNamespaceDeclHandler(XML_Parser parser,
XML_EndNamespaceDeclHandler end) {
if (parser != NULL)
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetNotStandaloneHandler(XML_Parser parser,
XML_NotStandaloneHandler handler) {
if (parser != NULL)
parser->m_notStandaloneHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandler(XML_Parser parser,
XML_ExternalEntityRefHandler handler) {
if (parser != NULL)
parser->m_externalEntityRefHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {
if (parser == NULL)
return;
if (arg)
parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
else
parser->m_externalEntityRefHandlerArg = parser;
}
void XMLCALL
XML_SetSkippedEntityHandler(XML_Parser parser,
XML_SkippedEntityHandler handler) {
if (parser != NULL)
parser->m_skippedEntityHandler = handler;
}
void XMLCALL
XML_SetUnknownEncodingHandler(XML_Parser parser,
XML_UnknownEncodingHandler handler, void *data) {
if (parser == NULL)
return;
parser->m_unknownEncodingHandler = handler;
parser->m_unknownEncodingHandlerData = data;
}
void XMLCALL
XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {
if (parser != NULL)
parser->m_elementDeclHandler = eldecl;
}
void XMLCALL
XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {
if (parser != NULL)
parser->m_attlistDeclHandler = attdecl;
}
void XMLCALL
XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {
if (parser != NULL)
parser->m_entityDeclHandler = handler;
}
void XMLCALL
XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {
if (parser != NULL)
parser->m_xmlDeclHandler = handler;
}
int XMLCALL
XML_SetParamEntityParsing(XML_Parser parser,
enum XML_ParamEntityParsing peParsing) {
if (parser == NULL)
return 0;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
#ifdef XML_DTD
parser->m_paramEntityParsing = peParsing;
return 1;
#else
return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
#endif
}
int XMLCALL
XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {
if (parser == NULL)
return 0;
if (parser->m_parentParser)
return XML_SetHashSalt(parser->m_parentParser, hash_salt);
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
parser->m_hash_secret_salt = hash_salt;
return 1;
}
enum XML_Status XMLCALL
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {
if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
if (parser != NULL)
parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
return XML_STATUS_ERROR;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && ! startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
if (len == 0) {
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
if (! isFinal)
return XML_STATUS_OK;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
/* If data are left over from last buffer, and we now know that these
data are the final chunk of input, then we have to check them again
to detect errors based on that fact.
*/
parser->m_errorCode
= parser->m_processor(parser, parser->m_bufferPtr,
parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode == XML_ERROR_NONE) {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
/* It is hard to be certain, but it seems that this case
* cannot occur. This code is cleaning up a previous parse
* with no new data (since len == 0). Changing the parsing
* state requires getting to execute a handler function, and
* there doesn't seem to be an opportunity for that while in
* this circumstance.
*
* Given the uncertainty, we retain the code but exclude it
* from coverage tests.
*
* LCOV_EXCL_START
*/
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return XML_STATUS_SUSPENDED;
/* LCOV_EXCL_STOP */
case XML_INITIALIZED:
case XML_PARSING:
parser->m_parsingStatus.parsing = XML_FINISHED;
/* fall through */
default:
return XML_STATUS_OK;
}
}
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
#ifndef XML_CONTEXT_BYTES
else if (parser->m_bufferPtr == parser->m_bufferEnd) {
const char *end;
int nLeftOver;
enum XML_Status result;
/* Detect overflow (a+b > MAX <==> b > MAX-a) */
if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_parseEndByteIndex += len;
parser->m_positionPtr = s;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode
= parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
} else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return XML_STATUS_OK;
}
/* fall through */
default:
result = XML_STATUS_OK;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,
&parser->m_position);
nLeftOver = s + len - end;
if (nLeftOver) {
if (parser->m_buffer == NULL
|| nLeftOver > parser->m_bufferLim - parser->m_buffer) {
/* avoid _signed_ integer overflow */
char *temp = NULL;
const int bytesToAllocate = (int)((unsigned)len * 2U);
if (bytesToAllocate > 0) {
temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate);
}
if (temp == NULL) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_buffer = temp;
parser->m_bufferLim = parser->m_buffer + bytesToAllocate;
}
memcpy(parser->m_buffer, end, nLeftOver);
}
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer + nLeftOver;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_eventPtr = parser->m_bufferPtr;
parser->m_eventEndPtr = parser->m_bufferPtr;
return result;
}
#endif /* not defined XML_CONTEXT_BYTES */
else {
void *buff = XML_GetBuffer(parser, len);
if (buff == NULL)
return XML_STATUS_ERROR;
else {
memcpy(buff, s, len);
return XML_ParseBuffer(parser, len, isFinal);
}
}
}
enum XML_Status XMLCALL
XML_ParseBuffer(XML_Parser parser, int len, int isFinal) {
const char *start;
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && ! startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
start = parser->m_bufferPtr;
parser->m_positionPtr = start;
parser->m_bufferEnd += len;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_parseEndByteIndex += len;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode = parser->m_processor(
parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
} else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default:; /* should not happen */
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void *XMLCALL
XML_GetBuffer(XML_Parser parser, int len) {
if (parser == NULL)
return NULL;
if (len < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return NULL;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return NULL;
default:;
}
if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) {
#ifdef XML_CONTEXT_BYTES
int keep;
#endif /* defined XML_CONTEXT_BYTES */
/* Do not invoke signed arithmetic overflow: */
int neededSize = (int)((unsigned)len
+ (unsigned)EXPAT_SAFE_PTR_DIFF(
parser->m_bufferEnd, parser->m_bufferPtr));
if (neededSize < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
#ifdef XML_CONTEXT_BYTES
keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
neededSize += keep;
#endif /* defined XML_CONTEXT_BYTES */
if (neededSize
<= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
#ifdef XML_CONTEXT_BYTES
if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
int offset
= (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)
- keep;
/* The buffer pointers cannot be NULL here; we have at least some bytes
* in the buffer */
memmove(parser->m_buffer, &parser->m_buffer[offset],
parser->m_bufferEnd - parser->m_bufferPtr + keep);
parser->m_bufferEnd -= offset;
parser->m_bufferPtr -= offset;
}
#else
if (parser->m_buffer && parser->m_bufferPtr) {
memmove(parser->m_buffer, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
parser->m_bufferEnd
= parser->m_buffer
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
parser->m_bufferPtr = parser->m_buffer;
}
#endif /* not defined XML_CONTEXT_BYTES */
} else {
char *newBuf;
int bufferSize
= (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
if (bufferSize == 0)
bufferSize = INIT_BUFFER_SIZE;
do {
/* Do not invoke signed arithmetic overflow: */
bufferSize = (int)(2U * (unsigned)bufferSize);
} while (bufferSize < neededSize && bufferSize > 0);
if (bufferSize <= 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
newBuf = (char *)MALLOC(parser, bufferSize);
if (newBuf == 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
parser->m_bufferLim = newBuf + bufferSize;
#ifdef XML_CONTEXT_BYTES
if (parser->m_bufferPtr) {
memcpy(newBuf, &parser->m_bufferPtr[-keep],
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
+ keep);
FREE(parser, parser->m_buffer);
parser->m_buffer = newBuf;
parser->m_bufferEnd
= parser->m_buffer
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
+ keep;
parser->m_bufferPtr = parser->m_buffer + keep;
} else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
parser->m_bufferPtr = parser->m_buffer = newBuf;
}
#else
if (parser->m_bufferPtr) {
memcpy(newBuf, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
FREE(parser, parser->m_buffer);
parser->m_bufferEnd
= newBuf
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
} else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
}
parser->m_bufferPtr = parser->m_buffer = newBuf;
#endif /* not defined XML_CONTEXT_BYTES */
}
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
}
return parser->m_bufferEnd;
}
enum XML_Status XMLCALL
XML_StopParser(XML_Parser parser, XML_Bool resumable) {
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
if (resumable) {
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_FINISHED;
break;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
default:
if (resumable) {
#ifdef XML_DTD
if (parser->m_isParamEntity) {
parser->m_errorCode = XML_ERROR_SUSPEND_PE;
return XML_STATUS_ERROR;
}
#endif
parser->m_parsingStatus.parsing = XML_SUSPENDED;
} else
parser->m_parsingStatus.parsing = XML_FINISHED;
}
return XML_STATUS_OK;
}
enum XML_Status XMLCALL
XML_ResumeParser(XML_Parser parser) {
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_PARSING;
parser->m_errorCode = parser->m_processor(
parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
} else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (parser->m_parsingStatus.finalBuffer) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default:;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void XMLCALL
XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {
if (parser == NULL)
return;
assert(status != NULL);
*status = parser->m_parsingStatus;
}
enum XML_Error XMLCALL
XML_GetErrorCode(XML_Parser parser) {
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
return parser->m_errorCode;
}
XML_Index XMLCALL
XML_GetCurrentByteIndex(XML_Parser parser) {
if (parser == NULL)
return -1;
if (parser->m_eventPtr)
return (XML_Index)(parser->m_parseEndByteIndex
- (parser->m_parseEndPtr - parser->m_eventPtr));
return -1;
}
int XMLCALL
XML_GetCurrentByteCount(XML_Parser parser) {
if (parser == NULL)
return 0;
if (parser->m_eventEndPtr && parser->m_eventPtr)
return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
return 0;
}
const char *XMLCALL
XML_GetInputContext(XML_Parser parser, int *offset, int *size) {
#ifdef XML_CONTEXT_BYTES
if (parser == NULL)
return NULL;
if (parser->m_eventPtr && parser->m_buffer) {
if (offset != NULL)
*offset = (int)(parser->m_eventPtr - parser->m_buffer);
if (size != NULL)
*size = (int)(parser->m_bufferEnd - parser->m_buffer);
return parser->m_buffer;
}
#else
(void)parser;
(void)offset;
(void)size;
#endif /* defined XML_CONTEXT_BYTES */
return (char *)0;
}
XML_Size XMLCALL
XML_GetCurrentLineNumber(XML_Parser parser) {
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.lineNumber + 1;
}
XML_Size XMLCALL
XML_GetCurrentColumnNumber(XML_Parser parser) {
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.columnNumber;
}
void XMLCALL
XML_FreeContentModel(XML_Parser parser, XML_Content *model) {
if (parser != NULL)
FREE(parser, model);
}
void *XMLCALL
XML_MemMalloc(XML_Parser parser, size_t size) {
if (parser == NULL)
return NULL;
return MALLOC(parser, size);
}
void *XMLCALL
XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {
if (parser == NULL)
return NULL;
return REALLOC(parser, ptr, size);
}
void XMLCALL
XML_MemFree(XML_Parser parser, void *ptr) {
if (parser != NULL)
FREE(parser, ptr);
}
void XMLCALL
XML_DefaultCurrent(XML_Parser parser) {
if (parser == NULL)
return;
if (parser->m_defaultHandler) {
if (parser->m_openInternalEntities)
reportDefault(parser, parser->m_internalEncoding,
parser->m_openInternalEntities->internalEventPtr,
parser->m_openInternalEntities->internalEventEndPtr);
else
reportDefault(parser, parser->m_encoding, parser->m_eventPtr,
parser->m_eventEndPtr);
}
}
const XML_LChar *XMLCALL
XML_ErrorString(enum XML_Error code) {
switch (code) {
case XML_ERROR_NONE:
return NULL;
case XML_ERROR_NO_MEMORY:
return XML_L("out of memory");
case XML_ERROR_SYNTAX:
return XML_L("syntax error");
case XML_ERROR_NO_ELEMENTS:
return XML_L("no element found");
case XML_ERROR_INVALID_TOKEN:
return XML_L("not well-formed (invalid token)");
case XML_ERROR_UNCLOSED_TOKEN:
return XML_L("unclosed token");
case XML_ERROR_PARTIAL_CHAR:
return XML_L("partial character");
case XML_ERROR_TAG_MISMATCH:
return XML_L("mismatched tag");
case XML_ERROR_DUPLICATE_ATTRIBUTE:
return XML_L("duplicate attribute");
case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
return XML_L("junk after document element");
case XML_ERROR_PARAM_ENTITY_REF:
return XML_L("illegal parameter entity reference");
case XML_ERROR_UNDEFINED_ENTITY:
return XML_L("undefined entity");
case XML_ERROR_RECURSIVE_ENTITY_REF:
return XML_L("recursive entity reference");
case XML_ERROR_ASYNC_ENTITY:
return XML_L("asynchronous entity");
case XML_ERROR_BAD_CHAR_REF:
return XML_L("reference to invalid character number");
case XML_ERROR_BINARY_ENTITY_REF:
return XML_L("reference to binary entity");
case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
return XML_L("reference to external entity in attribute");
case XML_ERROR_MISPLACED_XML_PI:
return XML_L("XML or text declaration not at start of entity");
case XML_ERROR_UNKNOWN_ENCODING:
return XML_L("unknown encoding");
case XML_ERROR_INCORRECT_ENCODING:
return XML_L("encoding specified in XML declaration is incorrect");
case XML_ERROR_UNCLOSED_CDATA_SECTION:
return XML_L("unclosed CDATA section");
case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
return XML_L("error in processing external entity reference");
case XML_ERROR_NOT_STANDALONE:
return XML_L("document is not standalone");
case XML_ERROR_UNEXPECTED_STATE:
return XML_L("unexpected parser state - please send a bug report");
case XML_ERROR_ENTITY_DECLARED_IN_PE:
return XML_L("entity declared in parameter entity");
case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
return XML_L("requested feature requires XML_DTD support in Expat");
case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
return XML_L("cannot change setting once parsing has begun");
/* Added in 1.95.7. */
case XML_ERROR_UNBOUND_PREFIX:
return XML_L("unbound prefix");
/* Added in 1.95.8. */
case XML_ERROR_UNDECLARING_PREFIX:
return XML_L("must not undeclare prefix");
case XML_ERROR_INCOMPLETE_PE:
return XML_L("incomplete markup in parameter entity");
case XML_ERROR_XML_DECL:
return XML_L("XML declaration not well-formed");
case XML_ERROR_TEXT_DECL:
return XML_L("text declaration not well-formed");
case XML_ERROR_PUBLICID:
return XML_L("illegal character(s) in public id");
case XML_ERROR_SUSPENDED:
return XML_L("parser suspended");
case XML_ERROR_NOT_SUSPENDED:
return XML_L("parser not suspended");
case XML_ERROR_ABORTED:
return XML_L("parsing aborted");
case XML_ERROR_FINISHED:
return XML_L("parsing finished");
case XML_ERROR_SUSPEND_PE:
return XML_L("cannot suspend in external parameter entity");
/* Added in 2.0.0. */
case XML_ERROR_RESERVED_PREFIX_XML:
return XML_L(
"reserved prefix (xml) must not be undeclared or bound to another namespace name");
case XML_ERROR_RESERVED_PREFIX_XMLNS:
return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
case XML_ERROR_RESERVED_NAMESPACE_URI:
return XML_L(
"prefix must not be bound to one of the reserved namespace names");
/* Added in 2.2.5. */
case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
return XML_L("invalid argument");
}
return NULL;
}
const XML_LChar *XMLCALL
XML_ExpatVersion(void) {
/* V1 is used to string-ize the version number. However, it would
string-ize the actual version macro *names* unless we get them
substituted before being passed to V1. CPP is defined to expand
a macro, then rescan for more expansions. Thus, we use V2 to expand
the version macros, then CPP will expand the resulting V1() macro
with the correct numerals. */
/* ### I'm assuming cpp is portable in this respect... */
#define V1(a, b, c) XML_L(#a) XML_L(".") XML_L(#b) XML_L(".") XML_L(#c)
#define V2(a, b, c) XML_L("expat_") V1(a, b, c)
return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
#undef V1
#undef V2
}
XML_Expat_Version XMLCALL
XML_ExpatVersionInfo(void) {
XML_Expat_Version version;
version.major = XML_MAJOR_VERSION;
version.minor = XML_MINOR_VERSION;
version.micro = XML_MICRO_VERSION;
return version;
}
const XML_Feature *XMLCALL
XML_GetFeatureList(void) {
static const XML_Feature features[]
= {{XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
sizeof(XML_Char)},
{XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
sizeof(XML_LChar)},
#ifdef XML_UNICODE
{XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
#endif
#ifdef XML_UNICODE_WCHAR_T
{XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
#endif
#ifdef XML_DTD
{XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
#endif
#ifdef XML_CONTEXT_BYTES
{XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
XML_CONTEXT_BYTES},
#endif
#ifdef XML_MIN_SIZE
{XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
#endif
#ifdef XML_NS
{XML_FEATURE_NS, XML_L("XML_NS"), 0},
#endif
#ifdef XML_LARGE_SIZE
{XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
#endif
#ifdef XML_ATTR_INFO
{XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
#endif
{XML_FEATURE_END, NULL, 0}};
return features;
}
/* Initially tag->rawName always points into the parse buffer;
for those TAG instances opened while the current parse buffer was
processed, and not yet closed, we need to store tag->rawName in a more
permanent location, since the parse buffer is about to be discarded.
*/
static XML_Bool
storeRawNames(XML_Parser parser) {
TAG *tag = parser->m_tagStack;
while (tag) {
int bufSize;
int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
char *rawNameBuf = tag->buf + nameLen;
/* Stop if already stored. Since m_tagStack is a stack, we can stop
at the first entry that has already been copied; everything
below it in the stack is already been accounted for in a
previous call to this function.
*/
if (tag->rawName == rawNameBuf)
break;
/* For re-use purposes we need to ensure that the
size of tag->buf is a multiple of sizeof(XML_Char).
*/
bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
if (bufSize > tag->bufEnd - tag->buf) {
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_FALSE;
/* if tag->name.str points to tag->buf (only when namespace
processing is off) then we have to update it
*/
if (tag->name.str == (XML_Char *)tag->buf)
tag->name.str = (XML_Char *)temp;
/* if tag->name.localPart is set (when namespace processing is on)
then update it as well, since it will always point into tag->buf
*/
if (tag->name.localPart)
tag->name.localPart
= (XML_Char *)temp + (tag->name.localPart - (XML_Char *)tag->buf);
tag->buf = temp;
tag->bufEnd = temp + bufSize;
rawNameBuf = temp + nameLen;
}
memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
tag->rawName = rawNameBuf;
tag = tag->parent;
}
return XML_TRUE;
}
static enum XML_Error PTRCALL
contentProcessor(XML_Parser parser, const char *start, const char *end,
const char **endPtr) {
enum XML_Error result
= doContent(parser, 0, parser->m_encoding, start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (! storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error PTRCALL
externalEntityInitProcessor(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = externalEntityInitProcessor2;
return externalEntityInitProcessor2(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor2(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
const char *next = start; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(parser->m_encoding, start, end, &next);
switch (tok) {
case XML_TOK_BOM:
/* If we are at the end of the buffer, this would cause the next stage,
i.e. externalEntityInitProcessor3, to pass control directly to
doContent (by detecting XML_TOK_NONE) without processing any xml text
declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
*/
if (next == end && ! parser->m_parsingStatus.finalBuffer) {
*endPtr = next;
return XML_ERROR_NONE;
}
start = next;
break;
case XML_TOK_PARTIAL:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityInitProcessor3;
return externalEntityInitProcessor3(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor3(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
int tok;
const char *next = start; /* XmlContentTok doesn't always set the last arg */
parser->m_eventPtr = start;
tok = XmlContentTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
case XML_TOK_XML_DECL: {
enum XML_Error result;
result = processXmlDecl(parser, 1, start, next);
if (result != XML_ERROR_NONE)
return result;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*endPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
start = next;
}
} break;
case XML_TOK_PARTIAL:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityContentProcessor;
parser->m_tagLevel = 1;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityContentProcessor(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
enum XML_Error result
= doContent(parser, 1, parser->m_encoding, start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (! storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error
doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
const char *s, const char *end, const char **nextPtr,
XML_Bool haveMore) {
/* save one level of indirection */
DTD *const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
} else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
for (;;) {
const char *next = s; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_TRAILING_CR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
*eventEndPP = end;
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0)
return XML_ERROR_NO_ELEMENTS;
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (startTagLevel > 0) {
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_NO_ELEMENTS;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_ENTITY_REF: {
const XML_Char *name;
ENTITY *entity;
XML_Char ch = (XML_Char)XmlPredefinedEntityName(
enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
if (ch) {
if (parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&dtd->pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity or default handler.
*/
if (! dtd->hasParamEntityRefs || dtd->standalone) {
if (! entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (! entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
} else if (! entity) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->notation)
return XML_ERROR_BINARY_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
if (! parser->m_defaultExpandInternalEntities) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,
0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
result = processInternalEntity(parser, entity, XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
} else if (parser->m_externalEntityRefHandler) {
const XML_Char *context;
entity->open = XML_TRUE;
context = getContext(parser);
entity->open = XML_FALSE;
if (! context)
return XML_ERROR_NO_MEMORY;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, context, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
poolDiscard(&parser->m_tempPool);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
case XML_TOK_START_TAG_NO_ATTS:
/* fall through */
case XML_TOK_START_TAG_WITH_ATTS: {
TAG *tag;
enum XML_Error result;
XML_Char *toPtr;
if (parser->m_freeTagList) {
tag = parser->m_freeTagList;
parser->m_freeTagList = parser->m_freeTagList->parent;
} else {
tag = (TAG *)MALLOC(parser, sizeof(TAG));
if (! tag)
return XML_ERROR_NO_MEMORY;
tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
if (! tag->buf) {
FREE(parser, tag);
return XML_ERROR_NO_MEMORY;
}
tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
}
tag->bindings = NULL;
tag->parent = parser->m_tagStack;
parser->m_tagStack = tag;
tag->name.localPart = NULL;
tag->name.prefix = NULL;
tag->rawName = s + enc->minBytesPerChar;
tag->rawNameLength = XmlNameLength(enc, tag->rawName);
++parser->m_tagLevel;
{
const char *rawNameEnd = tag->rawName + tag->rawNameLength;
const char *fromPtr = tag->rawName;
toPtr = (XML_Char *)tag->buf;
for (;;) {
int bufSize;
int convLen;
const enum XML_Convert_Result convert_res
= XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,
(ICHAR *)tag->bufEnd - 1);
convLen = (int)(toPtr - (XML_Char *)tag->buf);
if ((fromPtr >= rawNameEnd)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
tag->name.strLen = convLen;
break;
}
bufSize = (int)(tag->bufEnd - tag->buf) << 1;
{
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
tag->buf = temp;
tag->bufEnd = temp + bufSize;
toPtr = (XML_Char *)temp + convLen;
}
}
}
tag->name.str = (XML_Char *)tag->buf;
*toPtr = XML_T('\0');
result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
if (result)
return result;
if (parser->m_startElementHandler)
parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
(const XML_Char **)parser->m_atts);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
break;
}
case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
/* fall through */
case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {
const char *rawName = s + enc->minBytesPerChar;
enum XML_Error result;
BINDING *bindings = NULL;
XML_Bool noElmHandlers = XML_TRUE;
TAG_NAME name;
name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
rawName + XmlNameLength(enc, rawName));
if (! name.str)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
result = storeAtts(parser, enc, s, &name, &bindings);
if (result != XML_ERROR_NONE) {
freeBindings(parser, bindings);
return result;
}
poolFinish(&parser->m_tempPool);
if (parser->m_startElementHandler) {
parser->m_startElementHandler(parser->m_handlerArg, name.str,
(const XML_Char **)parser->m_atts);
noElmHandlers = XML_FALSE;
}
if (parser->m_endElementHandler) {
if (parser->m_startElementHandler)
*eventPP = *eventEndPP;
parser->m_endElementHandler(parser->m_handlerArg, name.str);
noElmHandlers = XML_FALSE;
}
if (noElmHandlers && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
freeBindings(parser, bindings);
}
if ((parser->m_tagLevel == 0)
&& (parser->m_parsingStatus.parsing != XML_FINISHED)) {
if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
parser->m_processor = epilogProcessor;
else
return epilogProcessor(parser, next, end, nextPtr);
}
break;
case XML_TOK_END_TAG:
if (parser->m_tagLevel == startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
else {
int len;
const char *rawName;
TAG *tag = parser->m_tagStack;
parser->m_tagStack = tag->parent;
tag->parent = parser->m_freeTagList;
parser->m_freeTagList = tag;
rawName = s + enc->minBytesPerChar * 2;
len = XmlNameLength(enc, rawName);
if (len != tag->rawNameLength
|| memcmp(tag->rawName, rawName, len) != 0) {
*eventPP = rawName;
return XML_ERROR_TAG_MISMATCH;
}
--parser->m_tagLevel;
if (parser->m_endElementHandler) {
const XML_Char *localPart;
const XML_Char *prefix;
XML_Char *uri;
localPart = tag->name.localPart;
if (parser->m_ns && localPart) {
/* localPart and prefix may have been overwritten in
tag->name.str, since this points to the binding->uri
buffer which gets re-used; so we have to add them again
*/
uri = (XML_Char *)tag->name.str + tag->name.uriLen;
/* don't need to check for space - already done in storeAtts() */
while (*localPart)
*uri++ = *localPart++;
prefix = (XML_Char *)tag->name.prefix;
if (parser->m_ns_triplets && prefix) {
*uri++ = parser->m_namespaceSeparator;
while (*prefix)
*uri++ = *prefix++;
}
*uri = XML_T('\0');
}
parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
while (tag->bindings) {
BINDING *b = tag->bindings;
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg,
b->prefix->name);
tag->bindings = tag->bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
if ((parser->m_tagLevel == 0)
&& (parser->m_parsingStatus.parsing != XML_FINISHED)) {
if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
parser->m_processor = epilogProcessor;
else
return epilogProcessor(parser, next, end, nextPtr);
}
}
break;
case XML_TOK_CHAR_REF: {
int n = XmlCharRefNumber(enc, s);
if (n < 0)
return XML_ERROR_BAD_CHAR_REF;
if (parser->m_characterDataHandler) {
XML_Char buf[XML_ENCODE_MAX];
parser->m_characterDataHandler(parser->m_handlerArg, buf,
XmlEncode(n, (ICHAR *)buf));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
} break;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_CDATA_SECT_OPEN: {
enum XML_Error result;
if (parser->m_startCdataSectionHandler)
parser->m_startCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* Suppose you doing a transformation on a document that involves
changing only the character data. You set up a defaultHandler
and a characterDataHandler. The defaultHandler simply copies
characters through. The characterDataHandler does the
transformation and writes the characters out escaping them as
necessary. This case will fail to work if we leave out the
following two lines (because & and < inside CDATA sections will
be incorrectly escaped).
However, now we have a start/endCdataSectionHandler, so it seems
easier to let the user deal with this.
*/
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (! next) {
parser->m_processor = cdataSectionProcessor;
return result;
}
} break;
case XML_TOK_TRAILING_RSQB:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (parser->m_characterDataHandler) {
if (MUST_CONVERT(enc, s)) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
parser->m_characterDataHandler(
parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
} else
parser->m_characterDataHandler(
parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)end - (XML_Char *)s));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0) {
*eventPP = end;
return XML_ERROR_NO_ELEMENTS;
}
if (parser->m_tagLevel != startTagLevel) {
*eventPP = end;
return XML_ERROR_ASYNC_ENTITY;
}
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_DATA_CHARS: {
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(
enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
} else
charDataHandler(parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
} break;
case XML_TOK_PI:
if (! reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (! reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
default:
/* All of the tokens produced by XmlContentTok() have their own
* explicit cases, so this default is not strictly necessary.
* However it is a useful safety net, so we retain the code and
* simply exclude it from the coverage tests.
*
* LCOV_EXCL_START
*/
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:;
}
}
/* not reached */
}
/* This function does not call free() on the allocated memory, merely
* moving it to the parser's m_freeBindingList where it can be freed or
* reused as appropriate.
*/
static void
freeBindings(XML_Parser parser, BINDING *bindings) {
while (bindings) {
BINDING *b = bindings;
/* m_startNamespaceDeclHandler will have been called for this
* binding in addBindings(), so call the end handler now.
*/
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
}
/* Precondition: all arguments must be non-NULL;
Purpose:
- normalize attributes
- check attributes for well-formedness
- generate namespace aware attribute names (URI, prefix)
- build list of attributes for startElementHandler
- default attributes
- process namespace declarations (check and report them)
- generate namespace aware element name (URI, prefix)
*/
static enum XML_Error
storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
TAG_NAME *tagNamePtr, BINDING **bindingsPtr) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
ELEMENT_TYPE *elementType;
int nDefaultAtts;
const XML_Char **appAtts; /* the attribute list for the application */
int attIndex = 0;
int prefixLen;
int i;
int n;
XML_Char *uri;
int nPrefixes = 0;
BINDING *binding;
const XML_Char *localPart;
/* lookup the element type name */
elementType
= (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);
if (! elementType) {
const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
if (! name)
return XML_ERROR_NO_MEMORY;
elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
sizeof(ELEMENT_TYPE));
if (! elementType)
return XML_ERROR_NO_MEMORY;
if (parser->m_ns && ! setElementTypePrefix(parser, elementType))
return XML_ERROR_NO_MEMORY;
}
nDefaultAtts = elementType->nDefaultAtts;
/* get the attributes from the tokenizer */
n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
if (n + nDefaultAtts > parser->m_attsSize) {
int oldAttsSize = parser->m_attsSize;
ATTRIBUTE *temp;
#ifdef XML_ATTR_INFO
XML_AttrInfo *temp2;
#endif
parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts,
parser->m_attsSize * sizeof(ATTRIBUTE));
if (temp == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_atts = temp;
#ifdef XML_ATTR_INFO
temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo,
parser->m_attsSize * sizeof(XML_AttrInfo));
if (temp2 == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_attInfo = temp2;
#endif
if (n > oldAttsSize)
XmlGetAttributes(enc, attStr, n, parser->m_atts);
}
appAtts = (const XML_Char **)parser->m_atts;
for (i = 0; i < n; i++) {
ATTRIBUTE *currAtt = &parser->m_atts[i];
#ifdef XML_ATTR_INFO
XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
#endif
/* add the name and value to the attribute list */
ATTRIBUTE_ID *attId
= getAttributeId(parser, enc, currAtt->name,
currAtt->name + XmlNameLength(enc, currAtt->name));
if (! attId)
return XML_ERROR_NO_MEMORY;
#ifdef XML_ATTR_INFO
currAttInfo->nameStart
= parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
currAttInfo->nameEnd
= currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);
currAttInfo->valueStart = parser->m_parseEndByteIndex
- (parser->m_parseEndPtr - currAtt->valuePtr);
currAttInfo->valueEnd = parser->m_parseEndByteIndex
- (parser->m_parseEndPtr - currAtt->valueEnd);
#endif
/* Detect duplicate attributes by their QNames. This does not work when
namespace processing is turned on and different prefixes for the same
namespace are used. For this case we have a check further down.
*/
if ((attId->name)[-1]) {
if (enc == parser->m_encoding)
parser->m_eventPtr = parser->m_atts[i].name;
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
(attId->name)[-1] = 1;
appAtts[attIndex++] = attId->name;
if (! parser->m_atts[i].normalized) {
enum XML_Error result;
XML_Bool isCdata = XML_TRUE;
/* figure out whether declared as other than CDATA */
if (attId->maybeTokenized) {
int j;
for (j = 0; j < nDefaultAtts; j++) {
if (attId == elementType->defaultAtts[j].id) {
isCdata = elementType->defaultAtts[j].isCdata;
break;
}
}
}
/* normalize the attribute value */
result = storeAttributeValue(
parser, enc, isCdata, parser->m_atts[i].valuePtr,
parser->m_atts[i].valueEnd, &parser->m_tempPool);
if (result)
return result;
appAtts[attIndex] = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
} else {
/* the value did not need normalizing */
appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,
parser->m_atts[i].valuePtr,
parser->m_atts[i].valueEnd);
if (appAtts[attIndex] == 0)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
}
/* handle prefixed attribute names */
if (attId->prefix) {
if (attId->xmlns) {
/* deal with namespace declarations here */
enum XML_Error result = addBinding(parser, attId->prefix, attId,
appAtts[attIndex], bindingsPtr);
if (result)
return result;
--attIndex;
} else {
/* deal with other prefixed names later */
attIndex++;
nPrefixes++;
(attId->name)[-1] = 2;
}
} else
attIndex++;
}
/* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
parser->m_nSpecifiedAtts = attIndex;
if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
for (i = 0; i < attIndex; i += 2)
if (appAtts[i] == elementType->idAtt->name) {
parser->m_idAttIndex = i;
break;
}
} else
parser->m_idAttIndex = -1;
/* do attribute defaulting */
for (i = 0; i < nDefaultAtts; i++) {
const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
if (! (da->id->name)[-1] && da->value) {
if (da->id->prefix) {
if (da->id->xmlns) {
enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
da->value, bindingsPtr);
if (result)
return result;
} else {
(da->id->name)[-1] = 2;
nPrefixes++;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
} else {
(da->id->name)[-1] = 1;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
}
}
appAtts[attIndex] = 0;
/* expand prefixed attribute names, check for duplicates,
and clear flags that say whether attributes were specified */
i = 0;
if (nPrefixes) {
int j; /* hash table index */
unsigned long version = parser->m_nsAttsVersion;
int nsAttsSize = (int)1 << parser->m_nsAttsPower;
unsigned char oldNsAttsPower = parser->m_nsAttsPower;
/* size of hash table must be at least 2 * (# of prefixed attributes) */
if ((nPrefixes << 1)
>> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
NS_ATT *temp;
/* hash table size must also be a power of 2 and >= 8 */
while (nPrefixes >> parser->m_nsAttsPower++)
;
if (parser->m_nsAttsPower < 3)
parser->m_nsAttsPower = 3;
nsAttsSize = (int)1 << parser->m_nsAttsPower;
temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts,
nsAttsSize * sizeof(NS_ATT));
if (! temp) {
/* Restore actual size of memory in m_nsAtts */
parser->m_nsAttsPower = oldNsAttsPower;
return XML_ERROR_NO_MEMORY;
}
parser->m_nsAtts = temp;
version = 0; /* force re-initialization of m_nsAtts hash table */
}
/* using a version flag saves us from initializing m_nsAtts every time */
if (! version) { /* initialize version flags when version wraps around */
version = INIT_ATTS_VERSION;
for (j = nsAttsSize; j != 0;)
parser->m_nsAtts[--j].version = version;
}
parser->m_nsAttsVersion = --version;
/* expand prefixed names and check for duplicates */
for (; i < attIndex; i += 2) {
const XML_Char *s = appAtts[i];
if (s[-1] == 2) { /* prefixed */
ATTRIBUTE_ID *id;
const BINDING *b;
unsigned long uriHash;
struct siphash sip_state;
struct sipkey sip_key;
copy_salt_to_sipkey(parser, &sip_key);
sip24_init(&sip_state, &sip_key);
((XML_Char *)s)[-1] = 0; /* clear flag */
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
if (! id || ! id->prefix) {
/* This code is walking through the appAtts array, dealing
* with (in this case) a prefixed attribute name. To be in
* the array, the attribute must have already been bound, so
* has to have passed through the hash table lookup once
* already. That implies that an entry for it already
* exists, so the lookup above will return a pointer to
* already allocated memory. There is no opportunaity for
* the allocator to fail, so the condition above cannot be
* fulfilled.
*
* Since it is difficult to be certain that the above
* analysis is complete, we retain the test and merely
* remove the code from coverage tests.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
b = id->prefix->binding;
if (! b)
return XML_ERROR_UNBOUND_PREFIX;
for (j = 0; j < b->uriLen; j++) {
const XML_Char c = b->uri[j];
if (! poolAppendChar(&parser->m_tempPool, c))
return XML_ERROR_NO_MEMORY;
}
sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
while (*s++ != XML_T(ASCII_COLON))
;
sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
do { /* copies null terminator */
if (! poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
uriHash = (unsigned long)sip24_final(&sip_state);
{ /* Check hash table for duplicate of expanded name (uriName).
Derived from code in lookup(parser, HASH_TABLE *table, ...).
*/
unsigned char step = 0;
unsigned long mask = nsAttsSize - 1;
j = uriHash & mask; /* index into hash table */
while (parser->m_nsAtts[j].version == version) {
/* for speed we compare stored hash values first */
if (uriHash == parser->m_nsAtts[j].hash) {
const XML_Char *s1 = poolStart(&parser->m_tempPool);
const XML_Char *s2 = parser->m_nsAtts[j].uriName;
/* s1 is null terminated, but not s2 */
for (; *s1 == *s2 && *s1 != 0; s1++, s2++)
;
if (*s1 == 0)
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
if (! step)
step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
j < step ? (j += nsAttsSize - step) : (j -= step);
}
}
if (parser->m_ns_triplets) { /* append namespace separator and prefix */
parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
s = b->prefix->name;
do {
if (! poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
}
/* store expanded name in attribute list */
s = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
appAtts[i] = s;
/* fill empty slot with new version, uriName and hash value */
parser->m_nsAtts[j].version = version;
parser->m_nsAtts[j].hash = uriHash;
parser->m_nsAtts[j].uriName = s;
if (! --nPrefixes) {
i += 2;
break;
}
} else /* not prefixed */
((XML_Char *)s)[-1] = 0; /* clear flag */
}
}
/* clear flags for the remaining attributes */
for (; i < attIndex; i += 2)
((XML_Char *)(appAtts[i]))[-1] = 0;
for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
binding->attId->name[-1] = 0;
if (! parser->m_ns)
return XML_ERROR_NONE;
/* expand the element type name */
if (elementType->prefix) {
binding = elementType->prefix->binding;
if (! binding)
return XML_ERROR_UNBOUND_PREFIX;
localPart = tagNamePtr->str;
while (*localPart++ != XML_T(ASCII_COLON))
;
} else if (dtd->defaultPrefix.binding) {
binding = dtd->defaultPrefix.binding;
localPart = tagNamePtr->str;
} else
return XML_ERROR_NONE;
prefixLen = 0;
if (parser->m_ns_triplets && binding->prefix->name) {
for (; binding->prefix->name[prefixLen++];)
; /* prefixLen includes null terminator */
}
tagNamePtr->localPart = localPart;
tagNamePtr->uriLen = binding->uriLen;
tagNamePtr->prefix = binding->prefix->name;
tagNamePtr->prefixLen = prefixLen;
for (i = 0; localPart[i++];)
; /* i includes null terminator */
n = i + binding->uriLen + prefixLen;
if (n > binding->uriAlloc) {
TAG *p;
uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
if (! uri)
return XML_ERROR_NO_MEMORY;
binding->uriAlloc = n + EXPAND_SPARE;
memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
for (p = parser->m_tagStack; p; p = p->parent)
if (p->name.str == binding->uri)
p->name.str = uri;
FREE(parser, binding->uri);
binding->uri = uri;
}
/* if m_namespaceSeparator != '\0' then uri includes it already */
uri = binding->uri + binding->uriLen;
memcpy(uri, localPart, i * sizeof(XML_Char));
/* we always have a namespace separator between localPart and prefix */
if (prefixLen) {
uri += i - 1;
*uri = parser->m_namespaceSeparator; /* replace null terminator */
memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
}
tagNamePtr->str = binding->uri;
return XML_ERROR_NONE;
}
/* addBinding() overwrites the value of prefix->binding without checking.
Therefore one must keep track of the old value outside of addBinding().
*/
static enum XML_Error
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
const XML_Char *uri, BINDING **bindingsPtr) {
static const XML_Char xmlNamespace[]
= {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON,
ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o,
ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M,
ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9,
ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m,
ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
ASCII_e, '\0'};
static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;
static const XML_Char xmlnsNamespace[]
= {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,
ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH,
ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x,
ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'};
static const int xmlnsLen
= (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;
XML_Bool mustBeXML = XML_FALSE;
XML_Bool isXML = XML_TRUE;
XML_Bool isXMLNS = XML_TRUE;
BINDING *b;
int len;
/* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
if (*uri == XML_T('\0') && prefix->name)
return XML_ERROR_UNDECLARING_PREFIX;
if (prefix->name && prefix->name[0] == XML_T(ASCII_x)
&& prefix->name[1] == XML_T(ASCII_m)
&& prefix->name[2] == XML_T(ASCII_l)) {
/* Not allowed to bind xmlns */
if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)
&& prefix->name[5] == XML_T('\0'))
return XML_ERROR_RESERVED_PREFIX_XMLNS;
if (prefix->name[3] == XML_T('\0'))
mustBeXML = XML_TRUE;
}
for (len = 0; uri[len]; len++) {
if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
isXML = XML_FALSE;
if (! mustBeXML && isXMLNS
&& (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
isXMLNS = XML_FALSE;
}
isXML = isXML && len == xmlLen;
isXMLNS = isXMLNS && len == xmlnsLen;
if (mustBeXML != isXML)
return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
: XML_ERROR_RESERVED_NAMESPACE_URI;
if (isXMLNS)
return XML_ERROR_RESERVED_NAMESPACE_URI;
if (parser->m_namespaceSeparator)
len++;
if (parser->m_freeBindingList) {
b = parser->m_freeBindingList;
if (len > b->uriAlloc) {
XML_Char *temp = (XML_Char *)REALLOC(
parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
b->uri = temp;
b->uriAlloc = len + EXPAND_SPARE;
}
parser->m_freeBindingList = b->nextTagBinding;
} else {
b = (BINDING *)MALLOC(parser, sizeof(BINDING));
if (! b)
return XML_ERROR_NO_MEMORY;
b->uri
= (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
if (! b->uri) {
FREE(parser, b);
return XML_ERROR_NO_MEMORY;
}
b->uriAlloc = len + EXPAND_SPARE;
}
b->uriLen = len;
memcpy(b->uri, uri, len * sizeof(XML_Char));
if (parser->m_namespaceSeparator)
b->uri[len - 1] = parser->m_namespaceSeparator;
b->prefix = prefix;
b->attId = attId;
b->prevPrefixBinding = prefix->binding;
/* NULL binding when default namespace undeclared */
if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
prefix->binding = NULL;
else
prefix->binding = b;
b->nextTagBinding = *bindingsPtr;
*bindingsPtr = b;
/* if attId == NULL then we are not starting a namespace scope */
if (attId && parser->m_startNamespaceDeclHandler)
parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
prefix->binding ? uri : 0);
return XML_ERROR_NONE;
}
/* The idea here is to avoid using stack for each CDATA section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
cdataSectionProcessor(XML_Parser parser, const char *start, const char *end,
const char **endPtr) {
enum XML_Error result
= doCdataSection(parser, parser->m_encoding, &start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
if (parser->m_parentParser) { /* we are parsing an external entity */
parser->m_processor = externalEntityContentProcessor;
return externalEntityContentProcessor(parser, start, end, endPtr);
} else {
parser->m_processor = contentProcessor;
return contentProcessor(parser, start, end, endPtr);
}
}
return result;
}
/* startPtr gets set to non-null if the section is closed, and to null if
the section is not yet closed.
*/
static enum XML_Error
doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore) {
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
} else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
*startPtr = NULL;
for (;;) {
const char *next;
int tok = XmlCdataSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_CDATA_SECT_CLOSE:
if (parser->m_endCdataSectionHandler)
parser->m_endCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* see comment under XML_TOK_CDATA_SECT_OPEN */
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_DATA_CHARS: {
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(
enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = next;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
} else
charDataHandler(parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
} break;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_CDATA_SECTION;
default:
/* Every token returned by XmlCdataSectionTok() has its own
* explicit case, so this default case will never be executed.
* We retain it as a safety net and exclude it from the coverage
* statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:;
}
}
/* not reached */
}
#ifdef XML_DTD
/* The idea here is to avoid using stack for each IGNORE section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
ignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,
const char **endPtr) {
enum XML_Error result
= doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
parser->m_processor = prologProcessor;
return prologProcessor(parser, start, end, endPtr);
}
return result;
}
/* startPtr gets set to non-null is the section is closed, and to null
if the section is not yet closed.
*/
static enum XML_Error
doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore) {
const char *next;
int tok;
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
} else {
/* It's not entirely clear, but it seems the following two lines
* of code cannot be executed. The only occasions on which 'enc'
* is not 'encoding' are when this function is called
* from the internal entity processing, and IGNORE sections are an
* error in internal entities.
*
* Since it really isn't clear that this is true, we keep the code
* and just remove it from our coverage tests.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
*eventPP = s;
*startPtr = NULL;
tok = XmlIgnoreSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_IGNORE_SECT:
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
default:
/* All of the tokens that XmlIgnoreSectionTok() returns have
* explicit cases to handle them, so this default case is never
* executed. We keep it as a safety net anyway, and remove it
* from our test coverage statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
/* not reached */
}
#endif /* XML_DTD */
static enum XML_Error
initializeEncoding(XML_Parser parser) {
const char *s;
#ifdef XML_UNICODE
char encodingBuf[128];
/* See comments abount `protoclEncodingName` in parserInit() */
if (! parser->m_protocolEncodingName)
s = NULL;
else {
int i;
for (i = 0; parser->m_protocolEncodingName[i]; i++) {
if (i == sizeof(encodingBuf) - 1
|| (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
encodingBuf[0] = '\0';
break;
}
encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
}
encodingBuf[i] = '\0';
s = encodingBuf;
}
#else
s = parser->m_protocolEncodingName;
#endif
if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(
&parser->m_initEncoding, &parser->m_encoding, s))
return XML_ERROR_NONE;
return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
}
static enum XML_Error
processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
const char *next) {
const char *encodingName = NULL;
const XML_Char *storedEncName = NULL;
const ENCODING *newEncoding = NULL;
const char *version = NULL;
const char *versionend;
const XML_Char *storedversion = NULL;
int standalone = -1;
if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(
isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,
&version, &versionend, &encodingName, &newEncoding, &standalone)) {
if (isGeneralTextEntity)
return XML_ERROR_TEXT_DECL;
else
return XML_ERROR_XML_DECL;
}
if (! isGeneralTextEntity && standalone == 1) {
parser->m_dtd->standalone = XML_TRUE;
#ifdef XML_DTD
if (parser->m_paramEntityParsing
== XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif /* XML_DTD */
}
if (parser->m_xmlDeclHandler) {
if (encodingName != NULL) {
storedEncName = poolStoreString(
&parser->m_temp2Pool, parser->m_encoding, encodingName,
encodingName + XmlNameLength(parser->m_encoding, encodingName));
if (! storedEncName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_temp2Pool);
}
if (version) {
storedversion
= poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,
versionend - parser->m_encoding->minBytesPerChar);
if (! storedversion)
return XML_ERROR_NO_MEMORY;
}
parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,
standalone);
} else if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_protocolEncodingName == NULL) {
if (newEncoding) {
/* Check that the specified encoding does not conflict with what
* the parser has already deduced. Do we have the same number
* of bytes in the smallest representation of a character? If
* this is UTF-16, is it the same endianness?
*/
if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
|| (newEncoding->minBytesPerChar == 2
&& newEncoding != parser->m_encoding)) {
parser->m_eventPtr = encodingName;
return XML_ERROR_INCORRECT_ENCODING;
}
parser->m_encoding = newEncoding;
} else if (encodingName) {
enum XML_Error result;
if (! storedEncName) {
storedEncName = poolStoreString(
&parser->m_temp2Pool, parser->m_encoding, encodingName,
encodingName + XmlNameLength(parser->m_encoding, encodingName));
if (! storedEncName)
return XML_ERROR_NO_MEMORY;
}
result = handleUnknownEncoding(parser, storedEncName);
poolClear(&parser->m_temp2Pool);
if (result == XML_ERROR_UNKNOWN_ENCODING)
parser->m_eventPtr = encodingName;
return result;
}
}
if (storedEncName || storedversion)
poolClear(&parser->m_temp2Pool);
return XML_ERROR_NONE;
}
static enum XML_Error
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {
if (parser->m_unknownEncodingHandler) {
XML_Encoding info;
int i;
for (i = 0; i < 256; i++)
info.map[i] = -1;
info.convert = NULL;
info.data = NULL;
info.release = NULL;
if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,
encodingName, &info)) {
ENCODING *enc;
parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
if (! parser->m_unknownEncodingMem) {
if (info.release)
info.release(info.data);
return XML_ERROR_NO_MEMORY;
}
enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(
parser->m_unknownEncodingMem, info.map, info.convert, info.data);
if (enc) {
parser->m_unknownEncodingData = info.data;
parser->m_unknownEncodingRelease = info.release;
parser->m_encoding = enc;
return XML_ERROR_NONE;
}
}
if (info.release != NULL)
info.release(info.data);
}
return XML_ERROR_UNKNOWN_ENCODING;
}
static enum XML_Error PTRCALL
prologInitProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = prologProcessor;
return prologProcessor(parser, s, end, nextPtr);
}
#ifdef XML_DTD
static enum XML_Error PTRCALL
externalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
/* we know now that XML_Parse(Buffer) has been called,
so we consider the external parameter entity read */
parser->m_dtd->paramEntityRead = XML_TRUE;
if (parser->m_prologState.inEntityValue) {
parser->m_processor = entityValueInitProcessor;
return entityValueInitProcessor(parser, s, end, nextPtr);
} else {
parser->m_processor = externalParEntProcessor;
return externalParEntProcessor(parser, s, end, nextPtr);
}
}
static enum XML_Error PTRCALL
entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
int tok;
const char *start = s;
const char *next = start;
parser->m_eventPtr = start;
for (;;) {
tok = XmlPrologTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, parser->m_encoding, s, end);
} else if (tok == XML_TOK_XML_DECL) {
enum XML_Error result;
result = processXmlDecl(parser, 0, start, next);
if (result != XML_ERROR_NONE)
return result;
/* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For
* that to happen, a parameter entity parsing handler must have attempted
* to suspend the parser, which fails and raises an error. The parser can
* be aborted, but can't be suspended.
*/
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
*nextPtr = next;
/* stop scanning for text declaration - we found one */
parser->m_processor = entityValueProcessor;
return entityValueProcessor(parser, next, end, nextPtr);
}
/* If we are at the end of the buffer, this would cause XmlPrologTok to
return XML_TOK_NONE on the next call, which would then cause the
function to exit with *nextPtr set to s - that is what we want for other
tokens, but not for the BOM - we would rather like to skip it;
then, when this routine is entered the next time, XmlPrologTok will
return XML_TOK_INVALID, since the BOM is still in the buffer
*/
else if (tok == XML_TOK_BOM && next == end
&& ! parser->m_parsingStatus.finalBuffer) {
*nextPtr = next;
return XML_ERROR_NONE;
}
/* If we get this token, we have the start of what might be a
normal tag, but not a declaration (i.e. it doesn't begin with
"<!"). In a DTD context, that isn't legal.
*/
else if (tok == XML_TOK_INSTANCE_START) {
*nextPtr = next;
return XML_ERROR_SYNTAX;
}
start = next;
parser->m_eventPtr = start;
}
}
static enum XML_Error PTRCALL
externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error PTRCALL
entityValueProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *start = s;
const char *next = s;
const ENCODING *enc = parser->m_encoding;
int tok;
for (;;) {
tok = XmlPrologTok(enc, start, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, enc, s, end);
}
start = next;
}
}
#endif /* XML_DTD */
static enum XML_Error PTRCALL
prologProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error
doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
int tok, const char *next, const char **nextPtr, XML_Bool haveMore) {
#ifdef XML_DTD
static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
#endif /* XML_DTD */
static const XML_Char atypeCDATA[]
= {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
static const XML_Char atypeIDREF[]
= {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
static const XML_Char atypeIDREFS[]
= {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
static const XML_Char atypeENTITY[]
= {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
static const XML_Char atypeENTITIES[]
= {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
ASCII_I, ASCII_E, ASCII_S, '\0'};
static const XML_Char atypeNMTOKEN[]
= {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
static const XML_Char atypeNMTOKENS[]
= {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
ASCII_E, ASCII_N, ASCII_S, '\0'};
static const XML_Char notationPrefix[]
= {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,
ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
/* save one level of indirection */
DTD *const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
enum XML_Content_Quant quant;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
} else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
for (;;) {
int role;
XML_Bool handleDefault = XML_TRUE;
*eventPP = s;
*eventEndPP = next;
if (tok <= 0) {
if (haveMore && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case -XML_TOK_PROLOG_S:
tok = -tok;
break;
case XML_TOK_NONE:
#ifdef XML_DTD
/* for internal PE NOT referenced between declarations */
if (enc != parser->m_encoding
&& ! parser->m_openInternalEntities->betweenDecl) {
*nextPtr = s;
return XML_ERROR_NONE;
}
/* WFC: PE Between Declarations - must check that PE contains
complete markup, not only for external PEs, but also for
internal PEs if the reference occurs between declarations.
*/
if (parser->m_isParamEntity || enc != parser->m_encoding) {
if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
== XML_ROLE_ERROR)
return XML_ERROR_INCOMPLETE_PE;
*nextPtr = s;
return XML_ERROR_NONE;
}
#endif /* XML_DTD */
return XML_ERROR_NO_ELEMENTS;
default:
tok = -tok;
next = end;
break;
}
}
role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
switch (role) {
case XML_ROLE_XML_DECL: {
enum XML_Error result = processXmlDecl(parser, 0, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
} break;
case XML_ROLE_DOCTYPE_NAME:
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeName
= poolStoreString(&parser->m_tempPool, enc, s, next);
if (! parser->m_doctypeName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = NULL;
handleDefault = XML_FALSE;
}
parser->m_doctypeSysid = NULL; /* always initialize to NULL */
break;
case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
if (parser->m_startDoctypeDeclHandler) {
parser->m_startDoctypeDeclHandler(
parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 1);
parser->m_doctypeName = NULL;
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
#ifdef XML_DTD
case XML_ROLE_TEXT_DECL: {
enum XML_Error result = processXmlDecl(parser, 1, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
} break;
#endif /* XML_DTD */
case XML_ROLE_DOCTYPE_PUBLIC_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
parser->m_declEntity = (ENTITY *)lookup(
parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
XML_Char *pubId;
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
pubId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! pubId)
return XML_ERROR_NO_MEMORY;
normalizePublicId(pubId);
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = pubId;
handleDefault = XML_FALSE;
goto alreadyChecked;
}
/* fall through */
case XML_ROLE_ENTITY_PUBLIC_ID:
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
alreadyChecked:
if (dtd->keepProcessing && parser->m_declEntity) {
XML_Char *tem
= poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declEntity->publicId = tem;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_PUBLIC_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_CLOSE:
if (parser->m_doctypeName) {
parser->m_startDoctypeDeclHandler(
parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 0);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
/* parser->m_doctypeSysid will be non-NULL in the case of a previous
XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
was not set, indicating an external subset
*/
#ifdef XML_DTD
if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing
&& parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName, sizeof(ENTITY));
if (! entity) {
/* The external subset name "#" will have already been
* inserted into the hash table at the start of the
* external entity parsing, so no allocation will happen
* and lookup() cannot fail.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
if (parser->m_useForeignDTD)
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else if (! parser->m_doctypeSysid)
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
parser->m_useForeignDTD = XML_FALSE;
}
#endif /* XML_DTD */
if (parser->m_endDoctypeDeclHandler) {
parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_INSTANCE_START:
#ifdef XML_DTD
/* if there is no DOCTYPE declaration then now is the
last chance to read the foreign DTD
*/
if (parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing
&& parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName, sizeof(ENTITY));
if (! entity)
return XML_ERROR_NO_MEMORY;
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
}
#endif /* XML_DTD */
parser->m_processor = contentProcessor;
return contentProcessor(parser, s, end, nextPtr);
case XML_ROLE_ATTLIST_ELEMENT_NAME:
parser->m_declElementType = getElementType(parser, enc, s, next);
if (! parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_NAME:
parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
if (! parser->m_declAttributeId)
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeType = NULL;
parser->m_declAttributeIsId = XML_FALSE;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
parser->m_declAttributeIsCdata = XML_TRUE;
parser->m_declAttributeType = atypeCDATA;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ID:
parser->m_declAttributeIsId = XML_TRUE;
parser->m_declAttributeType = atypeID;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
parser->m_declAttributeType = atypeIDREF;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
parser->m_declAttributeType = atypeIDREFS;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
parser->m_declAttributeType = atypeENTITY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
parser->m_declAttributeType = atypeENTITIES;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
parser->m_declAttributeType = atypeNMTOKEN;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
parser->m_declAttributeType = atypeNMTOKENS;
checkAttListDeclHandler:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
const XML_Char *prefix;
if (parser->m_declAttributeType) {
prefix = enumValueSep;
} else {
prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
: enumValueStart);
}
if (! poolAppendString(&parser->m_tempPool, prefix))
return XML_ERROR_NO_MEMORY;
if (! poolAppend(&parser->m_tempPool, enc, s, next))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
if (! defineAttribute(parser->m_declElementType,
parser->m_declAttributeId,
parser->m_declAttributeIsCdata,
parser->m_declAttributeIsId, 0, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
const XML_Char *attVal;
enum XML_Error result = storeAttributeValue(
parser, enc, parser->m_declAttributeIsCdata,
s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool);
if (result)
return result;
attVal = poolStart(&dtd->pool);
poolFinish(&dtd->pool);
/* ID attributes aren't allowed to have a default */
if (! defineAttribute(
parser->m_declElementType, parser->m_declAttributeId,
parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType,
attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_ENTITY_VALUE:
if (dtd->keepProcessing) {
enum XML_Error result = storeEntityValue(
parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
if (parser->m_declEntity) {
parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
parser->m_declEntity->textLen
= (int)(poolLength(&dtd->entityValuePool));
poolFinish(&dtd->entityValuePool);
if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
handleDefault = XML_FALSE;
}
} else
poolDiscard(&dtd->entityValuePool);
if (result != XML_ERROR_NONE)
return result;
}
break;
case XML_ROLE_DOCTYPE_SYSTEM_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (parser->m_doctypeSysid == NULL)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
#ifdef XML_DTD
else
/* use externalSubsetName to make parser->m_doctypeSysid non-NULL
for the case where no parser->m_startDoctypeDeclHandler is set */
parser->m_doctypeSysid = externalSubsetName;
#endif /* XML_DTD */
if (! dtd->standalone
#ifdef XML_DTD
&& ! parser->m_paramEntityParsing
#endif /* XML_DTD */
&& parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
#ifndef XML_DTD
break;
#else /* XML_DTD */
if (! parser->m_declEntity) {
parser->m_declEntity = (ENTITY *)lookup(
parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->publicId = NULL;
}
#endif /* XML_DTD */
/* fall through */
case XML_ROLE_ENTITY_SYSTEM_ID:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->systemId
= poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! parser->m_declEntity->systemId)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->base = parser->m_curBase;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_SYSTEM_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_COMPLETE:
if (dtd->keepProcessing && parser->m_declEntity
&& parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,
parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_NOTATION_NAME:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->notation
= poolStoreString(&dtd->pool, enc, s, next);
if (! parser->m_declEntity->notation)
return XML_ERROR_NO_MEMORY;
poolFinish(&dtd->pool);
if (parser->m_unparsedEntityDeclHandler) {
*eventEndPP = s;
parser->m_unparsedEntityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->base, parser->m_declEntity->systemId,
parser->m_declEntity->publicId, parser->m_declEntity->notation);
handleDefault = XML_FALSE;
} else if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,
parser->m_declEntity->base, parser->m_declEntity->systemId,
parser->m_declEntity->publicId, parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_GENERAL_ENTITY_NAME: {
if (XmlPredefinedEntityName(enc, s, next)) {
parser->m_declEntity = NULL;
break;
}
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (! name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,
name, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
} else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_FALSE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal
= ! (parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
} else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
} break;
case XML_ROLE_PARAM_ENTITY_NAME:
#ifdef XML_DTD
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (! name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
name, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
} else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_TRUE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal
= ! (parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
} else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
#else /* not XML_DTD */
parser->m_declEntity = NULL;
#endif /* XML_DTD */
break;
case XML_ROLE_NOTATION_NAME:
parser->m_declNotationPublicId = NULL;
parser->m_declNotationName = NULL;
if (parser->m_notationDeclHandler) {
parser->m_declNotationName
= poolStoreString(&parser->m_tempPool, enc, s, next);
if (! parser->m_declNotationName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_PUBLIC_ID:
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
if (parser
->m_declNotationName) { /* means m_notationDeclHandler != NULL */
XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declNotationPublicId = tem;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_SYSTEM_ID:
if (parser->m_declNotationName && parser->m_notationDeclHandler) {
const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! systemId)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_notationDeclHandler(
parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
systemId, parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_NOTATION_NO_SYSTEM_ID:
if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
*eventEndPP = s;
parser->m_notationDeclHandler(
parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
0, parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_ERROR:
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
/* PE references in internal subset are
not allowed within declarations. */
return XML_ERROR_PARAM_ENTITY_REF;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
default:
return XML_ERROR_SYNTAX;
}
#ifdef XML_DTD
case XML_ROLE_IGNORE_SECT: {
enum XML_Error result;
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
handleDefault = XML_FALSE;
result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (! next) {
parser->m_processor = ignoreSectionProcessor;
return result;
}
} break;
#endif /* XML_DTD */
case XML_ROLE_GROUP_OPEN:
if (parser->m_prologState.level >= parser->m_groupSize) {
if (parser->m_groupSize) {
{
char *const new_connector = (char *)REALLOC(
parser, parser->m_groupConnector, parser->m_groupSize *= 2);
if (new_connector == NULL) {
parser->m_groupSize /= 2;
return XML_ERROR_NO_MEMORY;
}
parser->m_groupConnector = new_connector;
}
if (dtd->scaffIndex) {
int *const new_scaff_index = (int *)REALLOC(
parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));
if (new_scaff_index == NULL)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex = new_scaff_index;
}
} else {
parser->m_groupConnector
= (char *)MALLOC(parser, parser->m_groupSize = 32);
if (! parser->m_groupConnector) {
parser->m_groupSize = 0;
return XML_ERROR_NO_MEMORY;
}
}
}
parser->m_groupConnector[parser->m_prologState.level] = 0;
if (dtd->in_eldecl) {
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
assert(dtd->scaffIndex != NULL);
dtd->scaffIndex[dtd->scaffLevel] = myindex;
dtd->scaffLevel++;
dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_SEQUENCE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
return XML_ERROR_SYNTAX;
parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
if (dtd->in_eldecl && parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_GROUP_CHOICE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
return XML_ERROR_SYNTAX;
if (dtd->in_eldecl
&& ! parser->m_groupConnector[parser->m_prologState.level]
&& (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
!= XML_CTYPE_MIXED)) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_CHOICE;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
break;
case XML_ROLE_PARAM_ENTITY_REF:
#ifdef XML_DTD
case XML_ROLE_INNER_PARAM_ENTITY_REF:
dtd->hasParamEntityRefs = XML_TRUE;
if (! parser->m_paramEntityParsing)
dtd->keepProcessing = dtd->standalone;
else {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&dtd->pool);
/* first, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity handler
*/
if (parser->m_prologState.documentEntity
&& (dtd->standalone ? ! parser->m_openInternalEntities
: ! dtd->hasParamEntityRefs)) {
if (! entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (! entity->is_internal) {
/* It's hard to exhaustively search the code to be sure,
* but there doesn't seem to be a way of executing the
* following line. There are two cases:
*
* If 'standalone' is false, the DTD must have no
* parameter entities or we wouldn't have passed the outer
* 'if' statement. That measn the only entity in the hash
* table is the external subset name "#" which cannot be
* given as a parameter entity name in XML syntax, so the
* lookup must have returned NULL and we don't even reach
* the test for an internal entity.
*
* If 'standalone' is true, it does not seem to be
* possible to create entities taking this code path that
* are not internal entities, so fail the test above.
*
* Because this analysis is very uncertain, the code is
* being left in place and merely removed from the
* coverage test statistics.
*/
return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
}
} else if (! entity) {
dtd->keepProcessing = dtd->standalone;
/* cannot report skipped entities in declarations */
if ((role == XML_ROLE_PARAM_ENTITY_REF)
&& parser->m_skippedEntityHandler) {
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
handleDefault = XML_FALSE;
}
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
XML_Bool betweenDecl
= (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
result = processInternalEntity(parser, entity, betweenDecl);
if (result != XML_ERROR_NONE)
return result;
handleDefault = XML_FALSE;
break;
}
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId)) {
entity->open = XML_FALSE;
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
entity->open = XML_FALSE;
handleDefault = XML_FALSE;
if (! dtd->paramEntityRead) {
dtd->keepProcessing = dtd->standalone;
break;
}
} else {
dtd->keepProcessing = dtd->standalone;
break;
}
}
#endif /* XML_DTD */
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
break;
/* Element declaration stuff */
case XML_ROLE_ELEMENT_NAME:
if (parser->m_elementDeclHandler) {
parser->m_declElementType = getElementType(parser, enc, s, next);
if (! parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
dtd->scaffLevel = 0;
dtd->scaffCount = 0;
dtd->in_eldecl = XML_TRUE;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ANY:
case XML_ROLE_CONTENT_EMPTY:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler) {
XML_Content *content
= (XML_Content *)MALLOC(parser, sizeof(XML_Content));
if (! content)
return XML_ERROR_NO_MEMORY;
content->quant = XML_CQUANT_NONE;
content->name = NULL;
content->numchildren = 0;
content->children = NULL;
content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY
: XML_CTYPE_EMPTY);
*eventEndPP = s;
parser->m_elementDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name, content);
handleDefault = XML_FALSE;
}
dtd->in_eldecl = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_PCDATA:
if (dtd->in_eldecl) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_MIXED;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ELEMENT:
quant = XML_CQUANT_NONE;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_OPT:
quant = XML_CQUANT_OPT;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_REP:
quant = XML_CQUANT_REP;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_PLUS:
quant = XML_CQUANT_PLUS;
elementContent:
if (dtd->in_eldecl) {
ELEMENT_TYPE *el;
const XML_Char *name;
int nameLen;
const char *nxt
= (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
dtd->scaffold[myindex].type = XML_CTYPE_NAME;
dtd->scaffold[myindex].quant = quant;
el = getElementType(parser, enc, s, nxt);
if (! el)
return XML_ERROR_NO_MEMORY;
name = el->name;
dtd->scaffold[myindex].name = name;
nameLen = 0;
for (; name[nameLen++];)
;
dtd->contentStringLen += nameLen;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_CLOSE:
quant = XML_CQUANT_NONE;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_OPT:
quant = XML_CQUANT_OPT;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_REP:
quant = XML_CQUANT_REP;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_PLUS:
quant = XML_CQUANT_PLUS;
closeGroup:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
dtd->scaffLevel--;
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
if (dtd->scaffLevel == 0) {
if (! handleDefault) {
XML_Content *model = build_model(parser);
if (! model)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_elementDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name, model);
}
dtd->in_eldecl = XML_FALSE;
dtd->contentStringLen = 0;
}
}
break;
/* End element declaration stuff */
case XML_ROLE_PI:
if (! reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_COMMENT:
if (! reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_NONE:
switch (tok) {
case XML_TOK_BOM:
handleDefault = XML_FALSE;
break;
}
break;
case XML_ROLE_DOCTYPE_NONE:
if (parser->m_startDoctypeDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ENTITY_NONE:
if (dtd->keepProcessing && parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_NOTATION_NONE:
if (parser->m_notationDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTLIST_NONE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ELEMENT_NONE:
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
} /* end of big switch */
if (handleDefault && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
s = next;
tok = XmlPrologTok(enc, s, end, &next);
}
}
/* not reached */
}
static enum XML_Error PTRCALL
epilogProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
parser->m_processor = epilogProcessor;
parser->m_eventPtr = s;
for (;;) {
const char *next = NULL;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
/* report partial linebreak - it might be the last token */
case -XML_TOK_PROLOG_S:
if (parser->m_defaultHandler) {
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
}
*nextPtr = next;
return XML_ERROR_NONE;
case XML_TOK_NONE:
*nextPtr = s;
return XML_ERROR_NONE;
case XML_TOK_PROLOG_S:
if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
break;
case XML_TOK_PI:
if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (! reportComment(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_INVALID:
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (! parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (! parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
default:
return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
}
parser->m_eventPtr = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:;
}
}
}
static enum XML_Error
processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
} else {
openEntity
= (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (! openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE);
} else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
static enum XML_Error PTRCALL
internalEntityProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
ENTITY *entity;
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
if (! openEntity)
return XML_ERROR_UNEXPECTED_STATE;
entity = openEntity->entity;
textStart = ((char *)entity->textPtr) + entity->processed;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE);
} else
#endif /* XML_DTD */
result = doContent(parser, openEntity->startTagLevel,
parser->m_internalEncoding, textStart, textEnd, &next,
XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
else if (textEnd != next
&& parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - (char *)entity->textPtr);
return result;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
#ifdef XML_DTD
if (entity->is_param) {
int tok;
parser->m_processor = prologProcessor;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
} else
#endif /* XML_DTD */
{
parser->m_processor = contentProcessor;
/* see externalEntityContentProcessor vs contentProcessor */
return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding,
s, end, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
}
}
static enum XML_Error PTRCALL
errorProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
UNUSED_P(s);
UNUSED_P(end);
UNUSED_P(nextPtr);
return parser->m_errorCode;
}
static enum XML_Error
storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end, STRING_POOL *pool) {
enum XML_Error result
= appendAttributeValue(parser, enc, isCdata, ptr, end, pool);
if (result)
return result;
if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
poolChop(pool);
if (! poolAppendChar(pool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
return XML_ERROR_NONE;
}
static enum XML_Error
appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end, STRING_POOL *pool) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
for (;;) {
const char *next;
int tok = XmlAttributeValueTok(enc, ptr, end, &next);
switch (tok) {
case XML_TOK_NONE:
return XML_ERROR_NONE;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_CHAR_REF: {
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, ptr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BAD_CHAR_REF;
}
if (! isCdata && n == 0x20 /* space */
&& (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (! poolAppendChar(pool, buf[i]))
return XML_ERROR_NO_MEMORY;
}
} break;
case XML_TOK_DATA_CHARS:
if (! poolAppend(pool, enc, ptr, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_TRAILING_CR:
next = ptr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_ATTRIBUTE_VALUE_S:
case XML_TOK_DATA_NEWLINE:
if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
if (! poolAppendChar(pool, 0x20))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_ENTITY_REF: {
const XML_Char *name;
ENTITY *entity;
char checkEntityDecl;
XML_Char ch = (XML_Char)XmlPredefinedEntityName(
enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);
if (ch) {
if (! poolAppendChar(pool, ch))
return XML_ERROR_NO_MEMORY;
break;
}
name = poolStoreString(&parser->m_temp2Pool, enc,
ptr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&parser->m_temp2Pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal.
*/
if (pool == &dtd->pool) /* are we called from prolog? */
checkEntityDecl =
#ifdef XML_DTD
parser->m_prologState.documentEntity &&
#endif /* XML_DTD */
(dtd->standalone ? ! parser->m_openInternalEntities
: ! dtd->hasParamEntityRefs);
else /* if (pool == &parser->m_tempPool): we are called from content */
checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;
if (checkEntityDecl) {
if (! entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (! entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
} else if (! entity) {
/* Cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler.
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
/* Cannot call the default handler because this would be
out of sync with the call to the startElementHandler.
if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
reportDefault(parser, enc, ptr, next);
*/
break;
}
if (entity->open) {
if (enc == parser->m_encoding) {
/* It does not appear that this line can be executed.
*
* The "if (entity->open)" check catches recursive entity
* definitions. In order to be called with an open
* entity, it must have gone through this code before and
* been through the recursive call to
* appendAttributeValue() some lines below. That call
* sets the local encoding ("enc") to the parser's
* internal encoding (internal_utf8 or internal_utf16),
* which can never be the same as the principle encoding.
* It doesn't appear there is another code path that gets
* here with entity->open being TRUE.
*
* Since it is not certain that this logic is watertight,
* we keep the line and merely exclude it from coverage
* tests.
*/
parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
}
return XML_ERROR_RECURSIVE_ENTITY_REF;
}
if (entity->notation) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BINARY_ENTITY_REF;
}
if (! entity->textPtr) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
} else {
enum XML_Error result;
const XML_Char *textEnd = entity->textPtr + entity->textLen;
entity->open = XML_TRUE;
result = appendAttributeValue(parser, parser->m_internalEncoding,
isCdata, (char *)entity->textPtr,
(char *)textEnd, pool);
entity->open = XML_FALSE;
if (result)
return result;
}
} break;
default:
/* The only token returned by XmlAttributeValueTok() that does
* not have an explicit case here is XML_TOK_PARTIAL_CHAR.
* Getting that would require an entity name to contain an
* incomplete XML character (e.g. \xE2\x82); however previous
* tokenisers will have already recognised and rejected such
* names before XmlAttributeValueTok() gets a look-in. This
* default case should be retained as a safety net, but the code
* excluded from coverage tests.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
ptr = next;
}
/* not reached */
}
static enum XML_Error
storeEntityValue(XML_Parser parser, const ENCODING *enc,
const char *entityTextPtr, const char *entityTextEnd) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
STRING_POOL *pool = &(dtd->entityValuePool);
enum XML_Error result = XML_ERROR_NONE;
#ifdef XML_DTD
int oldInEntityValue = parser->m_prologState.inEntityValue;
parser->m_prologState.inEntityValue = 1;
#endif /* XML_DTD */
/* never return Null for the value argument in EntityDeclHandler,
since this would indicate an external entity; therefore we
have to make sure that entityValuePool.start is not null */
if (! pool->blocks) {
if (! poolGrow(pool))
return XML_ERROR_NO_MEMORY;
}
for (;;) {
const char *next;
int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
#ifdef XML_DTD
if (parser->m_isParamEntity || enc != parser->m_encoding) {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&parser->m_tempPool, enc,
entityTextPtr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&parser->m_tempPool);
if (! entity) {
/* not a well-formedness error - see XML 1.0: WFC Entity Declared */
/* cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
dtd->keepProcessing = dtd->standalone;
goto endEntityValue;
}
if (entity->open) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_RECURSIVE_ENTITY_REF;
goto endEntityValue;
}
if (entity->systemId) {
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId)) {
entity->open = XML_FALSE;
result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
goto endEntityValue;
}
entity->open = XML_FALSE;
if (! dtd->paramEntityRead)
dtd->keepProcessing = dtd->standalone;
} else
dtd->keepProcessing = dtd->standalone;
} else {
entity->open = XML_TRUE;
result = storeEntityValue(
parser, parser->m_internalEncoding, (char *)entity->textPtr,
(char *)(entity->textPtr + entity->textLen));
entity->open = XML_FALSE;
if (result)
goto endEntityValue;
}
break;
}
#endif /* XML_DTD */
/* In the internal subset, PE references are not legal
within markup declarations, e.g entity values in this case. */
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_PARAM_ENTITY_REF;
goto endEntityValue;
case XML_TOK_NONE:
result = XML_ERROR_NONE;
goto endEntityValue;
case XML_TOK_ENTITY_REF:
case XML_TOK_DATA_CHARS:
if (! poolAppend(pool, enc, entityTextPtr, next)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
break;
case XML_TOK_TRAILING_CR:
next = entityTextPtr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_DATA_NEWLINE:
if (pool->end == pool->ptr && ! poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = 0xA;
break;
case XML_TOK_CHAR_REF: {
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, entityTextPtr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_BAD_CHAR_REF;
goto endEntityValue;
}
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (pool->end == pool->ptr && ! poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = buf[i];
}
} break;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
default:
/* This default case should be unnecessary -- all the tokens
* that XmlEntityValueTok() can return have their own explicit
* cases -- but should be retained for safety. We do however
* exclude it from the coverage statistics.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_UNEXPECTED_STATE;
goto endEntityValue;
/* LCOV_EXCL_STOP */
}
entityTextPtr = next;
}
endEntityValue:
#ifdef XML_DTD
parser->m_prologState.inEntityValue = oldInEntityValue;
#endif /* XML_DTD */
return result;
}
static void FASTCALL
normalizeLines(XML_Char *s) {
XML_Char *p;
for (;; s++) {
if (*s == XML_T('\0'))
return;
if (*s == 0xD)
break;
}
p = s;
do {
if (*s == 0xD) {
*p++ = 0xA;
if (*++s == 0xA)
s++;
} else
*p++ = *s++;
} while (*s);
*p = XML_T('\0');
}
static int
reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end) {
const XML_Char *target;
XML_Char *data;
const char *tem;
if (! parser->m_processingInstructionHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
start += enc->minBytesPerChar * 2;
tem = start + XmlNameLength(enc, start);
target = poolStoreString(&parser->m_tempPool, enc, start, tem);
if (! target)
return 0;
poolFinish(&parser->m_tempPool);
data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),
end - enc->minBytesPerChar * 2);
if (! data)
return 0;
normalizeLines(data);
parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
poolClear(&parser->m_tempPool);
return 1;
}
static int
reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end) {
XML_Char *data;
if (! parser->m_commentHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
data = poolStoreString(&parser->m_tempPool, enc,
start + enc->minBytesPerChar * 4,
end - enc->minBytesPerChar * 3);
if (! data)
return 0;
normalizeLines(data);
parser->m_commentHandler(parser->m_handlerArg, data);
poolClear(&parser->m_tempPool);
return 1;
}
static void
reportDefault(XML_Parser parser, const ENCODING *enc, const char *s,
const char *end) {
if (MUST_CONVERT(enc, s)) {
enum XML_Convert_Result convert_res;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
} else {
/* To get here, two things must be true; the parser must be
* using a character encoding that is not the same as the
* encoding passed in, and the encoding passed in must need
* conversion to the internal format (UTF-8 unless XML_UNICODE
* is defined). The only occasions on which the encoding passed
* in is not the same as the parser's encoding are when it is
* the internal encoding (e.g. a previously defined parameter
* entity, already converted to internal format). This by
* definition doesn't need conversion, so the whole branch never
* gets executed.
*
* For safety's sake we don't delete these lines and merely
* exclude them from coverage statistics.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
do {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
convert_res
= XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
*eventPP = s;
} while ((convert_res != XML_CONVERT_COMPLETED)
&& (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
} else
parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)end - (XML_Char *)s));
}
static int
defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
XML_Bool isId, const XML_Char *value, XML_Parser parser) {
DEFAULT_ATTRIBUTE *att;
if (value || isId) {
/* The handling of default attributes gets messed up if we have
a default which duplicates a non-default. */
int i;
for (i = 0; i < type->nDefaultAtts; i++)
if (attId == type->defaultAtts[i].id)
return 1;
if (isId && ! type->idAtt && ! attId->xmlns)
type->idAtt = attId;
}
if (type->nDefaultAtts == type->allocDefaultAtts) {
if (type->allocDefaultAtts == 0) {
type->allocDefaultAtts = 8;
type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(
parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
if (! type->defaultAtts) {
type->allocDefaultAtts = 0;
return 0;
}
} else {
DEFAULT_ATTRIBUTE *temp;
int count = type->allocDefaultAtts * 2;
temp = (DEFAULT_ATTRIBUTE *)REALLOC(parser, type->defaultAtts,
(count * sizeof(DEFAULT_ATTRIBUTE)));
if (temp == NULL)
return 0;
type->allocDefaultAtts = count;
type->defaultAtts = temp;
}
}
att = type->defaultAtts + type->nDefaultAtts;
att->id = attId;
att->value = value;
att->isCdata = isCdata;
if (! isCdata)
attId->maybeTokenized = XML_TRUE;
type->nDefaultAtts += 1;
return 1;
}
static int
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
PREFIX *prefix;
const XML_Char *s;
for (s = elementType->name; s != name; s++) {
if (! poolAppendChar(&dtd->pool, *s))
return 0;
}
if (! poolAppendChar(&dtd->pool, XML_T('\0')))
return 0;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (! prefix)
return 0;
if (prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
break;
}
}
return 1;
}
static ATTRIBUTE_ID *
getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
ATTRIBUTE_ID *id;
const XML_Char *name;
if (! poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
name = poolStoreString(&dtd->pool, enc, start, end);
if (! name)
return NULL;
/* skip quotation mark - its storage will be re-used (like in name[-1]) */
++name;
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,
sizeof(ATTRIBUTE_ID));
if (! id)
return NULL;
if (id->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (! parser->m_ns)
;
else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)
&& name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)
&& name[4] == XML_T(ASCII_s)
&& (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
if (name[5] == XML_T('\0'))
id->prefix = &dtd->defaultPrefix;
else
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,
sizeof(PREFIX));
id->xmlns = XML_TRUE;
} else {
int i;
for (i = 0; name[i]; i++) {
/* attributes without prefix are *not* in the default namespace */
if (name[i] == XML_T(ASCII_COLON)) {
int j;
for (j = 0; j < i; j++) {
if (! poolAppendChar(&dtd->pool, name[j]))
return NULL;
}
if (! poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,
poolStart(&dtd->pool), sizeof(PREFIX));
if (! id->prefix)
return NULL;
if (id->prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
break;
}
}
}
}
return id;
}
#define CONTEXT_SEP XML_T(ASCII_FF)
static const XML_Char *
getContext(XML_Parser parser) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
HASH_TABLE_ITER iter;
XML_Bool needSep = XML_FALSE;
if (dtd->defaultPrefix.binding) {
int i;
int len;
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = dtd->defaultPrefix.binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++) {
if (! poolAppendChar(&parser->m_tempPool,
dtd->defaultPrefix.binding->uri[i])) {
/* Because of memory caching, I don't believe this line can be
* executed.
*
* This is part of a loop copying the default prefix binding
* URI into the parser's temporary string pool. Previously,
* that URI was copied into the same string pool, with a
* terminating NUL character, as part of setContext(). When
* the pool was cleared, that leaves a block definitely big
* enough to hold the URI on the free block list of the pool.
* The URI copy in getContext() therefore cannot run out of
* memory.
*
* If the pool is used between the setContext() and
* getContext() calls, the worst it can do is leave a bigger
* block on the front of the free list. Given that this is
* all somewhat inobvious and program logic can be changed, we
* don't delete the line but we do exclude it from the test
* coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
}
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->prefixes));
for (;;) {
int i;
int len;
const XML_Char *s;
PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
if (! prefix)
break;
if (! prefix->binding) {
/* This test appears to be (justifiable) paranoia. There does
* not seem to be a way of injecting a prefix without a binding
* that doesn't get errored long before this function is called.
* The test should remain for safety's sake, so we instead
* exclude the following line from the coverage statistics.
*/
continue; /* LCOV_EXCL_LINE */
}
if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = prefix->name; *s; s++)
if (! poolAppendChar(&parser->m_tempPool, *s))
return NULL;
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = prefix->binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++)
if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
return NULL;
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->generalEntities));
for (;;) {
const XML_Char *s;
ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
if (! e)
break;
if (! e->open)
continue;
if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = e->name; *s; s++)
if (! poolAppendChar(&parser->m_tempPool, *s))
return 0;
needSep = XML_TRUE;
}
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return NULL;
return parser->m_tempPool.start;
}
static XML_Bool
setContext(XML_Parser parser, const XML_Char *context) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *s = context;
while (*context != XML_T('\0')) {
if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
ENTITY *e;
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
e = (ENTITY *)lookup(parser, &dtd->generalEntities,
poolStart(&parser->m_tempPool), 0);
if (e)
e->open = XML_TRUE;
if (*s != XML_T('\0'))
s++;
context = s;
poolDiscard(&parser->m_tempPool);
} else if (*s == XML_T(ASCII_EQUALS)) {
PREFIX *prefix;
if (poolLength(&parser->m_tempPool) == 0)
prefix = &dtd->defaultPrefix;
else {
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
prefix
= (PREFIX *)lookup(parser, &dtd->prefixes,
poolStart(&parser->m_tempPool), sizeof(PREFIX));
if (! prefix)
return XML_FALSE;
if (prefix->name == poolStart(&parser->m_tempPool)) {
prefix->name = poolCopyString(&dtd->pool, prefix->name);
if (! prefix->name)
return XML_FALSE;
}
poolDiscard(&parser->m_tempPool);
}
for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\0');
context++)
if (! poolAppendChar(&parser->m_tempPool, *context))
return XML_FALSE;
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
&parser->m_inheritedBindings)
!= XML_ERROR_NONE)
return XML_FALSE;
poolDiscard(&parser->m_tempPool);
if (*context != XML_T('\0'))
++context;
s = context;
} else {
if (! poolAppendChar(&parser->m_tempPool, *s))
return XML_FALSE;
s++;
}
}
return XML_TRUE;
}
static void FASTCALL
normalizePublicId(XML_Char *publicId) {
XML_Char *p = publicId;
XML_Char *s;
for (s = publicId; *s; s++) {
switch (*s) {
case 0x20:
case 0xD:
case 0xA:
if (p != publicId && p[-1] != 0x20)
*p++ = 0x20;
break;
default:
*p++ = *s;
}
}
if (p != publicId && p[-1] == 0x20)
--p;
*p = XML_T('\0');
}
static DTD *
dtdCreate(const XML_Memory_Handling_Suite *ms) {
DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD));
if (p == NULL)
return p;
poolInit(&(p->pool), ms);
poolInit(&(p->entityValuePool), ms);
hashTableInit(&(p->generalEntities), ms);
hashTableInit(&(p->elementTypes), ms);
hashTableInit(&(p->attributeIds), ms);
hashTableInit(&(p->prefixes), ms);
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableInit(&(p->paramEntities), ms);
#endif /* XML_DTD */
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
p->scaffIndex = NULL;
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
return p;
}
static void
dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms) {
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (! e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableClear(&(p->generalEntities));
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableClear(&(p->paramEntities));
#endif /* XML_DTD */
hashTableClear(&(p->elementTypes));
hashTableClear(&(p->attributeIds));
hashTableClear(&(p->prefixes));
poolClear(&(p->pool));
poolClear(&(p->entityValuePool));
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
ms->free_fcn(p->scaffIndex);
p->scaffIndex = NULL;
ms->free_fcn(p->scaffold);
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
}
static void
dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms) {
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (! e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableDestroy(&(p->generalEntities));
#ifdef XML_DTD
hashTableDestroy(&(p->paramEntities));
#endif /* XML_DTD */
hashTableDestroy(&(p->elementTypes));
hashTableDestroy(&(p->attributeIds));
hashTableDestroy(&(p->prefixes));
poolDestroy(&(p->pool));
poolDestroy(&(p->entityValuePool));
if (isDocEntity) {
ms->free_fcn(p->scaffIndex);
ms->free_fcn(p->scaffold);
}
ms->free_fcn(p);
}
/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
The new DTD has already been initialized.
*/
static int
dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
const XML_Memory_Handling_Suite *ms) {
HASH_TABLE_ITER iter;
/* Copy the prefix table. */
hashTableIterInit(&iter, &(oldDtd->prefixes));
for (;;) {
const XML_Char *name;
const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
if (! oldP)
break;
name = poolCopyString(&(newDtd->pool), oldP->name);
if (! name)
return 0;
if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
return 0;
}
hashTableIterInit(&iter, &(oldDtd->attributeIds));
/* Copy the attribute id table. */
for (;;) {
ATTRIBUTE_ID *newA;
const XML_Char *name;
const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
if (! oldA)
break;
/* Remember to allocate the scratch byte before the name. */
if (! poolAppendChar(&(newDtd->pool), XML_T('\0')))
return 0;
name = poolCopyString(&(newDtd->pool), oldA->name);
if (! name)
return 0;
++name;
newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
sizeof(ATTRIBUTE_ID));
if (! newA)
return 0;
newA->maybeTokenized = oldA->maybeTokenized;
if (oldA->prefix) {
newA->xmlns = oldA->xmlns;
if (oldA->prefix == &oldDtd->defaultPrefix)
newA->prefix = &newDtd->defaultPrefix;
else
newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldA->prefix->name, 0);
}
}
/* Copy the element type table. */
hashTableIterInit(&iter, &(oldDtd->elementTypes));
for (;;) {
int i;
ELEMENT_TYPE *newE;
const XML_Char *name;
const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (! oldE)
break;
name = poolCopyString(&(newDtd->pool), oldE->name);
if (! name)
return 0;
newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
sizeof(ELEMENT_TYPE));
if (! newE)
return 0;
if (oldE->nDefaultAtts) {
newE->defaultAtts = (DEFAULT_ATTRIBUTE *)ms->malloc_fcn(
oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
if (! newE->defaultAtts) {
return 0;
}
}
if (oldE->idAtt)
newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),
oldE->idAtt->name, 0);
newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
if (oldE->prefix)
newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldE->prefix->name, 0);
for (i = 0; i < newE->nDefaultAtts; i++) {
newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(
oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
if (oldE->defaultAtts[i].value) {
newE->defaultAtts[i].value
= poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
if (! newE->defaultAtts[i].value)
return 0;
} else
newE->defaultAtts[i].value = NULL;
}
}
/* Copy the entity tables. */
if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),
&(oldDtd->generalEntities)))
return 0;
#ifdef XML_DTD
if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),
&(oldDtd->paramEntities)))
return 0;
newDtd->paramEntityRead = oldDtd->paramEntityRead;
#endif /* XML_DTD */
newDtd->keepProcessing = oldDtd->keepProcessing;
newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
newDtd->standalone = oldDtd->standalone;
/* Don't want deep copying for scaffolding */
newDtd->in_eldecl = oldDtd->in_eldecl;
newDtd->scaffold = oldDtd->scaffold;
newDtd->contentStringLen = oldDtd->contentStringLen;
newDtd->scaffSize = oldDtd->scaffSize;
newDtd->scaffLevel = oldDtd->scaffLevel;
newDtd->scaffIndex = oldDtd->scaffIndex;
return 1;
} /* End dtdCopy */
static int
copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
STRING_POOL *newPool, const HASH_TABLE *oldTable) {
HASH_TABLE_ITER iter;
const XML_Char *cachedOldBase = NULL;
const XML_Char *cachedNewBase = NULL;
hashTableIterInit(&iter, oldTable);
for (;;) {
ENTITY *newE;
const XML_Char *name;
const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
if (! oldE)
break;
name = poolCopyString(newPool, oldE->name);
if (! name)
return 0;
newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
if (! newE)
return 0;
if (oldE->systemId) {
const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
if (! tem)
return 0;
newE->systemId = tem;
if (oldE->base) {
if (oldE->base == cachedOldBase)
newE->base = cachedNewBase;
else {
cachedOldBase = oldE->base;
tem = poolCopyString(newPool, cachedOldBase);
if (! tem)
return 0;
cachedNewBase = newE->base = tem;
}
}
if (oldE->publicId) {
tem = poolCopyString(newPool, oldE->publicId);
if (! tem)
return 0;
newE->publicId = tem;
}
} else {
const XML_Char *tem
= poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);
if (! tem)
return 0;
newE->textPtr = tem;
newE->textLen = oldE->textLen;
}
if (oldE->notation) {
const XML_Char *tem = poolCopyString(newPool, oldE->notation);
if (! tem)
return 0;
newE->notation = tem;
}
newE->is_param = oldE->is_param;
newE->is_internal = oldE->is_internal;
}
return 1;
}
#define INIT_POWER 6
static XML_Bool FASTCALL
keyeq(KEY s1, KEY s2) {
for (; *s1 == *s2; s1++, s2++)
if (*s1 == 0)
return XML_TRUE;
return XML_FALSE;
}
static size_t
keylen(KEY s) {
size_t len = 0;
for (; *s; s++, len++)
;
return len;
}
static void
copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {
key->k[0] = 0;
key->k[1] = get_hash_secret_salt(parser);
}
static unsigned long FASTCALL
hash(XML_Parser parser, KEY s) {
struct siphash state;
struct sipkey key;
(void)sip24_valid;
copy_salt_to_sipkey(parser, &key);
sip24_init(&state, &key);
sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
return (unsigned long)sip24_final(&state);
}
static NAMED *
lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {
size_t i;
if (table->size == 0) {
size_t tsize;
if (! createSize)
return NULL;
table->power = INIT_POWER;
/* table->size is a power of 2 */
table->size = (size_t)1 << INIT_POWER;
tsize = table->size * sizeof(NAMED *);
table->v = (NAMED **)table->mem->malloc_fcn(tsize);
if (! table->v) {
table->size = 0;
return NULL;
}
memset(table->v, 0, tsize);
i = hash(parser, name) & ((unsigned long)table->size - 1);
} else {
unsigned long h = hash(parser, name);
unsigned long mask = (unsigned long)table->size - 1;
unsigned char step = 0;
i = h & mask;
while (table->v[i]) {
if (keyeq(name, table->v[i]->name))
return table->v[i];
if (! step)
step = PROBE_STEP(h, mask, table->power);
i < step ? (i += table->size - step) : (i -= step);
}
if (! createSize)
return NULL;
/* check for overflow (table is half full) */
if (table->used >> (table->power - 1)) {
unsigned char newPower = table->power + 1;
size_t newSize = (size_t)1 << newPower;
unsigned long newMask = (unsigned long)newSize - 1;
size_t tsize = newSize * sizeof(NAMED *);
NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize);
if (! newV)
return NULL;
memset(newV, 0, tsize);
for (i = 0; i < table->size; i++)
if (table->v[i]) {
unsigned long newHash = hash(parser, table->v[i]->name);
size_t j = newHash & newMask;
step = 0;
while (newV[j]) {
if (! step)
step = PROBE_STEP(newHash, newMask, newPower);
j < step ? (j += newSize - step) : (j -= step);
}
newV[j] = table->v[i];
}
table->mem->free_fcn(table->v);
table->v = newV;
table->power = newPower;
table->size = newSize;
i = h & newMask;
step = 0;
while (table->v[i]) {
if (! step)
step = PROBE_STEP(h, newMask, newPower);
i < step ? (i += newSize - step) : (i -= step);
}
}
}
table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize);
if (! table->v[i])
return NULL;
memset(table->v[i], 0, createSize);
table->v[i]->name = name;
(table->used)++;
return table->v[i];
}
static void FASTCALL
hashTableClear(HASH_TABLE *table) {
size_t i;
for (i = 0; i < table->size; i++) {
table->mem->free_fcn(table->v[i]);
table->v[i] = NULL;
}
table->used = 0;
}
static void FASTCALL
hashTableDestroy(HASH_TABLE *table) {
size_t i;
for (i = 0; i < table->size; i++)
table->mem->free_fcn(table->v[i]);
table->mem->free_fcn(table->v);
}
static void FASTCALL
hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms) {
p->power = 0;
p->size = 0;
p->used = 0;
p->v = NULL;
p->mem = ms;
}
static void FASTCALL
hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {
iter->p = table->v;
iter->end = iter->p + table->size;
}
static NAMED *FASTCALL
hashTableIterNext(HASH_TABLE_ITER *iter) {
while (iter->p != iter->end) {
NAMED *tem = *(iter->p)++;
if (tem)
return tem;
}
return NULL;
}
static void FASTCALL
poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) {
pool->blocks = NULL;
pool->freeBlocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
pool->mem = ms;
}
static void FASTCALL
poolClear(STRING_POOL *pool) {
if (! pool->freeBlocks)
pool->freeBlocks = pool->blocks;
else {
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
p->next = pool->freeBlocks;
pool->freeBlocks = p;
p = tem;
}
}
pool->blocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
}
static void FASTCALL
poolDestroy(STRING_POOL *pool) {
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
p = pool->freeBlocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
}
static XML_Char *
poolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
const char *end) {
if (! pool->ptr && ! poolGrow(pool))
return NULL;
for (;;) {
const enum XML_Convert_Result convert_res = XmlConvert(
enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
if ((convert_res == XML_CONVERT_COMPLETED)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
if (! poolGrow(pool))
return NULL;
}
return pool->start;
}
static const XML_Char *FASTCALL
poolCopyString(STRING_POOL *pool, const XML_Char *s) {
do {
if (! poolAppendChar(pool, *s))
return NULL;
} while (*s++);
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char *
poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {
if (! pool->ptr && ! poolGrow(pool)) {
/* The following line is unreachable given the current usage of
* poolCopyStringN(). Currently it is called from exactly one
* place to copy the text of a simple general entity. By that
* point, the name of the entity is already stored in the pool, so
* pool->ptr cannot be NULL.
*
* If poolCopyStringN() is used elsewhere as it well might be,
* this line may well become executable again. Regardless, this
* sort of check shouldn't be removed lightly, so we just exclude
* it from the coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
for (; n > 0; --n, s++) {
if (! poolAppendChar(pool, *s))
return NULL;
}
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char *FASTCALL
poolAppendString(STRING_POOL *pool, const XML_Char *s) {
while (*s) {
if (! poolAppendChar(pool, *s))
return NULL;
s++;
}
return pool->start;
}
static XML_Char *
poolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
const char *end) {
if (! poolAppend(pool, enc, ptr, end))
return NULL;
if (pool->ptr == pool->end && ! poolGrow(pool))
return NULL;
*(pool->ptr)++ = 0;
return pool->start;
}
static size_t
poolBytesToAllocateFor(int blockSize) {
/* Unprotected math would be:
** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
**
** Detect overflow, avoiding _signed_ overflow undefined behavior
** For a + b * c we check b * c in isolation first, so that addition of a
** on top has no chance of making us accept a small non-negative number
*/
const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
if (blockSize <= 0)
return 0;
if (blockSize > (int)(INT_MAX / stretch))
return 0;
{
const int stretchedBlockSize = blockSize * (int)stretch;
const int bytesToAllocate
= (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
if (bytesToAllocate < 0)
return 0;
return (size_t)bytesToAllocate;
}
}
static XML_Bool FASTCALL
poolGrow(STRING_POOL *pool) {
if (pool->freeBlocks) {
if (pool->start == 0) {
pool->blocks = pool->freeBlocks;
pool->freeBlocks = pool->freeBlocks->next;
pool->blocks->next = NULL;
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
pool->ptr = pool->start;
return XML_TRUE;
}
if (pool->end - pool->start < pool->freeBlocks->size) {
BLOCK *tem = pool->freeBlocks->next;
pool->freeBlocks->next = pool->blocks;
pool->blocks = pool->freeBlocks;
pool->freeBlocks = tem;
memcpy(pool->blocks->s, pool->start,
(pool->end - pool->start) * sizeof(XML_Char));
pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
return XML_TRUE;
}
}
if (pool->blocks && pool->start == pool->blocks->s) {
BLOCK *temp;
int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);
size_t bytesToAllocate;
/* NOTE: Needs to be calculated prior to calling `realloc`
to avoid dangling pointers: */
const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX/2 bytes have already been allocated. This isn't
* readily testable, since it is unlikely that an average
* machine will have that much memory, so we exclude it from the
* coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
temp = (BLOCK *)pool->mem->realloc_fcn(pool->blocks,
(unsigned)bytesToAllocate);
if (temp == NULL)
return XML_FALSE;
pool->blocks = temp;
pool->blocks->size = blockSize;
pool->ptr = pool->blocks->s + offsetInsideBlock;
pool->start = pool->blocks->s;
pool->end = pool->start + blockSize;
} else {
BLOCK *tem;
int blockSize = (int)(pool->end - pool->start);
size_t bytesToAllocate;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX bytes have already been allocated (which is prevented
* by various pieces of program logic, not least this one, never
* mind the unlikelihood of actually having that much memory) or
* the pool control fields have been corrupted (which could
* conceivably happen in an extremely buggy user handler
* function). Either way it isn't readily testable, so we
* exclude it from the coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
if (blockSize < INIT_BLOCK_SIZE)
blockSize = INIT_BLOCK_SIZE;
else {
/* Detect overflow, avoiding _signed_ overflow undefined behavior */
if ((int)((unsigned)blockSize * 2U) < 0) {
return XML_FALSE;
}
blockSize *= 2;
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate);
if (! tem)
return XML_FALSE;
tem->size = blockSize;
tem->next = pool->blocks;
pool->blocks = tem;
if (pool->ptr != pool->start)
memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));
pool->ptr = tem->s + (pool->ptr - pool->start);
pool->start = tem->s;
pool->end = tem->s + blockSize;
}
return XML_TRUE;
}
static int FASTCALL
nextScaffoldPart(XML_Parser parser) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
CONTENT_SCAFFOLD *me;
int next;
if (! dtd->scaffIndex) {
dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
if (! dtd->scaffIndex)
return -1;
dtd->scaffIndex[0] = 0;
}
if (dtd->scaffCount >= dtd->scaffSize) {
CONTENT_SCAFFOLD *temp;
if (dtd->scaffold) {
temp = (CONTENT_SCAFFOLD *)REALLOC(
parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize *= 2;
} else {
temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
* sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
}
dtd->scaffold = temp;
}
next = dtd->scaffCount++;
me = &dtd->scaffold[next];
if (dtd->scaffLevel) {
CONTENT_SCAFFOLD *parent
= &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];
if (parent->lastchild) {
dtd->scaffold[parent->lastchild].nextsib = next;
}
if (! parent->childcnt)
parent->firstchild = next;
parent->lastchild = next;
parent->childcnt++;
}
me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
return next;
}
static void
build_node(XML_Parser parser, int src_node, XML_Content *dest,
XML_Content **contpos, XML_Char **strpos) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
dest->type = dtd->scaffold[src_node].type;
dest->quant = dtd->scaffold[src_node].quant;
if (dest->type == XML_CTYPE_NAME) {
const XML_Char *src;
dest->name = *strpos;
src = dtd->scaffold[src_node].name;
for (;;) {
*(*strpos)++ = *src;
if (! *src)
break;
src++;
}
dest->numchildren = 0;
dest->children = NULL;
} else {
unsigned int i;
int cn;
dest->numchildren = dtd->scaffold[src_node].childcnt;
dest->children = *contpos;
*contpos += dest->numchildren;
for (i = 0, cn = dtd->scaffold[src_node].firstchild; i < dest->numchildren;
i++, cn = dtd->scaffold[cn].nextsib) {
build_node(parser, cn, &(dest->children[i]), contpos, strpos);
}
dest->name = NULL;
}
}
static XML_Content *
build_model(XML_Parser parser) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
XML_Content *ret;
XML_Content *cpos;
XML_Char *str;
int allocsize = (dtd->scaffCount * sizeof(XML_Content)
+ (dtd->contentStringLen * sizeof(XML_Char)));
ret = (XML_Content *)MALLOC(parser, allocsize);
if (! ret)
return NULL;
str = (XML_Char *)(&ret[dtd->scaffCount]);
cpos = &ret[1];
build_node(parser, 0, ret, &cpos, &str);
return ret;
}
static ELEMENT_TYPE *
getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,
const char *end) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
ELEMENT_TYPE *ret;
if (! name)
return NULL;
ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
sizeof(ELEMENT_TYPE));
if (! ret)
return NULL;
if (ret->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (! setElementTypePrefix(parser, ret))
return NULL;
}
return ret;
}
static XML_Char *
copyString(const XML_Char *s, const XML_Memory_Handling_Suite *memsuite) {
int charsRequired = 0;
XML_Char *result;
/* First determine how long the string is */
while (s[charsRequired] != 0) {
charsRequired++;
}
/* Include the terminator */
charsRequired++;
/* Now allocate space for the copy */
result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
if (result == NULL)
return NULL;
/* Copy the original into place */
memcpy(result, s, charsRequired * sizeof(XML_Char));
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/bad_1054_0 |
crossvul-cpp_data_good_1054_0 | /* 69df5be70289a11fb834869ce4a91c23c1d9dd04baffcbd10e86742d149a080c (2.2.7+)
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000-2017 Expat development team
Licensed under the MIT license:
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.
*/
#if ! defined(_GNU_SOURCE)
# define _GNU_SOURCE 1 /* syscall prototype */
#endif
#ifdef _WIN32
/* force stdlib to define rand_s() */
# define _CRT_RAND_S
#endif
#include <stddef.h>
#include <string.h> /* memset(), memcpy() */
#include <assert.h>
#include <limits.h> /* UINT_MAX */
#include <stdio.h> /* fprintf */
#include <stdlib.h> /* getenv, rand_s */
#ifdef _WIN32
# define getpid GetCurrentProcessId
#else
# include <sys/time.h> /* gettimeofday() */
# include <sys/types.h> /* getpid() */
# include <unistd.h> /* getpid() */
# include <fcntl.h> /* O_RDONLY */
# include <errno.h>
#endif
#define XML_BUILDING_EXPAT 1
#ifdef _WIN32
# include "winconfig.h"
#elif defined(HAVE_EXPAT_CONFIG_H)
# include <expat_config.h>
#endif /* ndef _WIN32 */
#include "ascii.h"
#include "expat.h"
#include "siphash.h"
#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
# if defined(HAVE_GETRANDOM)
# include <sys/random.h> /* getrandom */
# else
# include <unistd.h> /* syscall */
# include <sys/syscall.h> /* SYS_getrandom */
# endif
# if ! defined(GRND_NONBLOCK)
# define GRND_NONBLOCK 0x0001
# endif /* defined(GRND_NONBLOCK) */
#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
#if defined(HAVE_LIBBSD) \
&& (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
# include <bsd/stdlib.h>
#endif
#if defined(_WIN32) && ! defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
#if ! defined(HAVE_GETRANDOM) && ! defined(HAVE_SYSCALL_GETRANDOM) \
&& ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) \
&& ! defined(XML_DEV_URANDOM) && ! defined(_WIN32) \
&& ! defined(XML_POOR_ENTROPY)
# error You do not have support for any sources of high quality entropy \
enabled. For end user security, that is probably not what you want. \
\
Your options include: \
* Linux + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
* Linux + glibc <2.25 (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
* BSD / macOS >=10.7 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
* BSD / macOS <10.7 (arc4random): HAVE_ARC4RANDOM, \
* libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
* libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
* Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \
* Windows (rand_s): _WIN32. \
\
If insist on not using any of these, bypass this error by defining \
XML_POOR_ENTROPY; you have been warned. \
\
If you have reasons to patch this detection code away or need changes \
to the build system, please open a bug. Thank you!
#endif
#ifdef XML_UNICODE
# define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
# define XmlConvert XmlUtf16Convert
# define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
# define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
# define XmlEncode XmlUtf16Encode
/* Using pointer subtraction to convert to integer type. */
# define MUST_CONVERT(enc, s) \
(! (enc)->isUtf16 || (((char *)(s) - (char *)NULL) & 1))
typedef unsigned short ICHAR;
#else
# define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
# define XmlConvert XmlUtf8Convert
# define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
# define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
# define XmlEncode XmlUtf8Encode
# define MUST_CONVERT(enc, s) (! (enc)->isUtf8)
typedef char ICHAR;
#endif
#ifndef XML_NS
# define XmlInitEncodingNS XmlInitEncoding
# define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
# undef XmlGetInternalEncodingNS
# define XmlGetInternalEncodingNS XmlGetInternalEncoding
# define XmlParseXmlDeclNS XmlParseXmlDecl
#endif
#ifdef XML_UNICODE
# ifdef XML_UNICODE_WCHAR_T
# define XML_T(x) (const wchar_t) x
# define XML_L(x) L##x
# else
# define XML_T(x) (const unsigned short)x
# define XML_L(x) x
# endif
#else
# define XML_T(x) x
# define XML_L(x) x
#endif
/* Round up n to be a multiple of sz, where sz is a power of 2. */
#define ROUND_UP(n, sz) (((n) + ((sz)-1)) & ~((sz)-1))
/* Do safe (NULL-aware) pointer arithmetic */
#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
#include "internal.h"
#include "xmltok.h"
#include "xmlrole.h"
typedef const XML_Char *KEY;
typedef struct {
KEY name;
} NAMED;
typedef struct {
NAMED **v;
unsigned char power;
size_t size;
size_t used;
const XML_Memory_Handling_Suite *mem;
} HASH_TABLE;
static size_t keylen(KEY s);
static void copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key);
/* For probing (after a collision) we need a step size relative prime
to the hash table size, which is a power of 2. We use double-hashing,
since we can calculate a second hash value cheaply by taking those bits
of the first hash value that were discarded (masked out) when the table
index was calculated: index = hash & mask, where mask = table->size - 1.
We limit the maximum step size to table->size / 4 (mask >> 2) and make
it odd, since odd numbers are always relative prime to a power of 2.
*/
#define SECOND_HASH(hash, mask, power) \
((((hash) & ~(mask)) >> ((power)-1)) & ((mask) >> 2))
#define PROBE_STEP(hash, mask, power) \
((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
typedef struct {
NAMED **p;
NAMED **end;
} HASH_TABLE_ITER;
#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
#define INIT_DATA_BUF_SIZE 1024
#define INIT_ATTS_SIZE 16
#define INIT_ATTS_VERSION 0xFFFFFFFF
#define INIT_BLOCK_SIZE 1024
#define INIT_BUFFER_SIZE 1024
#define EXPAND_SPARE 24
typedef struct binding {
struct prefix *prefix;
struct binding *nextTagBinding;
struct binding *prevPrefixBinding;
const struct attribute_id *attId;
XML_Char *uri;
int uriLen;
int uriAlloc;
} BINDING;
typedef struct prefix {
const XML_Char *name;
BINDING *binding;
} PREFIX;
typedef struct {
const XML_Char *str;
const XML_Char *localPart;
const XML_Char *prefix;
int strLen;
int uriLen;
int prefixLen;
} TAG_NAME;
/* TAG represents an open element.
The name of the element is stored in both the document and API
encodings. The memory buffer 'buf' is a separately-allocated
memory area which stores the name. During the XML_Parse()/
XMLParseBuffer() when the element is open, the memory for the 'raw'
version of the name (in the document encoding) is shared with the
document buffer. If the element is open across calls to
XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to
contain the 'raw' name as well.
A parser re-uses these structures, maintaining a list of allocated
TAG objects in a free list.
*/
typedef struct tag {
struct tag *parent; /* parent of this element */
const char *rawName; /* tagName in the original encoding */
int rawNameLength;
TAG_NAME name; /* tagName in the API encoding */
char *buf; /* buffer for name components */
char *bufEnd; /* end of the buffer */
BINDING *bindings;
} TAG;
typedef struct {
const XML_Char *name;
const XML_Char *textPtr;
int textLen; /* length in XML_Chars */
int processed; /* # of processed bytes - when suspended */
const XML_Char *systemId;
const XML_Char *base;
const XML_Char *publicId;
const XML_Char *notation;
XML_Bool open;
XML_Bool is_param;
XML_Bool is_internal; /* true if declared in internal subset outside PE */
} ENTITY;
typedef struct {
enum XML_Content_Type type;
enum XML_Content_Quant quant;
const XML_Char *name;
int firstchild;
int lastchild;
int childcnt;
int nextsib;
} CONTENT_SCAFFOLD;
#define INIT_SCAFFOLD_ELEMENTS 32
typedef struct block {
struct block *next;
int size;
XML_Char s[1];
} BLOCK;
typedef struct {
BLOCK *blocks;
BLOCK *freeBlocks;
const XML_Char *end;
XML_Char *ptr;
XML_Char *start;
const XML_Memory_Handling_Suite *mem;
} STRING_POOL;
/* The XML_Char before the name is used to determine whether
an attribute has been specified. */
typedef struct attribute_id {
XML_Char *name;
PREFIX *prefix;
XML_Bool maybeTokenized;
XML_Bool xmlns;
} ATTRIBUTE_ID;
typedef struct {
const ATTRIBUTE_ID *id;
XML_Bool isCdata;
const XML_Char *value;
} DEFAULT_ATTRIBUTE;
typedef struct {
unsigned long version;
unsigned long hash;
const XML_Char *uriName;
} NS_ATT;
typedef struct {
const XML_Char *name;
PREFIX *prefix;
const ATTRIBUTE_ID *idAtt;
int nDefaultAtts;
int allocDefaultAtts;
DEFAULT_ATTRIBUTE *defaultAtts;
} ELEMENT_TYPE;
typedef struct {
HASH_TABLE generalEntities;
HASH_TABLE elementTypes;
HASH_TABLE attributeIds;
HASH_TABLE prefixes;
STRING_POOL pool;
STRING_POOL entityValuePool;
/* false once a parameter entity reference has been skipped */
XML_Bool keepProcessing;
/* true once an internal or external PE reference has been encountered;
this includes the reference to an external subset */
XML_Bool hasParamEntityRefs;
XML_Bool standalone;
#ifdef XML_DTD
/* indicates if external PE has been read */
XML_Bool paramEntityRead;
HASH_TABLE paramEntities;
#endif /* XML_DTD */
PREFIX defaultPrefix;
/* === scaffolding for building content model === */
XML_Bool in_eldecl;
CONTENT_SCAFFOLD *scaffold;
unsigned contentStringLen;
unsigned scaffSize;
unsigned scaffCount;
int scaffLevel;
int *scaffIndex;
} DTD;
typedef struct open_internal_entity {
const char *internalEventPtr;
const char *internalEventEndPtr;
struct open_internal_entity *next;
ENTITY *entity;
int startTagLevel;
XML_Bool betweenDecl; /* WFC: PE Between Declarations */
} OPEN_INTERNAL_ENTITY;
typedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,
const char *end, const char **endPtr);
static Processor prologProcessor;
static Processor prologInitProcessor;
static Processor contentProcessor;
static Processor cdataSectionProcessor;
#ifdef XML_DTD
static Processor ignoreSectionProcessor;
static Processor externalParEntProcessor;
static Processor externalParEntInitProcessor;
static Processor entityValueProcessor;
static Processor entityValueInitProcessor;
#endif /* XML_DTD */
static Processor epilogProcessor;
static Processor errorProcessor;
static Processor externalEntityInitProcessor;
static Processor externalEntityInitProcessor2;
static Processor externalEntityInitProcessor3;
static Processor externalEntityContentProcessor;
static Processor internalEntityProcessor;
static enum XML_Error handleUnknownEncoding(XML_Parser parser,
const XML_Char *encodingName);
static enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
const char *s, const char *next);
static enum XML_Error initializeEncoding(XML_Parser parser);
static enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,
const char *s, const char *end, int tok,
const char *next, const char **nextPtr,
XML_Bool haveMore, XML_Bool allowClosingDoctype);
static enum XML_Error processInternalEntity(XML_Parser parser, ENTITY *entity,
XML_Bool betweenDecl);
static enum XML_Error doContent(XML_Parser parser, int startTagLevel,
const ENCODING *enc, const char *start,
const char *end, const char **endPtr,
XML_Bool haveMore);
static enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *,
const char **startPtr, const char *end,
const char **nextPtr, XML_Bool haveMore);
#ifdef XML_DTD
static enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *,
const char **startPtr, const char *end,
const char **nextPtr, XML_Bool haveMore);
#endif /* XML_DTD */
static void freeBindings(XML_Parser parser, BINDING *bindings);
static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *,
const char *s, TAG_NAME *tagNamePtr,
BINDING **bindingsPtr);
static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,
const ATTRIBUTE_ID *attId, const XML_Char *uri,
BINDING **bindingsPtr);
static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata,
XML_Bool isId, const XML_Char *dfltValue,
XML_Parser parser);
static enum XML_Error storeAttributeValue(XML_Parser parser, const ENCODING *,
XML_Bool isCdata, const char *,
const char *, STRING_POOL *);
static enum XML_Error appendAttributeValue(XML_Parser parser, const ENCODING *,
XML_Bool isCdata, const char *,
const char *, STRING_POOL *);
static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *);
static enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int reportComment(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static void reportDefault(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static const XML_Char *getContext(XML_Parser parser);
static XML_Bool setContext(XML_Parser parser, const XML_Char *context);
static void FASTCALL normalizePublicId(XML_Char *s);
static DTD *dtdCreate(const XML_Memory_Handling_Suite *ms);
/* do not call if m_parentParser != NULL */
static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
static void dtdDestroy(DTD *p, XML_Bool isDocEntity,
const XML_Memory_Handling_Suite *ms);
static int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
const XML_Memory_Handling_Suite *ms);
static int copyEntityTable(XML_Parser oldParser, HASH_TABLE *, STRING_POOL *,
const HASH_TABLE *);
static NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,
size_t createSize);
static void FASTCALL hashTableInit(HASH_TABLE *,
const XML_Memory_Handling_Suite *ms);
static void FASTCALL hashTableClear(HASH_TABLE *);
static void FASTCALL hashTableDestroy(HASH_TABLE *);
static void FASTCALL hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *);
static NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *);
static void FASTCALL poolInit(STRING_POOL *,
const XML_Memory_Handling_Suite *ms);
static void FASTCALL poolClear(STRING_POOL *);
static void FASTCALL poolDestroy(STRING_POOL *);
static XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
static const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,
const XML_Char *s);
static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,
int n);
static const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,
const XML_Char *s);
static int FASTCALL nextScaffoldPart(XML_Parser parser);
static XML_Content *build_model(XML_Parser parser);
static ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *copyString(const XML_Char *s,
const XML_Memory_Handling_Suite *memsuite);
static unsigned long generate_hash_secret_salt(XML_Parser parser);
static XML_Bool startParsing(XML_Parser parser);
static XML_Parser parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep, DTD *dtd);
static void parserInit(XML_Parser parser, const XML_Char *encodingName);
#define poolStart(pool) ((pool)->start)
#define poolEnd(pool) ((pool)->ptr)
#define poolLength(pool) ((pool)->ptr - (pool)->start)
#define poolChop(pool) ((void)--(pool->ptr))
#define poolLastChar(pool) (((pool)->ptr)[-1])
#define poolDiscard(pool) ((pool)->ptr = (pool)->start)
#define poolFinish(pool) ((pool)->start = (pool)->ptr)
#define poolAppendChar(pool, c) \
(((pool)->ptr == (pool)->end && ! poolGrow(pool)) \
? 0 \
: ((*((pool)->ptr)++ = c), 1))
struct XML_ParserStruct {
/* The first member must be m_userData so that the XML_GetUserData
macro works. */
void *m_userData;
void *m_handlerArg;
char *m_buffer;
const XML_Memory_Handling_Suite m_mem;
/* first character to be parsed */
const char *m_bufferPtr;
/* past last character to be parsed */
char *m_bufferEnd;
/* allocated end of m_buffer */
const char *m_bufferLim;
XML_Index m_parseEndByteIndex;
const char *m_parseEndPtr;
XML_Char *m_dataBuf;
XML_Char *m_dataBufEnd;
XML_StartElementHandler m_startElementHandler;
XML_EndElementHandler m_endElementHandler;
XML_CharacterDataHandler m_characterDataHandler;
XML_ProcessingInstructionHandler m_processingInstructionHandler;
XML_CommentHandler m_commentHandler;
XML_StartCdataSectionHandler m_startCdataSectionHandler;
XML_EndCdataSectionHandler m_endCdataSectionHandler;
XML_DefaultHandler m_defaultHandler;
XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
XML_NotationDeclHandler m_notationDeclHandler;
XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
XML_NotStandaloneHandler m_notStandaloneHandler;
XML_ExternalEntityRefHandler m_externalEntityRefHandler;
XML_Parser m_externalEntityRefHandlerArg;
XML_SkippedEntityHandler m_skippedEntityHandler;
XML_UnknownEncodingHandler m_unknownEncodingHandler;
XML_ElementDeclHandler m_elementDeclHandler;
XML_AttlistDeclHandler m_attlistDeclHandler;
XML_EntityDeclHandler m_entityDeclHandler;
XML_XmlDeclHandler m_xmlDeclHandler;
const ENCODING *m_encoding;
INIT_ENCODING m_initEncoding;
const ENCODING *m_internalEncoding;
const XML_Char *m_protocolEncodingName;
XML_Bool m_ns;
XML_Bool m_ns_triplets;
void *m_unknownEncodingMem;
void *m_unknownEncodingData;
void *m_unknownEncodingHandlerData;
void(XMLCALL *m_unknownEncodingRelease)(void *);
PROLOG_STATE m_prologState;
Processor *m_processor;
enum XML_Error m_errorCode;
const char *m_eventPtr;
const char *m_eventEndPtr;
const char *m_positionPtr;
OPEN_INTERNAL_ENTITY *m_openInternalEntities;
OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
XML_Bool m_defaultExpandInternalEntities;
int m_tagLevel;
ENTITY *m_declEntity;
const XML_Char *m_doctypeName;
const XML_Char *m_doctypeSysid;
const XML_Char *m_doctypePubid;
const XML_Char *m_declAttributeType;
const XML_Char *m_declNotationName;
const XML_Char *m_declNotationPublicId;
ELEMENT_TYPE *m_declElementType;
ATTRIBUTE_ID *m_declAttributeId;
XML_Bool m_declAttributeIsCdata;
XML_Bool m_declAttributeIsId;
DTD *m_dtd;
const XML_Char *m_curBase;
TAG *m_tagStack;
TAG *m_freeTagList;
BINDING *m_inheritedBindings;
BINDING *m_freeBindingList;
int m_attsSize;
int m_nSpecifiedAtts;
int m_idAttIndex;
ATTRIBUTE *m_atts;
NS_ATT *m_nsAtts;
unsigned long m_nsAttsVersion;
unsigned char m_nsAttsPower;
#ifdef XML_ATTR_INFO
XML_AttrInfo *m_attInfo;
#endif
POSITION m_position;
STRING_POOL m_tempPool;
STRING_POOL m_temp2Pool;
char *m_groupConnector;
unsigned int m_groupSize;
XML_Char m_namespaceSeparator;
XML_Parser m_parentParser;
XML_ParsingStatus m_parsingStatus;
#ifdef XML_DTD
XML_Bool m_isParamEntity;
XML_Bool m_useForeignDTD;
enum XML_ParamEntityParsing m_paramEntityParsing;
#endif
unsigned long m_hash_secret_salt;
};
#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))
#define FREE(parser, p) (parser->m_mem.free_fcn((p)))
XML_Parser XMLCALL
XML_ParserCreate(const XML_Char *encodingName) {
return XML_ParserCreate_MM(encodingName, NULL, NULL);
}
XML_Parser XMLCALL
XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {
XML_Char tmp[2];
*tmp = nsSep;
return XML_ParserCreate_MM(encodingName, NULL, tmp);
}
static const XML_Char implicitContext[]
= {ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h,
ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD,
ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r,
ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,
ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8,
ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,
ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e,
'\0'};
/* To avoid warnings about unused functions: */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
# if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
/* Obtain entropy on Linux 3.17+ */
static int
writeRandomBytes_getrandom_nonblock(void *target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const unsigned int getrandomFlags = GRND_NONBLOCK;
do {
void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const int bytesWrittenMore =
# if defined(HAVE_GETRANDOM)
getrandom(currentTarget, bytesToWrite, getrandomFlags);
# else
syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
# endif
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
return success;
}
# endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
# if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
/* Extract entropy from /dev/urandom */
static int
writeRandomBytes_dev_urandom(void *target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
return 0;
}
do {
void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
close(fd);
return success;
}
# endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
static void
writeRandomBytes_arc4random(void *target, size_t count) {
size_t bytesWrittenTotal = 0;
while (bytesWrittenTotal < count) {
const uint32_t random32 = arc4random();
size_t i = 0;
for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
i++, bytesWrittenTotal++) {
const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
((uint8_t *)target)[bytesWrittenTotal] = random8;
}
}
}
#endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
#ifdef _WIN32
/* Obtain entropy on Windows using the rand_s() function which
* generates cryptographically secure random numbers. Internally it
* uses RtlGenRandom API which is present in Windows XP and later.
*/
static int
writeRandomBytes_rand_s(void *target, size_t count) {
size_t bytesWrittenTotal = 0;
while (bytesWrittenTotal < count) {
unsigned int random32 = 0;
size_t i = 0;
if (rand_s(&random32))
return 0; /* failure */
for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
i++, bytesWrittenTotal++) {
const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
((uint8_t *)target)[bytesWrittenTotal] = random8;
}
}
return 1; /* success */
}
#endif /* _WIN32 */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
static unsigned long
gather_time_entropy(void) {
# ifdef _WIN32
FILETIME ft;
GetSystemTimeAsFileTime(&ft); /* never fails */
return ft.dwHighDateTime ^ ft.dwLowDateTime;
# else
struct timeval tv;
int gettimeofday_res;
gettimeofday_res = gettimeofday(&tv, NULL);
# if defined(NDEBUG)
(void)gettimeofday_res;
# else
assert(gettimeofday_res == 0);
# endif /* defined(NDEBUG) */
/* Microseconds time is <20 bits entropy */
return tv.tv_usec;
# endif
}
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
static unsigned long
ENTROPY_DEBUG(const char *label, unsigned long entropy) {
const char *const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) {
fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n", label,
(int)sizeof(entropy) * 2, entropy, (unsigned long)sizeof(entropy));
}
return entropy;
}
static unsigned long
generate_hash_secret_salt(XML_Parser parser) {
unsigned long entropy;
(void)parser;
/* "Failproof" high quality providers: */
#if defined(HAVE_ARC4RANDOM_BUF)
arc4random_buf(&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random_buf", entropy);
#elif defined(HAVE_ARC4RANDOM)
writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random", entropy);
#else
/* Try high quality providers first .. */
# ifdef _WIN32
if (writeRandomBytes_rand_s((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("rand_s", entropy);
}
# elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("getrandom", entropy);
}
# endif
# if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("/dev/urandom", entropy);
}
# endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
/* .. and self-made low quality for backup: */
/* Process ID is 0 bits entropy if attacker has local access */
entropy = gather_time_entropy() ^ getpid();
/* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
if (sizeof(unsigned long) == 4) {
return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
} else {
return ENTROPY_DEBUG("fallback(8)",
entropy * (unsigned long)2305843009213693951ULL);
}
#endif
}
static unsigned long
get_hash_secret_salt(XML_Parser parser) {
if (parser->m_parentParser != NULL)
return get_hash_secret_salt(parser->m_parentParser);
return parser->m_hash_secret_salt;
}
static XML_Bool /* only valid for root parser */
startParsing(XML_Parser parser) {
/* hash functions must be initialized before setContext() is called */
if (parser->m_hash_secret_salt == 0)
parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
if (parser->m_ns) {
/* implicit context only set for root parser, since child
parsers (i.e. external entity parsers) will inherit it
*/
return setContext(parser, implicitContext);
}
return XML_TRUE;
}
XML_Parser XMLCALL
XML_ParserCreate_MM(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep) {
return parserCreate(encodingName, memsuite, nameSep, NULL);
}
static XML_Parser
parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,
DTD *dtd) {
XML_Parser parser;
if (memsuite) {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = memsuite->malloc_fcn;
mtemp->realloc_fcn = memsuite->realloc_fcn;
mtemp->free_fcn = memsuite->free_fcn;
}
} else {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = malloc;
mtemp->realloc_fcn = realloc;
mtemp->free_fcn = free;
}
}
if (! parser)
return parser;
parser->m_buffer = NULL;
parser->m_bufferLim = NULL;
parser->m_attsSize = INIT_ATTS_SIZE;
parser->m_atts
= (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
if (parser->m_atts == NULL) {
FREE(parser, parser);
return NULL;
}
#ifdef XML_ATTR_INFO
parser->m_attInfo = (XML_AttrInfo *)MALLOC(
parser, parser->m_attsSize * sizeof(XML_AttrInfo));
if (parser->m_attInfo == NULL) {
FREE(parser, parser->m_atts);
FREE(parser, parser);
return NULL;
}
#endif
parser->m_dataBuf
= (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
if (parser->m_dataBuf == NULL) {
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
if (dtd)
parser->m_dtd = dtd;
else {
parser->m_dtd = dtdCreate(&parser->m_mem);
if (parser->m_dtd == NULL) {
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
}
parser->m_freeBindingList = NULL;
parser->m_freeTagList = NULL;
parser->m_freeInternalEntities = NULL;
parser->m_groupSize = 0;
parser->m_groupConnector = NULL;
parser->m_unknownEncodingHandler = NULL;
parser->m_unknownEncodingHandlerData = NULL;
parser->m_namespaceSeparator = ASCII_EXCL;
parser->m_ns = XML_FALSE;
parser->m_ns_triplets = XML_FALSE;
parser->m_nsAtts = NULL;
parser->m_nsAttsVersion = 0;
parser->m_nsAttsPower = 0;
parser->m_protocolEncodingName = NULL;
poolInit(&parser->m_tempPool, &(parser->m_mem));
poolInit(&parser->m_temp2Pool, &(parser->m_mem));
parserInit(parser, encodingName);
if (encodingName && ! parser->m_protocolEncodingName) {
XML_ParserFree(parser);
return NULL;
}
if (nameSep) {
parser->m_ns = XML_TRUE;
parser->m_internalEncoding = XmlGetInternalEncodingNS();
parser->m_namespaceSeparator = *nameSep;
} else {
parser->m_internalEncoding = XmlGetInternalEncoding();
}
return parser;
}
static void
parserInit(XML_Parser parser, const XML_Char *encodingName) {
parser->m_processor = prologInitProcessor;
XmlPrologStateInit(&parser->m_prologState);
if (encodingName != NULL) {
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
}
parser->m_curBase = NULL;
XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
parser->m_userData = NULL;
parser->m_handlerArg = NULL;
parser->m_startElementHandler = NULL;
parser->m_endElementHandler = NULL;
parser->m_characterDataHandler = NULL;
parser->m_processingInstructionHandler = NULL;
parser->m_commentHandler = NULL;
parser->m_startCdataSectionHandler = NULL;
parser->m_endCdataSectionHandler = NULL;
parser->m_defaultHandler = NULL;
parser->m_startDoctypeDeclHandler = NULL;
parser->m_endDoctypeDeclHandler = NULL;
parser->m_unparsedEntityDeclHandler = NULL;
parser->m_notationDeclHandler = NULL;
parser->m_startNamespaceDeclHandler = NULL;
parser->m_endNamespaceDeclHandler = NULL;
parser->m_notStandaloneHandler = NULL;
parser->m_externalEntityRefHandler = NULL;
parser->m_externalEntityRefHandlerArg = parser;
parser->m_skippedEntityHandler = NULL;
parser->m_elementDeclHandler = NULL;
parser->m_attlistDeclHandler = NULL;
parser->m_entityDeclHandler = NULL;
parser->m_xmlDeclHandler = NULL;
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer;
parser->m_parseEndByteIndex = 0;
parser->m_parseEndPtr = NULL;
parser->m_declElementType = NULL;
parser->m_declAttributeId = NULL;
parser->m_declEntity = NULL;
parser->m_doctypeName = NULL;
parser->m_doctypeSysid = NULL;
parser->m_doctypePubid = NULL;
parser->m_declAttributeType = NULL;
parser->m_declNotationName = NULL;
parser->m_declNotationPublicId = NULL;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeIsId = XML_FALSE;
memset(&parser->m_position, 0, sizeof(POSITION));
parser->m_errorCode = XML_ERROR_NONE;
parser->m_eventPtr = NULL;
parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
parser->m_openInternalEntities = NULL;
parser->m_defaultExpandInternalEntities = XML_TRUE;
parser->m_tagLevel = 0;
parser->m_tagStack = NULL;
parser->m_inheritedBindings = NULL;
parser->m_nSpecifiedAtts = 0;
parser->m_unknownEncodingMem = NULL;
parser->m_unknownEncodingRelease = NULL;
parser->m_unknownEncodingData = NULL;
parser->m_parentParser = NULL;
parser->m_parsingStatus.parsing = XML_INITIALIZED;
#ifdef XML_DTD
parser->m_isParamEntity = XML_FALSE;
parser->m_useForeignDTD = XML_FALSE;
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif
parser->m_hash_secret_salt = 0;
}
/* moves list of bindings to m_freeBindingList */
static void FASTCALL
moveToFreeBindingList(XML_Parser parser, BINDING *bindings) {
while (bindings) {
BINDING *b = bindings;
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
}
}
XML_Bool XMLCALL
XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
TAG *tStk;
OPEN_INTERNAL_ENTITY *openEntityList;
if (parser == NULL)
return XML_FALSE;
if (parser->m_parentParser)
return XML_FALSE;
/* move m_tagStack to m_freeTagList */
tStk = parser->m_tagStack;
while (tStk) {
TAG *tag = tStk;
tStk = tStk->parent;
tag->parent = parser->m_freeTagList;
moveToFreeBindingList(parser, tag->bindings);
tag->bindings = NULL;
parser->m_freeTagList = tag;
}
/* move m_openInternalEntities to m_freeInternalEntities */
openEntityList = parser->m_openInternalEntities;
while (openEntityList) {
OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
openEntityList = openEntity->next;
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
moveToFreeBindingList(parser, parser->m_inheritedBindings);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
poolClear(&parser->m_tempPool);
poolClear(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
parser->m_protocolEncodingName = NULL;
parserInit(parser, encodingName);
dtdReset(parser->m_dtd, &parser->m_mem);
return XML_TRUE;
}
enum XML_Status XMLCALL
XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {
if (parser == NULL)
return XML_STATUS_ERROR;
/* Block after XML_Parse()/XML_ParseBuffer() has been called.
XXX There's no way for the caller to determine which of the
XXX possible error cases caused the XML_STATUS_ERROR return.
*/
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_STATUS_ERROR;
/* Get rid of any previous encoding name */
FREE(parser, (void *)parser->m_protocolEncodingName);
if (encodingName == NULL)
/* No new encoding name */
parser->m_protocolEncodingName = NULL;
else {
/* Copy the new encoding name into allocated memory */
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
if (! parser->m_protocolEncodingName)
return XML_STATUS_ERROR;
}
return XML_STATUS_OK;
}
XML_Parser XMLCALL
XML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,
const XML_Char *encodingName) {
XML_Parser parser = oldParser;
DTD *newDtd = NULL;
DTD *oldDtd;
XML_StartElementHandler oldStartElementHandler;
XML_EndElementHandler oldEndElementHandler;
XML_CharacterDataHandler oldCharacterDataHandler;
XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
XML_CommentHandler oldCommentHandler;
XML_StartCdataSectionHandler oldStartCdataSectionHandler;
XML_EndCdataSectionHandler oldEndCdataSectionHandler;
XML_DefaultHandler oldDefaultHandler;
XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
XML_NotationDeclHandler oldNotationDeclHandler;
XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
XML_NotStandaloneHandler oldNotStandaloneHandler;
XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
XML_SkippedEntityHandler oldSkippedEntityHandler;
XML_UnknownEncodingHandler oldUnknownEncodingHandler;
XML_ElementDeclHandler oldElementDeclHandler;
XML_AttlistDeclHandler oldAttlistDeclHandler;
XML_EntityDeclHandler oldEntityDeclHandler;
XML_XmlDeclHandler oldXmlDeclHandler;
ELEMENT_TYPE *oldDeclElementType;
void *oldUserData;
void *oldHandlerArg;
XML_Bool oldDefaultExpandInternalEntities;
XML_Parser oldExternalEntityRefHandlerArg;
#ifdef XML_DTD
enum XML_ParamEntityParsing oldParamEntityParsing;
int oldInEntityValue;
#endif
XML_Bool oldns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
unsigned long oldhash_secret_salt;
/* Validate the oldParser parameter before we pull everything out of it */
if (oldParser == NULL)
return NULL;
/* Stash the original parser contents on the stack */
oldDtd = parser->m_dtd;
oldStartElementHandler = parser->m_startElementHandler;
oldEndElementHandler = parser->m_endElementHandler;
oldCharacterDataHandler = parser->m_characterDataHandler;
oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
oldCommentHandler = parser->m_commentHandler;
oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
oldDefaultHandler = parser->m_defaultHandler;
oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
oldNotationDeclHandler = parser->m_notationDeclHandler;
oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
oldNotStandaloneHandler = parser->m_notStandaloneHandler;
oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
oldSkippedEntityHandler = parser->m_skippedEntityHandler;
oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
oldElementDeclHandler = parser->m_elementDeclHandler;
oldAttlistDeclHandler = parser->m_attlistDeclHandler;
oldEntityDeclHandler = parser->m_entityDeclHandler;
oldXmlDeclHandler = parser->m_xmlDeclHandler;
oldDeclElementType = parser->m_declElementType;
oldUserData = parser->m_userData;
oldHandlerArg = parser->m_handlerArg;
oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
#ifdef XML_DTD
oldParamEntityParsing = parser->m_paramEntityParsing;
oldInEntityValue = parser->m_prologState.inEntityValue;
#endif
oldns_triplets = parser->m_ns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
oldhash_secret_salt = parser->m_hash_secret_salt;
#ifdef XML_DTD
if (! context)
newDtd = oldDtd;
#endif /* XML_DTD */
/* Note that the magical uses of the pre-processor to make field
access look more like C++ require that `parser' be overwritten
here. This makes this function more painful to follow than it
would be otherwise.
*/
if (parser->m_ns) {
XML_Char tmp[2];
*tmp = parser->m_namespaceSeparator;
parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
} else {
parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
}
if (! parser)
return NULL;
parser->m_startElementHandler = oldStartElementHandler;
parser->m_endElementHandler = oldEndElementHandler;
parser->m_characterDataHandler = oldCharacterDataHandler;
parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
parser->m_commentHandler = oldCommentHandler;
parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
parser->m_defaultHandler = oldDefaultHandler;
parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
parser->m_notationDeclHandler = oldNotationDeclHandler;
parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
parser->m_notStandaloneHandler = oldNotStandaloneHandler;
parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
parser->m_skippedEntityHandler = oldSkippedEntityHandler;
parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
parser->m_elementDeclHandler = oldElementDeclHandler;
parser->m_attlistDeclHandler = oldAttlistDeclHandler;
parser->m_entityDeclHandler = oldEntityDeclHandler;
parser->m_xmlDeclHandler = oldXmlDeclHandler;
parser->m_declElementType = oldDeclElementType;
parser->m_userData = oldUserData;
if (oldUserData == oldHandlerArg)
parser->m_handlerArg = parser->m_userData;
else
parser->m_handlerArg = parser;
if (oldExternalEntityRefHandlerArg != oldParser)
parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
parser->m_ns_triplets = oldns_triplets;
parser->m_hash_secret_salt = oldhash_secret_salt;
parser->m_parentParser = oldParser;
#ifdef XML_DTD
parser->m_paramEntityParsing = oldParamEntityParsing;
parser->m_prologState.inEntityValue = oldInEntityValue;
if (context) {
#endif /* XML_DTD */
if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
|| ! setContext(parser, context)) {
XML_ParserFree(parser);
return NULL;
}
parser->m_processor = externalEntityInitProcessor;
#ifdef XML_DTD
} else {
/* The DTD instance referenced by parser->m_dtd is shared between the
document's root parser and external PE parsers, therefore one does not
need to call setContext. In addition, one also *must* not call
setContext, because this would overwrite existing prefix->binding
pointers in parser->m_dtd with ones that get destroyed with the external
PE parser. This would leave those prefixes with dangling pointers.
*/
parser->m_isParamEntity = XML_TRUE;
XmlPrologStateInitExternalEntity(&parser->m_prologState);
parser->m_processor = externalParEntInitProcessor;
}
#endif /* XML_DTD */
return parser;
}
static void FASTCALL
destroyBindings(BINDING *bindings, XML_Parser parser) {
for (;;) {
BINDING *b = bindings;
if (! b)
break;
bindings = b->nextTagBinding;
FREE(parser, b->uri);
FREE(parser, b);
}
}
void XMLCALL
XML_ParserFree(XML_Parser parser) {
TAG *tagList;
OPEN_INTERNAL_ENTITY *entityList;
if (parser == NULL)
return;
/* free m_tagStack and m_freeTagList */
tagList = parser->m_tagStack;
for (;;) {
TAG *p;
if (tagList == NULL) {
if (parser->m_freeTagList == NULL)
break;
tagList = parser->m_freeTagList;
parser->m_freeTagList = NULL;
}
p = tagList;
tagList = tagList->parent;
FREE(parser, p->buf);
destroyBindings(p->bindings, parser);
FREE(parser, p);
}
/* free m_openInternalEntities and m_freeInternalEntities */
entityList = parser->m_openInternalEntities;
for (;;) {
OPEN_INTERNAL_ENTITY *openEntity;
if (entityList == NULL) {
if (parser->m_freeInternalEntities == NULL)
break;
entityList = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = NULL;
}
openEntity = entityList;
entityList = entityList->next;
FREE(parser, openEntity);
}
destroyBindings(parser->m_freeBindingList, parser);
destroyBindings(parser->m_inheritedBindings, parser);
poolDestroy(&parser->m_tempPool);
poolDestroy(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
#ifdef XML_DTD
/* external parameter entity parsers share the DTD structure
parser->m_dtd with the root parser, so we must not destroy it
*/
if (! parser->m_isParamEntity && parser->m_dtd)
#else
if (parser->m_dtd)
#endif /* XML_DTD */
dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser,
&parser->m_mem);
FREE(parser, (void *)parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, (void *)parser->m_attInfo);
#endif
FREE(parser, parser->m_groupConnector);
FREE(parser, parser->m_buffer);
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_nsAtts);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
FREE(parser, parser);
}
void XMLCALL
XML_UseParserAsHandlerArg(XML_Parser parser) {
if (parser != NULL)
parser->m_handlerArg = parser;
}
enum XML_Error XMLCALL
XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
#ifdef XML_DTD
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
parser->m_useForeignDTD = useDTD;
return XML_ERROR_NONE;
#else
return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
#endif
}
void XMLCALL
XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {
if (parser == NULL)
return;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return;
parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
}
void XMLCALL
XML_SetUserData(XML_Parser parser, void *p) {
if (parser == NULL)
return;
if (parser->m_handlerArg == parser->m_userData)
parser->m_handlerArg = parser->m_userData = p;
else
parser->m_userData = p;
}
enum XML_Status XMLCALL
XML_SetBase(XML_Parser parser, const XML_Char *p) {
if (parser == NULL)
return XML_STATUS_ERROR;
if (p) {
p = poolCopyString(&parser->m_dtd->pool, p);
if (! p)
return XML_STATUS_ERROR;
parser->m_curBase = p;
} else
parser->m_curBase = NULL;
return XML_STATUS_OK;
}
const XML_Char *XMLCALL
XML_GetBase(XML_Parser parser) {
if (parser == NULL)
return NULL;
return parser->m_curBase;
}
int XMLCALL
XML_GetSpecifiedAttributeCount(XML_Parser parser) {
if (parser == NULL)
return -1;
return parser->m_nSpecifiedAtts;
}
int XMLCALL
XML_GetIdAttributeIndex(XML_Parser parser) {
if (parser == NULL)
return -1;
return parser->m_idAttIndex;
}
#ifdef XML_ATTR_INFO
const XML_AttrInfo *XMLCALL
XML_GetAttributeInfo(XML_Parser parser) {
if (parser == NULL)
return NULL;
return parser->m_attInfo;
}
#endif
void XMLCALL
XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
XML_EndElementHandler end) {
if (parser == NULL)
return;
parser->m_startElementHandler = start;
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {
if (parser != NULL)
parser->m_startElementHandler = start;
}
void XMLCALL
XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {
if (parser != NULL)
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetCharacterDataHandler(XML_Parser parser,
XML_CharacterDataHandler handler) {
if (parser != NULL)
parser->m_characterDataHandler = handler;
}
void XMLCALL
XML_SetProcessingInstructionHandler(XML_Parser parser,
XML_ProcessingInstructionHandler handler) {
if (parser != NULL)
parser->m_processingInstructionHandler = handler;
}
void XMLCALL
XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {
if (parser != NULL)
parser->m_commentHandler = handler;
}
void XMLCALL
XML_SetCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start,
XML_EndCdataSectionHandler end) {
if (parser == NULL)
return;
parser->m_startCdataSectionHandler = start;
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetStartCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start) {
if (parser != NULL)
parser->m_startCdataSectionHandler = start;
}
void XMLCALL
XML_SetEndCdataSectionHandler(XML_Parser parser,
XML_EndCdataSectionHandler end) {
if (parser != NULL)
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_FALSE;
}
void XMLCALL
XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_TRUE;
}
void XMLCALL
XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
XML_EndDoctypeDeclHandler end) {
if (parser == NULL)
return;
parser->m_startDoctypeDeclHandler = start;
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetStartDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start) {
if (parser != NULL)
parser->m_startDoctypeDeclHandler = start;
}
void XMLCALL
XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {
if (parser != NULL)
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
XML_UnparsedEntityDeclHandler handler) {
if (parser != NULL)
parser->m_unparsedEntityDeclHandler = handler;
}
void XMLCALL
XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {
if (parser != NULL)
parser->m_notationDeclHandler = handler;
}
void XMLCALL
XML_SetNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start,
XML_EndNamespaceDeclHandler end) {
if (parser == NULL)
return;
parser->m_startNamespaceDeclHandler = start;
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetStartNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start) {
if (parser != NULL)
parser->m_startNamespaceDeclHandler = start;
}
void XMLCALL
XML_SetEndNamespaceDeclHandler(XML_Parser parser,
XML_EndNamespaceDeclHandler end) {
if (parser != NULL)
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetNotStandaloneHandler(XML_Parser parser,
XML_NotStandaloneHandler handler) {
if (parser != NULL)
parser->m_notStandaloneHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandler(XML_Parser parser,
XML_ExternalEntityRefHandler handler) {
if (parser != NULL)
parser->m_externalEntityRefHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {
if (parser == NULL)
return;
if (arg)
parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
else
parser->m_externalEntityRefHandlerArg = parser;
}
void XMLCALL
XML_SetSkippedEntityHandler(XML_Parser parser,
XML_SkippedEntityHandler handler) {
if (parser != NULL)
parser->m_skippedEntityHandler = handler;
}
void XMLCALL
XML_SetUnknownEncodingHandler(XML_Parser parser,
XML_UnknownEncodingHandler handler, void *data) {
if (parser == NULL)
return;
parser->m_unknownEncodingHandler = handler;
parser->m_unknownEncodingHandlerData = data;
}
void XMLCALL
XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {
if (parser != NULL)
parser->m_elementDeclHandler = eldecl;
}
void XMLCALL
XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {
if (parser != NULL)
parser->m_attlistDeclHandler = attdecl;
}
void XMLCALL
XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {
if (parser != NULL)
parser->m_entityDeclHandler = handler;
}
void XMLCALL
XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {
if (parser != NULL)
parser->m_xmlDeclHandler = handler;
}
int XMLCALL
XML_SetParamEntityParsing(XML_Parser parser,
enum XML_ParamEntityParsing peParsing) {
if (parser == NULL)
return 0;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
#ifdef XML_DTD
parser->m_paramEntityParsing = peParsing;
return 1;
#else
return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
#endif
}
int XMLCALL
XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {
if (parser == NULL)
return 0;
if (parser->m_parentParser)
return XML_SetHashSalt(parser->m_parentParser, hash_salt);
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING
|| parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
parser->m_hash_secret_salt = hash_salt;
return 1;
}
enum XML_Status XMLCALL
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {
if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
if (parser != NULL)
parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
return XML_STATUS_ERROR;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && ! startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
if (len == 0) {
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
if (! isFinal)
return XML_STATUS_OK;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
/* If data are left over from last buffer, and we now know that these
data are the final chunk of input, then we have to check them again
to detect errors based on that fact.
*/
parser->m_errorCode
= parser->m_processor(parser, parser->m_bufferPtr,
parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode == XML_ERROR_NONE) {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
/* It is hard to be certain, but it seems that this case
* cannot occur. This code is cleaning up a previous parse
* with no new data (since len == 0). Changing the parsing
* state requires getting to execute a handler function, and
* there doesn't seem to be an opportunity for that while in
* this circumstance.
*
* Given the uncertainty, we retain the code but exclude it
* from coverage tests.
*
* LCOV_EXCL_START
*/
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return XML_STATUS_SUSPENDED;
/* LCOV_EXCL_STOP */
case XML_INITIALIZED:
case XML_PARSING:
parser->m_parsingStatus.parsing = XML_FINISHED;
/* fall through */
default:
return XML_STATUS_OK;
}
}
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
#ifndef XML_CONTEXT_BYTES
else if (parser->m_bufferPtr == parser->m_bufferEnd) {
const char *end;
int nLeftOver;
enum XML_Status result;
/* Detect overflow (a+b > MAX <==> b > MAX-a) */
if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_parseEndByteIndex += len;
parser->m_positionPtr = s;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode
= parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
} else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return XML_STATUS_OK;
}
/* fall through */
default:
result = XML_STATUS_OK;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,
&parser->m_position);
nLeftOver = s + len - end;
if (nLeftOver) {
if (parser->m_buffer == NULL
|| nLeftOver > parser->m_bufferLim - parser->m_buffer) {
/* avoid _signed_ integer overflow */
char *temp = NULL;
const int bytesToAllocate = (int)((unsigned)len * 2U);
if (bytesToAllocate > 0) {
temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate);
}
if (temp == NULL) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_buffer = temp;
parser->m_bufferLim = parser->m_buffer + bytesToAllocate;
}
memcpy(parser->m_buffer, end, nLeftOver);
}
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer + nLeftOver;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_eventPtr = parser->m_bufferPtr;
parser->m_eventEndPtr = parser->m_bufferPtr;
return result;
}
#endif /* not defined XML_CONTEXT_BYTES */
else {
void *buff = XML_GetBuffer(parser, len);
if (buff == NULL)
return XML_STATUS_ERROR;
else {
memcpy(buff, s, len);
return XML_ParseBuffer(parser, len, isFinal);
}
}
}
enum XML_Status XMLCALL
XML_ParseBuffer(XML_Parser parser, int len, int isFinal) {
const char *start;
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && ! startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
start = parser->m_bufferPtr;
parser->m_positionPtr = start;
parser->m_bufferEnd += len;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_parseEndByteIndex += len;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode = parser->m_processor(
parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
} else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default:; /* should not happen */
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void *XMLCALL
XML_GetBuffer(XML_Parser parser, int len) {
if (parser == NULL)
return NULL;
if (len < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return NULL;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return NULL;
default:;
}
if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) {
#ifdef XML_CONTEXT_BYTES
int keep;
#endif /* defined XML_CONTEXT_BYTES */
/* Do not invoke signed arithmetic overflow: */
int neededSize = (int)((unsigned)len
+ (unsigned)EXPAT_SAFE_PTR_DIFF(
parser->m_bufferEnd, parser->m_bufferPtr));
if (neededSize < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
#ifdef XML_CONTEXT_BYTES
keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
neededSize += keep;
#endif /* defined XML_CONTEXT_BYTES */
if (neededSize
<= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
#ifdef XML_CONTEXT_BYTES
if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
int offset
= (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)
- keep;
/* The buffer pointers cannot be NULL here; we have at least some bytes
* in the buffer */
memmove(parser->m_buffer, &parser->m_buffer[offset],
parser->m_bufferEnd - parser->m_bufferPtr + keep);
parser->m_bufferEnd -= offset;
parser->m_bufferPtr -= offset;
}
#else
if (parser->m_buffer && parser->m_bufferPtr) {
memmove(parser->m_buffer, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
parser->m_bufferEnd
= parser->m_buffer
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
parser->m_bufferPtr = parser->m_buffer;
}
#endif /* not defined XML_CONTEXT_BYTES */
} else {
char *newBuf;
int bufferSize
= (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
if (bufferSize == 0)
bufferSize = INIT_BUFFER_SIZE;
do {
/* Do not invoke signed arithmetic overflow: */
bufferSize = (int)(2U * (unsigned)bufferSize);
} while (bufferSize < neededSize && bufferSize > 0);
if (bufferSize <= 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
newBuf = (char *)MALLOC(parser, bufferSize);
if (newBuf == 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
parser->m_bufferLim = newBuf + bufferSize;
#ifdef XML_CONTEXT_BYTES
if (parser->m_bufferPtr) {
memcpy(newBuf, &parser->m_bufferPtr[-keep],
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
+ keep);
FREE(parser, parser->m_buffer);
parser->m_buffer = newBuf;
parser->m_bufferEnd
= parser->m_buffer
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
+ keep;
parser->m_bufferPtr = parser->m_buffer + keep;
} else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
parser->m_bufferPtr = parser->m_buffer = newBuf;
}
#else
if (parser->m_bufferPtr) {
memcpy(newBuf, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
FREE(parser, parser->m_buffer);
parser->m_bufferEnd
= newBuf
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
} else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
}
parser->m_bufferPtr = parser->m_buffer = newBuf;
#endif /* not defined XML_CONTEXT_BYTES */
}
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
}
return parser->m_bufferEnd;
}
enum XML_Status XMLCALL
XML_StopParser(XML_Parser parser, XML_Bool resumable) {
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
if (resumable) {
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_FINISHED;
break;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
default:
if (resumable) {
#ifdef XML_DTD
if (parser->m_isParamEntity) {
parser->m_errorCode = XML_ERROR_SUSPEND_PE;
return XML_STATUS_ERROR;
}
#endif
parser->m_parsingStatus.parsing = XML_SUSPENDED;
} else
parser->m_parsingStatus.parsing = XML_FINISHED;
}
return XML_STATUS_OK;
}
enum XML_Status XMLCALL
XML_ResumeParser(XML_Parser parser) {
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_PARSING;
parser->m_errorCode = parser->m_processor(
parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
} else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (parser->m_parsingStatus.finalBuffer) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default:;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void XMLCALL
XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {
if (parser == NULL)
return;
assert(status != NULL);
*status = parser->m_parsingStatus;
}
enum XML_Error XMLCALL
XML_GetErrorCode(XML_Parser parser) {
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
return parser->m_errorCode;
}
XML_Index XMLCALL
XML_GetCurrentByteIndex(XML_Parser parser) {
if (parser == NULL)
return -1;
if (parser->m_eventPtr)
return (XML_Index)(parser->m_parseEndByteIndex
- (parser->m_parseEndPtr - parser->m_eventPtr));
return -1;
}
int XMLCALL
XML_GetCurrentByteCount(XML_Parser parser) {
if (parser == NULL)
return 0;
if (parser->m_eventEndPtr && parser->m_eventPtr)
return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
return 0;
}
const char *XMLCALL
XML_GetInputContext(XML_Parser parser, int *offset, int *size) {
#ifdef XML_CONTEXT_BYTES
if (parser == NULL)
return NULL;
if (parser->m_eventPtr && parser->m_buffer) {
if (offset != NULL)
*offset = (int)(parser->m_eventPtr - parser->m_buffer);
if (size != NULL)
*size = (int)(parser->m_bufferEnd - parser->m_buffer);
return parser->m_buffer;
}
#else
(void)parser;
(void)offset;
(void)size;
#endif /* defined XML_CONTEXT_BYTES */
return (char *)0;
}
XML_Size XMLCALL
XML_GetCurrentLineNumber(XML_Parser parser) {
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.lineNumber + 1;
}
XML_Size XMLCALL
XML_GetCurrentColumnNumber(XML_Parser parser) {
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.columnNumber;
}
void XMLCALL
XML_FreeContentModel(XML_Parser parser, XML_Content *model) {
if (parser != NULL)
FREE(parser, model);
}
void *XMLCALL
XML_MemMalloc(XML_Parser parser, size_t size) {
if (parser == NULL)
return NULL;
return MALLOC(parser, size);
}
void *XMLCALL
XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {
if (parser == NULL)
return NULL;
return REALLOC(parser, ptr, size);
}
void XMLCALL
XML_MemFree(XML_Parser parser, void *ptr) {
if (parser != NULL)
FREE(parser, ptr);
}
void XMLCALL
XML_DefaultCurrent(XML_Parser parser) {
if (parser == NULL)
return;
if (parser->m_defaultHandler) {
if (parser->m_openInternalEntities)
reportDefault(parser, parser->m_internalEncoding,
parser->m_openInternalEntities->internalEventPtr,
parser->m_openInternalEntities->internalEventEndPtr);
else
reportDefault(parser, parser->m_encoding, parser->m_eventPtr,
parser->m_eventEndPtr);
}
}
const XML_LChar *XMLCALL
XML_ErrorString(enum XML_Error code) {
switch (code) {
case XML_ERROR_NONE:
return NULL;
case XML_ERROR_NO_MEMORY:
return XML_L("out of memory");
case XML_ERROR_SYNTAX:
return XML_L("syntax error");
case XML_ERROR_NO_ELEMENTS:
return XML_L("no element found");
case XML_ERROR_INVALID_TOKEN:
return XML_L("not well-formed (invalid token)");
case XML_ERROR_UNCLOSED_TOKEN:
return XML_L("unclosed token");
case XML_ERROR_PARTIAL_CHAR:
return XML_L("partial character");
case XML_ERROR_TAG_MISMATCH:
return XML_L("mismatched tag");
case XML_ERROR_DUPLICATE_ATTRIBUTE:
return XML_L("duplicate attribute");
case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
return XML_L("junk after document element");
case XML_ERROR_PARAM_ENTITY_REF:
return XML_L("illegal parameter entity reference");
case XML_ERROR_UNDEFINED_ENTITY:
return XML_L("undefined entity");
case XML_ERROR_RECURSIVE_ENTITY_REF:
return XML_L("recursive entity reference");
case XML_ERROR_ASYNC_ENTITY:
return XML_L("asynchronous entity");
case XML_ERROR_BAD_CHAR_REF:
return XML_L("reference to invalid character number");
case XML_ERROR_BINARY_ENTITY_REF:
return XML_L("reference to binary entity");
case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
return XML_L("reference to external entity in attribute");
case XML_ERROR_MISPLACED_XML_PI:
return XML_L("XML or text declaration not at start of entity");
case XML_ERROR_UNKNOWN_ENCODING:
return XML_L("unknown encoding");
case XML_ERROR_INCORRECT_ENCODING:
return XML_L("encoding specified in XML declaration is incorrect");
case XML_ERROR_UNCLOSED_CDATA_SECTION:
return XML_L("unclosed CDATA section");
case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
return XML_L("error in processing external entity reference");
case XML_ERROR_NOT_STANDALONE:
return XML_L("document is not standalone");
case XML_ERROR_UNEXPECTED_STATE:
return XML_L("unexpected parser state - please send a bug report");
case XML_ERROR_ENTITY_DECLARED_IN_PE:
return XML_L("entity declared in parameter entity");
case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
return XML_L("requested feature requires XML_DTD support in Expat");
case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
return XML_L("cannot change setting once parsing has begun");
/* Added in 1.95.7. */
case XML_ERROR_UNBOUND_PREFIX:
return XML_L("unbound prefix");
/* Added in 1.95.8. */
case XML_ERROR_UNDECLARING_PREFIX:
return XML_L("must not undeclare prefix");
case XML_ERROR_INCOMPLETE_PE:
return XML_L("incomplete markup in parameter entity");
case XML_ERROR_XML_DECL:
return XML_L("XML declaration not well-formed");
case XML_ERROR_TEXT_DECL:
return XML_L("text declaration not well-formed");
case XML_ERROR_PUBLICID:
return XML_L("illegal character(s) in public id");
case XML_ERROR_SUSPENDED:
return XML_L("parser suspended");
case XML_ERROR_NOT_SUSPENDED:
return XML_L("parser not suspended");
case XML_ERROR_ABORTED:
return XML_L("parsing aborted");
case XML_ERROR_FINISHED:
return XML_L("parsing finished");
case XML_ERROR_SUSPEND_PE:
return XML_L("cannot suspend in external parameter entity");
/* Added in 2.0.0. */
case XML_ERROR_RESERVED_PREFIX_XML:
return XML_L(
"reserved prefix (xml) must not be undeclared or bound to another namespace name");
case XML_ERROR_RESERVED_PREFIX_XMLNS:
return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
case XML_ERROR_RESERVED_NAMESPACE_URI:
return XML_L(
"prefix must not be bound to one of the reserved namespace names");
/* Added in 2.2.5. */
case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
return XML_L("invalid argument");
}
return NULL;
}
const XML_LChar *XMLCALL
XML_ExpatVersion(void) {
/* V1 is used to string-ize the version number. However, it would
string-ize the actual version macro *names* unless we get them
substituted before being passed to V1. CPP is defined to expand
a macro, then rescan for more expansions. Thus, we use V2 to expand
the version macros, then CPP will expand the resulting V1() macro
with the correct numerals. */
/* ### I'm assuming cpp is portable in this respect... */
#define V1(a, b, c) XML_L(#a) XML_L(".") XML_L(#b) XML_L(".") XML_L(#c)
#define V2(a, b, c) XML_L("expat_") V1(a, b, c)
return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
#undef V1
#undef V2
}
XML_Expat_Version XMLCALL
XML_ExpatVersionInfo(void) {
XML_Expat_Version version;
version.major = XML_MAJOR_VERSION;
version.minor = XML_MINOR_VERSION;
version.micro = XML_MICRO_VERSION;
return version;
}
const XML_Feature *XMLCALL
XML_GetFeatureList(void) {
static const XML_Feature features[]
= {{XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
sizeof(XML_Char)},
{XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
sizeof(XML_LChar)},
#ifdef XML_UNICODE
{XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
#endif
#ifdef XML_UNICODE_WCHAR_T
{XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
#endif
#ifdef XML_DTD
{XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
#endif
#ifdef XML_CONTEXT_BYTES
{XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
XML_CONTEXT_BYTES},
#endif
#ifdef XML_MIN_SIZE
{XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
#endif
#ifdef XML_NS
{XML_FEATURE_NS, XML_L("XML_NS"), 0},
#endif
#ifdef XML_LARGE_SIZE
{XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
#endif
#ifdef XML_ATTR_INFO
{XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
#endif
{XML_FEATURE_END, NULL, 0}};
return features;
}
/* Initially tag->rawName always points into the parse buffer;
for those TAG instances opened while the current parse buffer was
processed, and not yet closed, we need to store tag->rawName in a more
permanent location, since the parse buffer is about to be discarded.
*/
static XML_Bool
storeRawNames(XML_Parser parser) {
TAG *tag = parser->m_tagStack;
while (tag) {
int bufSize;
int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
char *rawNameBuf = tag->buf + nameLen;
/* Stop if already stored. Since m_tagStack is a stack, we can stop
at the first entry that has already been copied; everything
below it in the stack is already been accounted for in a
previous call to this function.
*/
if (tag->rawName == rawNameBuf)
break;
/* For re-use purposes we need to ensure that the
size of tag->buf is a multiple of sizeof(XML_Char).
*/
bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
if (bufSize > tag->bufEnd - tag->buf) {
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_FALSE;
/* if tag->name.str points to tag->buf (only when namespace
processing is off) then we have to update it
*/
if (tag->name.str == (XML_Char *)tag->buf)
tag->name.str = (XML_Char *)temp;
/* if tag->name.localPart is set (when namespace processing is on)
then update it as well, since it will always point into tag->buf
*/
if (tag->name.localPart)
tag->name.localPart
= (XML_Char *)temp + (tag->name.localPart - (XML_Char *)tag->buf);
tag->buf = temp;
tag->bufEnd = temp + bufSize;
rawNameBuf = temp + nameLen;
}
memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
tag->rawName = rawNameBuf;
tag = tag->parent;
}
return XML_TRUE;
}
static enum XML_Error PTRCALL
contentProcessor(XML_Parser parser, const char *start, const char *end,
const char **endPtr) {
enum XML_Error result
= doContent(parser, 0, parser->m_encoding, start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (! storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error PTRCALL
externalEntityInitProcessor(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = externalEntityInitProcessor2;
return externalEntityInitProcessor2(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor2(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
const char *next = start; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(parser->m_encoding, start, end, &next);
switch (tok) {
case XML_TOK_BOM:
/* If we are at the end of the buffer, this would cause the next stage,
i.e. externalEntityInitProcessor3, to pass control directly to
doContent (by detecting XML_TOK_NONE) without processing any xml text
declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
*/
if (next == end && ! parser->m_parsingStatus.finalBuffer) {
*endPtr = next;
return XML_ERROR_NONE;
}
start = next;
break;
case XML_TOK_PARTIAL:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityInitProcessor3;
return externalEntityInitProcessor3(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor3(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
int tok;
const char *next = start; /* XmlContentTok doesn't always set the last arg */
parser->m_eventPtr = start;
tok = XmlContentTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
case XML_TOK_XML_DECL: {
enum XML_Error result;
result = processXmlDecl(parser, 1, start, next);
if (result != XML_ERROR_NONE)
return result;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*endPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
start = next;
}
} break;
case XML_TOK_PARTIAL:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (! parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityContentProcessor;
parser->m_tagLevel = 1;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityContentProcessor(XML_Parser parser, const char *start,
const char *end, const char **endPtr) {
enum XML_Error result
= doContent(parser, 1, parser->m_encoding, start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (! storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error
doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
const char *s, const char *end, const char **nextPtr,
XML_Bool haveMore) {
/* save one level of indirection */
DTD *const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
} else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
for (;;) {
const char *next = s; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_TRAILING_CR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
*eventEndPP = end;
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0)
return XML_ERROR_NO_ELEMENTS;
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (startTagLevel > 0) {
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_NO_ELEMENTS;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_ENTITY_REF: {
const XML_Char *name;
ENTITY *entity;
XML_Char ch = (XML_Char)XmlPredefinedEntityName(
enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
if (ch) {
if (parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&dtd->pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity or default handler.
*/
if (! dtd->hasParamEntityRefs || dtd->standalone) {
if (! entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (! entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
} else if (! entity) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->notation)
return XML_ERROR_BINARY_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
if (! parser->m_defaultExpandInternalEntities) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,
0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
result = processInternalEntity(parser, entity, XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
} else if (parser->m_externalEntityRefHandler) {
const XML_Char *context;
entity->open = XML_TRUE;
context = getContext(parser);
entity->open = XML_FALSE;
if (! context)
return XML_ERROR_NO_MEMORY;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, context, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
poolDiscard(&parser->m_tempPool);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
case XML_TOK_START_TAG_NO_ATTS:
/* fall through */
case XML_TOK_START_TAG_WITH_ATTS: {
TAG *tag;
enum XML_Error result;
XML_Char *toPtr;
if (parser->m_freeTagList) {
tag = parser->m_freeTagList;
parser->m_freeTagList = parser->m_freeTagList->parent;
} else {
tag = (TAG *)MALLOC(parser, sizeof(TAG));
if (! tag)
return XML_ERROR_NO_MEMORY;
tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
if (! tag->buf) {
FREE(parser, tag);
return XML_ERROR_NO_MEMORY;
}
tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
}
tag->bindings = NULL;
tag->parent = parser->m_tagStack;
parser->m_tagStack = tag;
tag->name.localPart = NULL;
tag->name.prefix = NULL;
tag->rawName = s + enc->minBytesPerChar;
tag->rawNameLength = XmlNameLength(enc, tag->rawName);
++parser->m_tagLevel;
{
const char *rawNameEnd = tag->rawName + tag->rawNameLength;
const char *fromPtr = tag->rawName;
toPtr = (XML_Char *)tag->buf;
for (;;) {
int bufSize;
int convLen;
const enum XML_Convert_Result convert_res
= XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,
(ICHAR *)tag->bufEnd - 1);
convLen = (int)(toPtr - (XML_Char *)tag->buf);
if ((fromPtr >= rawNameEnd)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
tag->name.strLen = convLen;
break;
}
bufSize = (int)(tag->bufEnd - tag->buf) << 1;
{
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
tag->buf = temp;
tag->bufEnd = temp + bufSize;
toPtr = (XML_Char *)temp + convLen;
}
}
}
tag->name.str = (XML_Char *)tag->buf;
*toPtr = XML_T('\0');
result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
if (result)
return result;
if (parser->m_startElementHandler)
parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
(const XML_Char **)parser->m_atts);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
break;
}
case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
/* fall through */
case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {
const char *rawName = s + enc->minBytesPerChar;
enum XML_Error result;
BINDING *bindings = NULL;
XML_Bool noElmHandlers = XML_TRUE;
TAG_NAME name;
name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
rawName + XmlNameLength(enc, rawName));
if (! name.str)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
result = storeAtts(parser, enc, s, &name, &bindings);
if (result != XML_ERROR_NONE) {
freeBindings(parser, bindings);
return result;
}
poolFinish(&parser->m_tempPool);
if (parser->m_startElementHandler) {
parser->m_startElementHandler(parser->m_handlerArg, name.str,
(const XML_Char **)parser->m_atts);
noElmHandlers = XML_FALSE;
}
if (parser->m_endElementHandler) {
if (parser->m_startElementHandler)
*eventPP = *eventEndPP;
parser->m_endElementHandler(parser->m_handlerArg, name.str);
noElmHandlers = XML_FALSE;
}
if (noElmHandlers && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
freeBindings(parser, bindings);
}
if ((parser->m_tagLevel == 0)
&& (parser->m_parsingStatus.parsing != XML_FINISHED)) {
if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
parser->m_processor = epilogProcessor;
else
return epilogProcessor(parser, next, end, nextPtr);
}
break;
case XML_TOK_END_TAG:
if (parser->m_tagLevel == startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
else {
int len;
const char *rawName;
TAG *tag = parser->m_tagStack;
parser->m_tagStack = tag->parent;
tag->parent = parser->m_freeTagList;
parser->m_freeTagList = tag;
rawName = s + enc->minBytesPerChar * 2;
len = XmlNameLength(enc, rawName);
if (len != tag->rawNameLength
|| memcmp(tag->rawName, rawName, len) != 0) {
*eventPP = rawName;
return XML_ERROR_TAG_MISMATCH;
}
--parser->m_tagLevel;
if (parser->m_endElementHandler) {
const XML_Char *localPart;
const XML_Char *prefix;
XML_Char *uri;
localPart = tag->name.localPart;
if (parser->m_ns && localPart) {
/* localPart and prefix may have been overwritten in
tag->name.str, since this points to the binding->uri
buffer which gets re-used; so we have to add them again
*/
uri = (XML_Char *)tag->name.str + tag->name.uriLen;
/* don't need to check for space - already done in storeAtts() */
while (*localPart)
*uri++ = *localPart++;
prefix = (XML_Char *)tag->name.prefix;
if (parser->m_ns_triplets && prefix) {
*uri++ = parser->m_namespaceSeparator;
while (*prefix)
*uri++ = *prefix++;
}
*uri = XML_T('\0');
}
parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
while (tag->bindings) {
BINDING *b = tag->bindings;
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg,
b->prefix->name);
tag->bindings = tag->bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
if ((parser->m_tagLevel == 0)
&& (parser->m_parsingStatus.parsing != XML_FINISHED)) {
if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
parser->m_processor = epilogProcessor;
else
return epilogProcessor(parser, next, end, nextPtr);
}
}
break;
case XML_TOK_CHAR_REF: {
int n = XmlCharRefNumber(enc, s);
if (n < 0)
return XML_ERROR_BAD_CHAR_REF;
if (parser->m_characterDataHandler) {
XML_Char buf[XML_ENCODE_MAX];
parser->m_characterDataHandler(parser->m_handlerArg, buf,
XmlEncode(n, (ICHAR *)buf));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
} break;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_CDATA_SECT_OPEN: {
enum XML_Error result;
if (parser->m_startCdataSectionHandler)
parser->m_startCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* Suppose you doing a transformation on a document that involves
changing only the character data. You set up a defaultHandler
and a characterDataHandler. The defaultHandler simply copies
characters through. The characterDataHandler does the
transformation and writes the characters out escaping them as
necessary. This case will fail to work if we leave out the
following two lines (because & and < inside CDATA sections will
be incorrectly escaped).
However, now we have a start/endCdataSectionHandler, so it seems
easier to let the user deal with this.
*/
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (! next) {
parser->m_processor = cdataSectionProcessor;
return result;
}
} break;
case XML_TOK_TRAILING_RSQB:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (parser->m_characterDataHandler) {
if (MUST_CONVERT(enc, s)) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
parser->m_characterDataHandler(
parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
} else
parser->m_characterDataHandler(
parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)end - (XML_Char *)s));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0) {
*eventPP = end;
return XML_ERROR_NO_ELEMENTS;
}
if (parser->m_tagLevel != startTagLevel) {
*eventPP = end;
return XML_ERROR_ASYNC_ENTITY;
}
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_DATA_CHARS: {
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(
enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
} else
charDataHandler(parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
} break;
case XML_TOK_PI:
if (! reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (! reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
default:
/* All of the tokens produced by XmlContentTok() have their own
* explicit cases, so this default is not strictly necessary.
* However it is a useful safety net, so we retain the code and
* simply exclude it from the coverage tests.
*
* LCOV_EXCL_START
*/
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:;
}
}
/* not reached */
}
/* This function does not call free() on the allocated memory, merely
* moving it to the parser's m_freeBindingList where it can be freed or
* reused as appropriate.
*/
static void
freeBindings(XML_Parser parser, BINDING *bindings) {
while (bindings) {
BINDING *b = bindings;
/* m_startNamespaceDeclHandler will have been called for this
* binding in addBindings(), so call the end handler now.
*/
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
}
/* Precondition: all arguments must be non-NULL;
Purpose:
- normalize attributes
- check attributes for well-formedness
- generate namespace aware attribute names (URI, prefix)
- build list of attributes for startElementHandler
- default attributes
- process namespace declarations (check and report them)
- generate namespace aware element name (URI, prefix)
*/
static enum XML_Error
storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
TAG_NAME *tagNamePtr, BINDING **bindingsPtr) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
ELEMENT_TYPE *elementType;
int nDefaultAtts;
const XML_Char **appAtts; /* the attribute list for the application */
int attIndex = 0;
int prefixLen;
int i;
int n;
XML_Char *uri;
int nPrefixes = 0;
BINDING *binding;
const XML_Char *localPart;
/* lookup the element type name */
elementType
= (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);
if (! elementType) {
const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
if (! name)
return XML_ERROR_NO_MEMORY;
elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
sizeof(ELEMENT_TYPE));
if (! elementType)
return XML_ERROR_NO_MEMORY;
if (parser->m_ns && ! setElementTypePrefix(parser, elementType))
return XML_ERROR_NO_MEMORY;
}
nDefaultAtts = elementType->nDefaultAtts;
/* get the attributes from the tokenizer */
n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
if (n + nDefaultAtts > parser->m_attsSize) {
int oldAttsSize = parser->m_attsSize;
ATTRIBUTE *temp;
#ifdef XML_ATTR_INFO
XML_AttrInfo *temp2;
#endif
parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts,
parser->m_attsSize * sizeof(ATTRIBUTE));
if (temp == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_atts = temp;
#ifdef XML_ATTR_INFO
temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo,
parser->m_attsSize * sizeof(XML_AttrInfo));
if (temp2 == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_attInfo = temp2;
#endif
if (n > oldAttsSize)
XmlGetAttributes(enc, attStr, n, parser->m_atts);
}
appAtts = (const XML_Char **)parser->m_atts;
for (i = 0; i < n; i++) {
ATTRIBUTE *currAtt = &parser->m_atts[i];
#ifdef XML_ATTR_INFO
XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
#endif
/* add the name and value to the attribute list */
ATTRIBUTE_ID *attId
= getAttributeId(parser, enc, currAtt->name,
currAtt->name + XmlNameLength(enc, currAtt->name));
if (! attId)
return XML_ERROR_NO_MEMORY;
#ifdef XML_ATTR_INFO
currAttInfo->nameStart
= parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
currAttInfo->nameEnd
= currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);
currAttInfo->valueStart = parser->m_parseEndByteIndex
- (parser->m_parseEndPtr - currAtt->valuePtr);
currAttInfo->valueEnd = parser->m_parseEndByteIndex
- (parser->m_parseEndPtr - currAtt->valueEnd);
#endif
/* Detect duplicate attributes by their QNames. This does not work when
namespace processing is turned on and different prefixes for the same
namespace are used. For this case we have a check further down.
*/
if ((attId->name)[-1]) {
if (enc == parser->m_encoding)
parser->m_eventPtr = parser->m_atts[i].name;
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
(attId->name)[-1] = 1;
appAtts[attIndex++] = attId->name;
if (! parser->m_atts[i].normalized) {
enum XML_Error result;
XML_Bool isCdata = XML_TRUE;
/* figure out whether declared as other than CDATA */
if (attId->maybeTokenized) {
int j;
for (j = 0; j < nDefaultAtts; j++) {
if (attId == elementType->defaultAtts[j].id) {
isCdata = elementType->defaultAtts[j].isCdata;
break;
}
}
}
/* normalize the attribute value */
result = storeAttributeValue(
parser, enc, isCdata, parser->m_atts[i].valuePtr,
parser->m_atts[i].valueEnd, &parser->m_tempPool);
if (result)
return result;
appAtts[attIndex] = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
} else {
/* the value did not need normalizing */
appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,
parser->m_atts[i].valuePtr,
parser->m_atts[i].valueEnd);
if (appAtts[attIndex] == 0)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
}
/* handle prefixed attribute names */
if (attId->prefix) {
if (attId->xmlns) {
/* deal with namespace declarations here */
enum XML_Error result = addBinding(parser, attId->prefix, attId,
appAtts[attIndex], bindingsPtr);
if (result)
return result;
--attIndex;
} else {
/* deal with other prefixed names later */
attIndex++;
nPrefixes++;
(attId->name)[-1] = 2;
}
} else
attIndex++;
}
/* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
parser->m_nSpecifiedAtts = attIndex;
if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
for (i = 0; i < attIndex; i += 2)
if (appAtts[i] == elementType->idAtt->name) {
parser->m_idAttIndex = i;
break;
}
} else
parser->m_idAttIndex = -1;
/* do attribute defaulting */
for (i = 0; i < nDefaultAtts; i++) {
const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
if (! (da->id->name)[-1] && da->value) {
if (da->id->prefix) {
if (da->id->xmlns) {
enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
da->value, bindingsPtr);
if (result)
return result;
} else {
(da->id->name)[-1] = 2;
nPrefixes++;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
} else {
(da->id->name)[-1] = 1;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
}
}
appAtts[attIndex] = 0;
/* expand prefixed attribute names, check for duplicates,
and clear flags that say whether attributes were specified */
i = 0;
if (nPrefixes) {
int j; /* hash table index */
unsigned long version = parser->m_nsAttsVersion;
int nsAttsSize = (int)1 << parser->m_nsAttsPower;
unsigned char oldNsAttsPower = parser->m_nsAttsPower;
/* size of hash table must be at least 2 * (# of prefixed attributes) */
if ((nPrefixes << 1)
>> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
NS_ATT *temp;
/* hash table size must also be a power of 2 and >= 8 */
while (nPrefixes >> parser->m_nsAttsPower++)
;
if (parser->m_nsAttsPower < 3)
parser->m_nsAttsPower = 3;
nsAttsSize = (int)1 << parser->m_nsAttsPower;
temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts,
nsAttsSize * sizeof(NS_ATT));
if (! temp) {
/* Restore actual size of memory in m_nsAtts */
parser->m_nsAttsPower = oldNsAttsPower;
return XML_ERROR_NO_MEMORY;
}
parser->m_nsAtts = temp;
version = 0; /* force re-initialization of m_nsAtts hash table */
}
/* using a version flag saves us from initializing m_nsAtts every time */
if (! version) { /* initialize version flags when version wraps around */
version = INIT_ATTS_VERSION;
for (j = nsAttsSize; j != 0;)
parser->m_nsAtts[--j].version = version;
}
parser->m_nsAttsVersion = --version;
/* expand prefixed names and check for duplicates */
for (; i < attIndex; i += 2) {
const XML_Char *s = appAtts[i];
if (s[-1] == 2) { /* prefixed */
ATTRIBUTE_ID *id;
const BINDING *b;
unsigned long uriHash;
struct siphash sip_state;
struct sipkey sip_key;
copy_salt_to_sipkey(parser, &sip_key);
sip24_init(&sip_state, &sip_key);
((XML_Char *)s)[-1] = 0; /* clear flag */
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
if (! id || ! id->prefix) {
/* This code is walking through the appAtts array, dealing
* with (in this case) a prefixed attribute name. To be in
* the array, the attribute must have already been bound, so
* has to have passed through the hash table lookup once
* already. That implies that an entry for it already
* exists, so the lookup above will return a pointer to
* already allocated memory. There is no opportunaity for
* the allocator to fail, so the condition above cannot be
* fulfilled.
*
* Since it is difficult to be certain that the above
* analysis is complete, we retain the test and merely
* remove the code from coverage tests.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
b = id->prefix->binding;
if (! b)
return XML_ERROR_UNBOUND_PREFIX;
for (j = 0; j < b->uriLen; j++) {
const XML_Char c = b->uri[j];
if (! poolAppendChar(&parser->m_tempPool, c))
return XML_ERROR_NO_MEMORY;
}
sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
while (*s++ != XML_T(ASCII_COLON))
;
sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
do { /* copies null terminator */
if (! poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
uriHash = (unsigned long)sip24_final(&sip_state);
{ /* Check hash table for duplicate of expanded name (uriName).
Derived from code in lookup(parser, HASH_TABLE *table, ...).
*/
unsigned char step = 0;
unsigned long mask = nsAttsSize - 1;
j = uriHash & mask; /* index into hash table */
while (parser->m_nsAtts[j].version == version) {
/* for speed we compare stored hash values first */
if (uriHash == parser->m_nsAtts[j].hash) {
const XML_Char *s1 = poolStart(&parser->m_tempPool);
const XML_Char *s2 = parser->m_nsAtts[j].uriName;
/* s1 is null terminated, but not s2 */
for (; *s1 == *s2 && *s1 != 0; s1++, s2++)
;
if (*s1 == 0)
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
if (! step)
step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
j < step ? (j += nsAttsSize - step) : (j -= step);
}
}
if (parser->m_ns_triplets) { /* append namespace separator and prefix */
parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
s = b->prefix->name;
do {
if (! poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
}
/* store expanded name in attribute list */
s = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
appAtts[i] = s;
/* fill empty slot with new version, uriName and hash value */
parser->m_nsAtts[j].version = version;
parser->m_nsAtts[j].hash = uriHash;
parser->m_nsAtts[j].uriName = s;
if (! --nPrefixes) {
i += 2;
break;
}
} else /* not prefixed */
((XML_Char *)s)[-1] = 0; /* clear flag */
}
}
/* clear flags for the remaining attributes */
for (; i < attIndex; i += 2)
((XML_Char *)(appAtts[i]))[-1] = 0;
for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
binding->attId->name[-1] = 0;
if (! parser->m_ns)
return XML_ERROR_NONE;
/* expand the element type name */
if (elementType->prefix) {
binding = elementType->prefix->binding;
if (! binding)
return XML_ERROR_UNBOUND_PREFIX;
localPart = tagNamePtr->str;
while (*localPart++ != XML_T(ASCII_COLON))
;
} else if (dtd->defaultPrefix.binding) {
binding = dtd->defaultPrefix.binding;
localPart = tagNamePtr->str;
} else
return XML_ERROR_NONE;
prefixLen = 0;
if (parser->m_ns_triplets && binding->prefix->name) {
for (; binding->prefix->name[prefixLen++];)
; /* prefixLen includes null terminator */
}
tagNamePtr->localPart = localPart;
tagNamePtr->uriLen = binding->uriLen;
tagNamePtr->prefix = binding->prefix->name;
tagNamePtr->prefixLen = prefixLen;
for (i = 0; localPart[i++];)
; /* i includes null terminator */
n = i + binding->uriLen + prefixLen;
if (n > binding->uriAlloc) {
TAG *p;
uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
if (! uri)
return XML_ERROR_NO_MEMORY;
binding->uriAlloc = n + EXPAND_SPARE;
memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
for (p = parser->m_tagStack; p; p = p->parent)
if (p->name.str == binding->uri)
p->name.str = uri;
FREE(parser, binding->uri);
binding->uri = uri;
}
/* if m_namespaceSeparator != '\0' then uri includes it already */
uri = binding->uri + binding->uriLen;
memcpy(uri, localPart, i * sizeof(XML_Char));
/* we always have a namespace separator between localPart and prefix */
if (prefixLen) {
uri += i - 1;
*uri = parser->m_namespaceSeparator; /* replace null terminator */
memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
}
tagNamePtr->str = binding->uri;
return XML_ERROR_NONE;
}
/* addBinding() overwrites the value of prefix->binding without checking.
Therefore one must keep track of the old value outside of addBinding().
*/
static enum XML_Error
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
const XML_Char *uri, BINDING **bindingsPtr) {
static const XML_Char xmlNamespace[]
= {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON,
ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o,
ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M,
ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9,
ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m,
ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
ASCII_e, '\0'};
static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;
static const XML_Char xmlnsNamespace[]
= {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,
ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH,
ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x,
ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'};
static const int xmlnsLen
= (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;
XML_Bool mustBeXML = XML_FALSE;
XML_Bool isXML = XML_TRUE;
XML_Bool isXMLNS = XML_TRUE;
BINDING *b;
int len;
/* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
if (*uri == XML_T('\0') && prefix->name)
return XML_ERROR_UNDECLARING_PREFIX;
if (prefix->name && prefix->name[0] == XML_T(ASCII_x)
&& prefix->name[1] == XML_T(ASCII_m)
&& prefix->name[2] == XML_T(ASCII_l)) {
/* Not allowed to bind xmlns */
if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)
&& prefix->name[5] == XML_T('\0'))
return XML_ERROR_RESERVED_PREFIX_XMLNS;
if (prefix->name[3] == XML_T('\0'))
mustBeXML = XML_TRUE;
}
for (len = 0; uri[len]; len++) {
if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
isXML = XML_FALSE;
if (! mustBeXML && isXMLNS
&& (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
isXMLNS = XML_FALSE;
}
isXML = isXML && len == xmlLen;
isXMLNS = isXMLNS && len == xmlnsLen;
if (mustBeXML != isXML)
return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
: XML_ERROR_RESERVED_NAMESPACE_URI;
if (isXMLNS)
return XML_ERROR_RESERVED_NAMESPACE_URI;
if (parser->m_namespaceSeparator)
len++;
if (parser->m_freeBindingList) {
b = parser->m_freeBindingList;
if (len > b->uriAlloc) {
XML_Char *temp = (XML_Char *)REALLOC(
parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
b->uri = temp;
b->uriAlloc = len + EXPAND_SPARE;
}
parser->m_freeBindingList = b->nextTagBinding;
} else {
b = (BINDING *)MALLOC(parser, sizeof(BINDING));
if (! b)
return XML_ERROR_NO_MEMORY;
b->uri
= (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
if (! b->uri) {
FREE(parser, b);
return XML_ERROR_NO_MEMORY;
}
b->uriAlloc = len + EXPAND_SPARE;
}
b->uriLen = len;
memcpy(b->uri, uri, len * sizeof(XML_Char));
if (parser->m_namespaceSeparator)
b->uri[len - 1] = parser->m_namespaceSeparator;
b->prefix = prefix;
b->attId = attId;
b->prevPrefixBinding = prefix->binding;
/* NULL binding when default namespace undeclared */
if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
prefix->binding = NULL;
else
prefix->binding = b;
b->nextTagBinding = *bindingsPtr;
*bindingsPtr = b;
/* if attId == NULL then we are not starting a namespace scope */
if (attId && parser->m_startNamespaceDeclHandler)
parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
prefix->binding ? uri : 0);
return XML_ERROR_NONE;
}
/* The idea here is to avoid using stack for each CDATA section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
cdataSectionProcessor(XML_Parser parser, const char *start, const char *end,
const char **endPtr) {
enum XML_Error result
= doCdataSection(parser, parser->m_encoding, &start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
if (parser->m_parentParser) { /* we are parsing an external entity */
parser->m_processor = externalEntityContentProcessor;
return externalEntityContentProcessor(parser, start, end, endPtr);
} else {
parser->m_processor = contentProcessor;
return contentProcessor(parser, start, end, endPtr);
}
}
return result;
}
/* startPtr gets set to non-null if the section is closed, and to null if
the section is not yet closed.
*/
static enum XML_Error
doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore) {
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
} else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
*startPtr = NULL;
for (;;) {
const char *next;
int tok = XmlCdataSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_CDATA_SECT_CLOSE:
if (parser->m_endCdataSectionHandler)
parser->m_endCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* see comment under XML_TOK_CDATA_SECT_OPEN */
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_DATA_CHARS: {
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(
enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = next;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
} else
charDataHandler(parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
} else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
} break;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_CDATA_SECTION;
default:
/* Every token returned by XmlCdataSectionTok() has its own
* explicit case, so this default case will never be executed.
* We retain it as a safety net and exclude it from the coverage
* statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:;
}
}
/* not reached */
}
#ifdef XML_DTD
/* The idea here is to avoid using stack for each IGNORE section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
ignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,
const char **endPtr) {
enum XML_Error result
= doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
parser->m_processor = prologProcessor;
return prologProcessor(parser, start, end, endPtr);
}
return result;
}
/* startPtr gets set to non-null is the section is closed, and to null
if the section is not yet closed.
*/
static enum XML_Error
doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore) {
const char *next;
int tok;
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
} else {
/* It's not entirely clear, but it seems the following two lines
* of code cannot be executed. The only occasions on which 'enc'
* is not 'encoding' are when this function is called
* from the internal entity processing, and IGNORE sections are an
* error in internal entities.
*
* Since it really isn't clear that this is true, we keep the code
* and just remove it from our coverage tests.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
*eventPP = s;
*startPtr = NULL;
tok = XmlIgnoreSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_IGNORE_SECT:
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
default:
/* All of the tokens that XmlIgnoreSectionTok() returns have
* explicit cases to handle them, so this default case is never
* executed. We keep it as a safety net anyway, and remove it
* from our test coverage statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
/* not reached */
}
#endif /* XML_DTD */
static enum XML_Error
initializeEncoding(XML_Parser parser) {
const char *s;
#ifdef XML_UNICODE
char encodingBuf[128];
/* See comments abount `protoclEncodingName` in parserInit() */
if (! parser->m_protocolEncodingName)
s = NULL;
else {
int i;
for (i = 0; parser->m_protocolEncodingName[i]; i++) {
if (i == sizeof(encodingBuf) - 1
|| (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
encodingBuf[0] = '\0';
break;
}
encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
}
encodingBuf[i] = '\0';
s = encodingBuf;
}
#else
s = parser->m_protocolEncodingName;
#endif
if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(
&parser->m_initEncoding, &parser->m_encoding, s))
return XML_ERROR_NONE;
return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
}
static enum XML_Error
processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
const char *next) {
const char *encodingName = NULL;
const XML_Char *storedEncName = NULL;
const ENCODING *newEncoding = NULL;
const char *version = NULL;
const char *versionend;
const XML_Char *storedversion = NULL;
int standalone = -1;
if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(
isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,
&version, &versionend, &encodingName, &newEncoding, &standalone)) {
if (isGeneralTextEntity)
return XML_ERROR_TEXT_DECL;
else
return XML_ERROR_XML_DECL;
}
if (! isGeneralTextEntity && standalone == 1) {
parser->m_dtd->standalone = XML_TRUE;
#ifdef XML_DTD
if (parser->m_paramEntityParsing
== XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif /* XML_DTD */
}
if (parser->m_xmlDeclHandler) {
if (encodingName != NULL) {
storedEncName = poolStoreString(
&parser->m_temp2Pool, parser->m_encoding, encodingName,
encodingName + XmlNameLength(parser->m_encoding, encodingName));
if (! storedEncName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_temp2Pool);
}
if (version) {
storedversion
= poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,
versionend - parser->m_encoding->minBytesPerChar);
if (! storedversion)
return XML_ERROR_NO_MEMORY;
}
parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,
standalone);
} else if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_protocolEncodingName == NULL) {
if (newEncoding) {
/* Check that the specified encoding does not conflict with what
* the parser has already deduced. Do we have the same number
* of bytes in the smallest representation of a character? If
* this is UTF-16, is it the same endianness?
*/
if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
|| (newEncoding->minBytesPerChar == 2
&& newEncoding != parser->m_encoding)) {
parser->m_eventPtr = encodingName;
return XML_ERROR_INCORRECT_ENCODING;
}
parser->m_encoding = newEncoding;
} else if (encodingName) {
enum XML_Error result;
if (! storedEncName) {
storedEncName = poolStoreString(
&parser->m_temp2Pool, parser->m_encoding, encodingName,
encodingName + XmlNameLength(parser->m_encoding, encodingName));
if (! storedEncName)
return XML_ERROR_NO_MEMORY;
}
result = handleUnknownEncoding(parser, storedEncName);
poolClear(&parser->m_temp2Pool);
if (result == XML_ERROR_UNKNOWN_ENCODING)
parser->m_eventPtr = encodingName;
return result;
}
}
if (storedEncName || storedversion)
poolClear(&parser->m_temp2Pool);
return XML_ERROR_NONE;
}
static enum XML_Error
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {
if (parser->m_unknownEncodingHandler) {
XML_Encoding info;
int i;
for (i = 0; i < 256; i++)
info.map[i] = -1;
info.convert = NULL;
info.data = NULL;
info.release = NULL;
if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,
encodingName, &info)) {
ENCODING *enc;
parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
if (! parser->m_unknownEncodingMem) {
if (info.release)
info.release(info.data);
return XML_ERROR_NO_MEMORY;
}
enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(
parser->m_unknownEncodingMem, info.map, info.convert, info.data);
if (enc) {
parser->m_unknownEncodingData = info.data;
parser->m_unknownEncodingRelease = info.release;
parser->m_encoding = enc;
return XML_ERROR_NONE;
}
}
if (info.release != NULL)
info.release(info.data);
}
return XML_ERROR_UNKNOWN_ENCODING;
}
static enum XML_Error PTRCALL
prologInitProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = prologProcessor;
return prologProcessor(parser, s, end, nextPtr);
}
#ifdef XML_DTD
static enum XML_Error PTRCALL
externalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
/* we know now that XML_Parse(Buffer) has been called,
so we consider the external parameter entity read */
parser->m_dtd->paramEntityRead = XML_TRUE;
if (parser->m_prologState.inEntityValue) {
parser->m_processor = entityValueInitProcessor;
return entityValueInitProcessor(parser, s, end, nextPtr);
} else {
parser->m_processor = externalParEntProcessor;
return externalParEntProcessor(parser, s, end, nextPtr);
}
}
static enum XML_Error PTRCALL
entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
int tok;
const char *start = s;
const char *next = start;
parser->m_eventPtr = start;
for (;;) {
tok = XmlPrologTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, parser->m_encoding, s, end);
} else if (tok == XML_TOK_XML_DECL) {
enum XML_Error result;
result = processXmlDecl(parser, 0, start, next);
if (result != XML_ERROR_NONE)
return result;
/* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For
* that to happen, a parameter entity parsing handler must have attempted
* to suspend the parser, which fails and raises an error. The parser can
* be aborted, but can't be suspended.
*/
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
*nextPtr = next;
/* stop scanning for text declaration - we found one */
parser->m_processor = entityValueProcessor;
return entityValueProcessor(parser, next, end, nextPtr);
}
/* If we are at the end of the buffer, this would cause XmlPrologTok to
return XML_TOK_NONE on the next call, which would then cause the
function to exit with *nextPtr set to s - that is what we want for other
tokens, but not for the BOM - we would rather like to skip it;
then, when this routine is entered the next time, XmlPrologTok will
return XML_TOK_INVALID, since the BOM is still in the buffer
*/
else if (tok == XML_TOK_BOM && next == end
&& ! parser->m_parsingStatus.finalBuffer) {
*nextPtr = next;
return XML_ERROR_NONE;
}
/* If we get this token, we have the start of what might be a
normal tag, but not a declaration (i.e. it doesn't begin with
"<!"). In a DTD context, that isn't legal.
*/
else if (tok == XML_TOK_INSTANCE_START) {
*nextPtr = next;
return XML_ERROR_SYNTAX;
}
start = next;
parser->m_eventPtr = start;
}
}
static enum XML_Error PTRCALL
externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
}
static enum XML_Error PTRCALL
entityValueProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *start = s;
const char *next = s;
const ENCODING *enc = parser->m_encoding;
int tok;
for (;;) {
tok = XmlPrologTok(enc, start, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, enc, s, end);
}
start = next;
}
}
#endif /* XML_DTD */
static enum XML_Error PTRCALL
prologProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
}
static enum XML_Error
doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
int tok, const char *next, const char **nextPtr, XML_Bool haveMore,
XML_Bool allowClosingDoctype) {
#ifdef XML_DTD
static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
#endif /* XML_DTD */
static const XML_Char atypeCDATA[]
= {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
static const XML_Char atypeIDREF[]
= {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
static const XML_Char atypeIDREFS[]
= {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
static const XML_Char atypeENTITY[]
= {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
static const XML_Char atypeENTITIES[]
= {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
ASCII_I, ASCII_E, ASCII_S, '\0'};
static const XML_Char atypeNMTOKEN[]
= {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
static const XML_Char atypeNMTOKENS[]
= {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
ASCII_E, ASCII_N, ASCII_S, '\0'};
static const XML_Char notationPrefix[]
= {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,
ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
/* save one level of indirection */
DTD *const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
enum XML_Content_Quant quant;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
} else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
for (;;) {
int role;
XML_Bool handleDefault = XML_TRUE;
*eventPP = s;
*eventEndPP = next;
if (tok <= 0) {
if (haveMore && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case -XML_TOK_PROLOG_S:
tok = -tok;
break;
case XML_TOK_NONE:
#ifdef XML_DTD
/* for internal PE NOT referenced between declarations */
if (enc != parser->m_encoding
&& ! parser->m_openInternalEntities->betweenDecl) {
*nextPtr = s;
return XML_ERROR_NONE;
}
/* WFC: PE Between Declarations - must check that PE contains
complete markup, not only for external PEs, but also for
internal PEs if the reference occurs between declarations.
*/
if (parser->m_isParamEntity || enc != parser->m_encoding) {
if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
== XML_ROLE_ERROR)
return XML_ERROR_INCOMPLETE_PE;
*nextPtr = s;
return XML_ERROR_NONE;
}
#endif /* XML_DTD */
return XML_ERROR_NO_ELEMENTS;
default:
tok = -tok;
next = end;
break;
}
}
role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
switch (role) {
case XML_ROLE_XML_DECL: {
enum XML_Error result = processXmlDecl(parser, 0, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
} break;
case XML_ROLE_DOCTYPE_NAME:
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeName
= poolStoreString(&parser->m_tempPool, enc, s, next);
if (! parser->m_doctypeName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = NULL;
handleDefault = XML_FALSE;
}
parser->m_doctypeSysid = NULL; /* always initialize to NULL */
break;
case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
if (parser->m_startDoctypeDeclHandler) {
parser->m_startDoctypeDeclHandler(
parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 1);
parser->m_doctypeName = NULL;
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
#ifdef XML_DTD
case XML_ROLE_TEXT_DECL: {
enum XML_Error result = processXmlDecl(parser, 1, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
} break;
#endif /* XML_DTD */
case XML_ROLE_DOCTYPE_PUBLIC_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
parser->m_declEntity = (ENTITY *)lookup(
parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
XML_Char *pubId;
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
pubId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! pubId)
return XML_ERROR_NO_MEMORY;
normalizePublicId(pubId);
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = pubId;
handleDefault = XML_FALSE;
goto alreadyChecked;
}
/* fall through */
case XML_ROLE_ENTITY_PUBLIC_ID:
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
alreadyChecked:
if (dtd->keepProcessing && parser->m_declEntity) {
XML_Char *tem
= poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declEntity->publicId = tem;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_PUBLIC_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_CLOSE:
if (allowClosingDoctype != XML_TRUE) {
/* Must not close doctype from within expanded parameter entities */
return XML_ERROR_INVALID_TOKEN;
}
if (parser->m_doctypeName) {
parser->m_startDoctypeDeclHandler(
parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 0);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
/* parser->m_doctypeSysid will be non-NULL in the case of a previous
XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
was not set, indicating an external subset
*/
#ifdef XML_DTD
if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing
&& parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName, sizeof(ENTITY));
if (! entity) {
/* The external subset name "#" will have already been
* inserted into the hash table at the start of the
* external entity parsing, so no allocation will happen
* and lookup() cannot fail.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
if (parser->m_useForeignDTD)
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else if (! parser->m_doctypeSysid)
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
parser->m_useForeignDTD = XML_FALSE;
}
#endif /* XML_DTD */
if (parser->m_endDoctypeDeclHandler) {
parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_INSTANCE_START:
#ifdef XML_DTD
/* if there is no DOCTYPE declaration then now is the
last chance to read the foreign DTD
*/
if (parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing
&& parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName, sizeof(ENTITY));
if (! entity)
return XML_ERROR_NO_MEMORY;
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
}
#endif /* XML_DTD */
parser->m_processor = contentProcessor;
return contentProcessor(parser, s, end, nextPtr);
case XML_ROLE_ATTLIST_ELEMENT_NAME:
parser->m_declElementType = getElementType(parser, enc, s, next);
if (! parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_NAME:
parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
if (! parser->m_declAttributeId)
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeType = NULL;
parser->m_declAttributeIsId = XML_FALSE;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
parser->m_declAttributeIsCdata = XML_TRUE;
parser->m_declAttributeType = atypeCDATA;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ID:
parser->m_declAttributeIsId = XML_TRUE;
parser->m_declAttributeType = atypeID;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
parser->m_declAttributeType = atypeIDREF;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
parser->m_declAttributeType = atypeIDREFS;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
parser->m_declAttributeType = atypeENTITY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
parser->m_declAttributeType = atypeENTITIES;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
parser->m_declAttributeType = atypeNMTOKEN;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
parser->m_declAttributeType = atypeNMTOKENS;
checkAttListDeclHandler:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
const XML_Char *prefix;
if (parser->m_declAttributeType) {
prefix = enumValueSep;
} else {
prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
: enumValueStart);
}
if (! poolAppendString(&parser->m_tempPool, prefix))
return XML_ERROR_NO_MEMORY;
if (! poolAppend(&parser->m_tempPool, enc, s, next))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
if (! defineAttribute(parser->m_declElementType,
parser->m_declAttributeId,
parser->m_declAttributeIsCdata,
parser->m_declAttributeIsId, 0, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
const XML_Char *attVal;
enum XML_Error result = storeAttributeValue(
parser, enc, parser->m_declAttributeIsCdata,
s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool);
if (result)
return result;
attVal = poolStart(&dtd->pool);
poolFinish(&dtd->pool);
/* ID attributes aren't allowed to have a default */
if (! defineAttribute(
parser->m_declElementType, parser->m_declAttributeId,
parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType,
attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_ENTITY_VALUE:
if (dtd->keepProcessing) {
enum XML_Error result = storeEntityValue(
parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
if (parser->m_declEntity) {
parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
parser->m_declEntity->textLen
= (int)(poolLength(&dtd->entityValuePool));
poolFinish(&dtd->entityValuePool);
if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
handleDefault = XML_FALSE;
}
} else
poolDiscard(&dtd->entityValuePool);
if (result != XML_ERROR_NONE)
return result;
}
break;
case XML_ROLE_DOCTYPE_SYSTEM_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (parser->m_doctypeSysid == NULL)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
#ifdef XML_DTD
else
/* use externalSubsetName to make parser->m_doctypeSysid non-NULL
for the case where no parser->m_startDoctypeDeclHandler is set */
parser->m_doctypeSysid = externalSubsetName;
#endif /* XML_DTD */
if (! dtd->standalone
#ifdef XML_DTD
&& ! parser->m_paramEntityParsing
#endif /* XML_DTD */
&& parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
#ifndef XML_DTD
break;
#else /* XML_DTD */
if (! parser->m_declEntity) {
parser->m_declEntity = (ENTITY *)lookup(
parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->publicId = NULL;
}
#endif /* XML_DTD */
/* fall through */
case XML_ROLE_ENTITY_SYSTEM_ID:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->systemId
= poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! parser->m_declEntity->systemId)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->base = parser->m_curBase;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_SYSTEM_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_COMPLETE:
if (dtd->keepProcessing && parser->m_declEntity
&& parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,
parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_NOTATION_NAME:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->notation
= poolStoreString(&dtd->pool, enc, s, next);
if (! parser->m_declEntity->notation)
return XML_ERROR_NO_MEMORY;
poolFinish(&dtd->pool);
if (parser->m_unparsedEntityDeclHandler) {
*eventEndPP = s;
parser->m_unparsedEntityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->base, parser->m_declEntity->systemId,
parser->m_declEntity->publicId, parser->m_declEntity->notation);
handleDefault = XML_FALSE;
} else if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,
parser->m_declEntity->base, parser->m_declEntity->systemId,
parser->m_declEntity->publicId, parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_GENERAL_ENTITY_NAME: {
if (XmlPredefinedEntityName(enc, s, next)) {
parser->m_declEntity = NULL;
break;
}
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (! name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,
name, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
} else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_FALSE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal
= ! (parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
} else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
} break;
case XML_ROLE_PARAM_ENTITY_NAME:
#ifdef XML_DTD
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (! name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
name, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
} else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_TRUE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal
= ! (parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
} else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
#else /* not XML_DTD */
parser->m_declEntity = NULL;
#endif /* XML_DTD */
break;
case XML_ROLE_NOTATION_NAME:
parser->m_declNotationPublicId = NULL;
parser->m_declNotationName = NULL;
if (parser->m_notationDeclHandler) {
parser->m_declNotationName
= poolStoreString(&parser->m_tempPool, enc, s, next);
if (! parser->m_declNotationName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_PUBLIC_ID:
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
if (parser
->m_declNotationName) { /* means m_notationDeclHandler != NULL */
XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declNotationPublicId = tem;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_SYSTEM_ID:
if (parser->m_declNotationName && parser->m_notationDeclHandler) {
const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! systemId)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_notationDeclHandler(
parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
systemId, parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_NOTATION_NO_SYSTEM_ID:
if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
*eventEndPP = s;
parser->m_notationDeclHandler(
parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
0, parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_ERROR:
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
/* PE references in internal subset are
not allowed within declarations. */
return XML_ERROR_PARAM_ENTITY_REF;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
default:
return XML_ERROR_SYNTAX;
}
#ifdef XML_DTD
case XML_ROLE_IGNORE_SECT: {
enum XML_Error result;
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
handleDefault = XML_FALSE;
result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (! next) {
parser->m_processor = ignoreSectionProcessor;
return result;
}
} break;
#endif /* XML_DTD */
case XML_ROLE_GROUP_OPEN:
if (parser->m_prologState.level >= parser->m_groupSize) {
if (parser->m_groupSize) {
{
char *const new_connector = (char *)REALLOC(
parser, parser->m_groupConnector, parser->m_groupSize *= 2);
if (new_connector == NULL) {
parser->m_groupSize /= 2;
return XML_ERROR_NO_MEMORY;
}
parser->m_groupConnector = new_connector;
}
if (dtd->scaffIndex) {
int *const new_scaff_index = (int *)REALLOC(
parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));
if (new_scaff_index == NULL)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex = new_scaff_index;
}
} else {
parser->m_groupConnector
= (char *)MALLOC(parser, parser->m_groupSize = 32);
if (! parser->m_groupConnector) {
parser->m_groupSize = 0;
return XML_ERROR_NO_MEMORY;
}
}
}
parser->m_groupConnector[parser->m_prologState.level] = 0;
if (dtd->in_eldecl) {
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
assert(dtd->scaffIndex != NULL);
dtd->scaffIndex[dtd->scaffLevel] = myindex;
dtd->scaffLevel++;
dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_SEQUENCE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
return XML_ERROR_SYNTAX;
parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
if (dtd->in_eldecl && parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_GROUP_CHOICE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
return XML_ERROR_SYNTAX;
if (dtd->in_eldecl
&& ! parser->m_groupConnector[parser->m_prologState.level]
&& (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
!= XML_CTYPE_MIXED)) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_CHOICE;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
break;
case XML_ROLE_PARAM_ENTITY_REF:
#ifdef XML_DTD
case XML_ROLE_INNER_PARAM_ENTITY_REF:
dtd->hasParamEntityRefs = XML_TRUE;
if (! parser->m_paramEntityParsing)
dtd->keepProcessing = dtd->standalone;
else {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&dtd->pool);
/* first, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity handler
*/
if (parser->m_prologState.documentEntity
&& (dtd->standalone ? ! parser->m_openInternalEntities
: ! dtd->hasParamEntityRefs)) {
if (! entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (! entity->is_internal) {
/* It's hard to exhaustively search the code to be sure,
* but there doesn't seem to be a way of executing the
* following line. There are two cases:
*
* If 'standalone' is false, the DTD must have no
* parameter entities or we wouldn't have passed the outer
* 'if' statement. That measn the only entity in the hash
* table is the external subset name "#" which cannot be
* given as a parameter entity name in XML syntax, so the
* lookup must have returned NULL and we don't even reach
* the test for an internal entity.
*
* If 'standalone' is true, it does not seem to be
* possible to create entities taking this code path that
* are not internal entities, so fail the test above.
*
* Because this analysis is very uncertain, the code is
* being left in place and merely removed from the
* coverage test statistics.
*/
return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
}
} else if (! entity) {
dtd->keepProcessing = dtd->standalone;
/* cannot report skipped entities in declarations */
if ((role == XML_ROLE_PARAM_ENTITY_REF)
&& parser->m_skippedEntityHandler) {
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
handleDefault = XML_FALSE;
}
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
XML_Bool betweenDecl
= (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
result = processInternalEntity(parser, entity, betweenDecl);
if (result != XML_ERROR_NONE)
return result;
handleDefault = XML_FALSE;
break;
}
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId)) {
entity->open = XML_FALSE;
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
entity->open = XML_FALSE;
handleDefault = XML_FALSE;
if (! dtd->paramEntityRead) {
dtd->keepProcessing = dtd->standalone;
break;
}
} else {
dtd->keepProcessing = dtd->standalone;
break;
}
}
#endif /* XML_DTD */
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
break;
/* Element declaration stuff */
case XML_ROLE_ELEMENT_NAME:
if (parser->m_elementDeclHandler) {
parser->m_declElementType = getElementType(parser, enc, s, next);
if (! parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
dtd->scaffLevel = 0;
dtd->scaffCount = 0;
dtd->in_eldecl = XML_TRUE;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ANY:
case XML_ROLE_CONTENT_EMPTY:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler) {
XML_Content *content
= (XML_Content *)MALLOC(parser, sizeof(XML_Content));
if (! content)
return XML_ERROR_NO_MEMORY;
content->quant = XML_CQUANT_NONE;
content->name = NULL;
content->numchildren = 0;
content->children = NULL;
content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY
: XML_CTYPE_EMPTY);
*eventEndPP = s;
parser->m_elementDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name, content);
handleDefault = XML_FALSE;
}
dtd->in_eldecl = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_PCDATA:
if (dtd->in_eldecl) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_MIXED;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ELEMENT:
quant = XML_CQUANT_NONE;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_OPT:
quant = XML_CQUANT_OPT;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_REP:
quant = XML_CQUANT_REP;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_PLUS:
quant = XML_CQUANT_PLUS;
elementContent:
if (dtd->in_eldecl) {
ELEMENT_TYPE *el;
const XML_Char *name;
int nameLen;
const char *nxt
= (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
dtd->scaffold[myindex].type = XML_CTYPE_NAME;
dtd->scaffold[myindex].quant = quant;
el = getElementType(parser, enc, s, nxt);
if (! el)
return XML_ERROR_NO_MEMORY;
name = el->name;
dtd->scaffold[myindex].name = name;
nameLen = 0;
for (; name[nameLen++];)
;
dtd->contentStringLen += nameLen;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_CLOSE:
quant = XML_CQUANT_NONE;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_OPT:
quant = XML_CQUANT_OPT;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_REP:
quant = XML_CQUANT_REP;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_PLUS:
quant = XML_CQUANT_PLUS;
closeGroup:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
dtd->scaffLevel--;
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
if (dtd->scaffLevel == 0) {
if (! handleDefault) {
XML_Content *model = build_model(parser);
if (! model)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_elementDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name, model);
}
dtd->in_eldecl = XML_FALSE;
dtd->contentStringLen = 0;
}
}
break;
/* End element declaration stuff */
case XML_ROLE_PI:
if (! reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_COMMENT:
if (! reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_NONE:
switch (tok) {
case XML_TOK_BOM:
handleDefault = XML_FALSE;
break;
}
break;
case XML_ROLE_DOCTYPE_NONE:
if (parser->m_startDoctypeDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ENTITY_NONE:
if (dtd->keepProcessing && parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_NOTATION_NONE:
if (parser->m_notationDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTLIST_NONE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ELEMENT_NONE:
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
} /* end of big switch */
if (handleDefault && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
s = next;
tok = XmlPrologTok(enc, s, end, &next);
}
}
/* not reached */
}
static enum XML_Error PTRCALL
epilogProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
parser->m_processor = epilogProcessor;
parser->m_eventPtr = s;
for (;;) {
const char *next = NULL;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
/* report partial linebreak - it might be the last token */
case -XML_TOK_PROLOG_S:
if (parser->m_defaultHandler) {
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
}
*nextPtr = next;
return XML_ERROR_NONE;
case XML_TOK_NONE:
*nextPtr = s;
return XML_ERROR_NONE;
case XML_TOK_PROLOG_S:
if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
break;
case XML_TOK_PI:
if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (! reportComment(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_INVALID:
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (! parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (! parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
default:
return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
}
parser->m_eventPtr = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:;
}
}
}
static enum XML_Error
processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
} else {
openEntity
= (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (! openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE, XML_FALSE);
} else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
static enum XML_Error PTRCALL
internalEntityProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
ENTITY *entity;
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
if (! openEntity)
return XML_ERROR_UNEXPECTED_STATE;
entity = openEntity->entity;
textStart = ((char *)entity->textPtr) + entity->processed;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE, XML_TRUE);
} else
#endif /* XML_DTD */
result = doContent(parser, openEntity->startTagLevel,
parser->m_internalEncoding, textStart, textEnd, &next,
XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
else if (textEnd != next
&& parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - (char *)entity->textPtr);
return result;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
#ifdef XML_DTD
if (entity->is_param) {
int tok;
parser->m_processor = prologProcessor;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
} else
#endif /* XML_DTD */
{
parser->m_processor = contentProcessor;
/* see externalEntityContentProcessor vs contentProcessor */
return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding,
s, end, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
}
}
static enum XML_Error PTRCALL
errorProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
UNUSED_P(s);
UNUSED_P(end);
UNUSED_P(nextPtr);
return parser->m_errorCode;
}
static enum XML_Error
storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end, STRING_POOL *pool) {
enum XML_Error result
= appendAttributeValue(parser, enc, isCdata, ptr, end, pool);
if (result)
return result;
if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
poolChop(pool);
if (! poolAppendChar(pool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
return XML_ERROR_NONE;
}
static enum XML_Error
appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end, STRING_POOL *pool) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
for (;;) {
const char *next;
int tok = XmlAttributeValueTok(enc, ptr, end, &next);
switch (tok) {
case XML_TOK_NONE:
return XML_ERROR_NONE;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_CHAR_REF: {
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, ptr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BAD_CHAR_REF;
}
if (! isCdata && n == 0x20 /* space */
&& (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (! poolAppendChar(pool, buf[i]))
return XML_ERROR_NO_MEMORY;
}
} break;
case XML_TOK_DATA_CHARS:
if (! poolAppend(pool, enc, ptr, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_TRAILING_CR:
next = ptr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_ATTRIBUTE_VALUE_S:
case XML_TOK_DATA_NEWLINE:
if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
if (! poolAppendChar(pool, 0x20))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_ENTITY_REF: {
const XML_Char *name;
ENTITY *entity;
char checkEntityDecl;
XML_Char ch = (XML_Char)XmlPredefinedEntityName(
enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);
if (ch) {
if (! poolAppendChar(pool, ch))
return XML_ERROR_NO_MEMORY;
break;
}
name = poolStoreString(&parser->m_temp2Pool, enc,
ptr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&parser->m_temp2Pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal.
*/
if (pool == &dtd->pool) /* are we called from prolog? */
checkEntityDecl =
#ifdef XML_DTD
parser->m_prologState.documentEntity &&
#endif /* XML_DTD */
(dtd->standalone ? ! parser->m_openInternalEntities
: ! dtd->hasParamEntityRefs);
else /* if (pool == &parser->m_tempPool): we are called from content */
checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;
if (checkEntityDecl) {
if (! entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (! entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
} else if (! entity) {
/* Cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler.
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
/* Cannot call the default handler because this would be
out of sync with the call to the startElementHandler.
if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
reportDefault(parser, enc, ptr, next);
*/
break;
}
if (entity->open) {
if (enc == parser->m_encoding) {
/* It does not appear that this line can be executed.
*
* The "if (entity->open)" check catches recursive entity
* definitions. In order to be called with an open
* entity, it must have gone through this code before and
* been through the recursive call to
* appendAttributeValue() some lines below. That call
* sets the local encoding ("enc") to the parser's
* internal encoding (internal_utf8 or internal_utf16),
* which can never be the same as the principle encoding.
* It doesn't appear there is another code path that gets
* here with entity->open being TRUE.
*
* Since it is not certain that this logic is watertight,
* we keep the line and merely exclude it from coverage
* tests.
*/
parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
}
return XML_ERROR_RECURSIVE_ENTITY_REF;
}
if (entity->notation) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BINARY_ENTITY_REF;
}
if (! entity->textPtr) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
} else {
enum XML_Error result;
const XML_Char *textEnd = entity->textPtr + entity->textLen;
entity->open = XML_TRUE;
result = appendAttributeValue(parser, parser->m_internalEncoding,
isCdata, (char *)entity->textPtr,
(char *)textEnd, pool);
entity->open = XML_FALSE;
if (result)
return result;
}
} break;
default:
/* The only token returned by XmlAttributeValueTok() that does
* not have an explicit case here is XML_TOK_PARTIAL_CHAR.
* Getting that would require an entity name to contain an
* incomplete XML character (e.g. \xE2\x82); however previous
* tokenisers will have already recognised and rejected such
* names before XmlAttributeValueTok() gets a look-in. This
* default case should be retained as a safety net, but the code
* excluded from coverage tests.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
ptr = next;
}
/* not reached */
}
static enum XML_Error
storeEntityValue(XML_Parser parser, const ENCODING *enc,
const char *entityTextPtr, const char *entityTextEnd) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
STRING_POOL *pool = &(dtd->entityValuePool);
enum XML_Error result = XML_ERROR_NONE;
#ifdef XML_DTD
int oldInEntityValue = parser->m_prologState.inEntityValue;
parser->m_prologState.inEntityValue = 1;
#endif /* XML_DTD */
/* never return Null for the value argument in EntityDeclHandler,
since this would indicate an external entity; therefore we
have to make sure that entityValuePool.start is not null */
if (! pool->blocks) {
if (! poolGrow(pool))
return XML_ERROR_NO_MEMORY;
}
for (;;) {
const char *next;
int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
#ifdef XML_DTD
if (parser->m_isParamEntity || enc != parser->m_encoding) {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&parser->m_tempPool, enc,
entityTextPtr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&parser->m_tempPool);
if (! entity) {
/* not a well-formedness error - see XML 1.0: WFC Entity Declared */
/* cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
dtd->keepProcessing = dtd->standalone;
goto endEntityValue;
}
if (entity->open) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_RECURSIVE_ENTITY_REF;
goto endEntityValue;
}
if (entity->systemId) {
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId)) {
entity->open = XML_FALSE;
result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
goto endEntityValue;
}
entity->open = XML_FALSE;
if (! dtd->paramEntityRead)
dtd->keepProcessing = dtd->standalone;
} else
dtd->keepProcessing = dtd->standalone;
} else {
entity->open = XML_TRUE;
result = storeEntityValue(
parser, parser->m_internalEncoding, (char *)entity->textPtr,
(char *)(entity->textPtr + entity->textLen));
entity->open = XML_FALSE;
if (result)
goto endEntityValue;
}
break;
}
#endif /* XML_DTD */
/* In the internal subset, PE references are not legal
within markup declarations, e.g entity values in this case. */
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_PARAM_ENTITY_REF;
goto endEntityValue;
case XML_TOK_NONE:
result = XML_ERROR_NONE;
goto endEntityValue;
case XML_TOK_ENTITY_REF:
case XML_TOK_DATA_CHARS:
if (! poolAppend(pool, enc, entityTextPtr, next)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
break;
case XML_TOK_TRAILING_CR:
next = entityTextPtr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_DATA_NEWLINE:
if (pool->end == pool->ptr && ! poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = 0xA;
break;
case XML_TOK_CHAR_REF: {
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, entityTextPtr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_BAD_CHAR_REF;
goto endEntityValue;
}
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (pool->end == pool->ptr && ! poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = buf[i];
}
} break;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
default:
/* This default case should be unnecessary -- all the tokens
* that XmlEntityValueTok() can return have their own explicit
* cases -- but should be retained for safety. We do however
* exclude it from the coverage statistics.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_UNEXPECTED_STATE;
goto endEntityValue;
/* LCOV_EXCL_STOP */
}
entityTextPtr = next;
}
endEntityValue:
#ifdef XML_DTD
parser->m_prologState.inEntityValue = oldInEntityValue;
#endif /* XML_DTD */
return result;
}
static void FASTCALL
normalizeLines(XML_Char *s) {
XML_Char *p;
for (;; s++) {
if (*s == XML_T('\0'))
return;
if (*s == 0xD)
break;
}
p = s;
do {
if (*s == 0xD) {
*p++ = 0xA;
if (*++s == 0xA)
s++;
} else
*p++ = *s++;
} while (*s);
*p = XML_T('\0');
}
static int
reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end) {
const XML_Char *target;
XML_Char *data;
const char *tem;
if (! parser->m_processingInstructionHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
start += enc->minBytesPerChar * 2;
tem = start + XmlNameLength(enc, start);
target = poolStoreString(&parser->m_tempPool, enc, start, tem);
if (! target)
return 0;
poolFinish(&parser->m_tempPool);
data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),
end - enc->minBytesPerChar * 2);
if (! data)
return 0;
normalizeLines(data);
parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
poolClear(&parser->m_tempPool);
return 1;
}
static int
reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end) {
XML_Char *data;
if (! parser->m_commentHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
data = poolStoreString(&parser->m_tempPool, enc,
start + enc->minBytesPerChar * 4,
end - enc->minBytesPerChar * 3);
if (! data)
return 0;
normalizeLines(data);
parser->m_commentHandler(parser->m_handlerArg, data);
poolClear(&parser->m_tempPool);
return 1;
}
static void
reportDefault(XML_Parser parser, const ENCODING *enc, const char *s,
const char *end) {
if (MUST_CONVERT(enc, s)) {
enum XML_Convert_Result convert_res;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
} else {
/* To get here, two things must be true; the parser must be
* using a character encoding that is not the same as the
* encoding passed in, and the encoding passed in must need
* conversion to the internal format (UTF-8 unless XML_UNICODE
* is defined). The only occasions on which the encoding passed
* in is not the same as the parser's encoding are when it is
* the internal encoding (e.g. a previously defined parameter
* entity, already converted to internal format). This by
* definition doesn't need conversion, so the whole branch never
* gets executed.
*
* For safety's sake we don't delete these lines and merely
* exclude them from coverage statistics.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
do {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
convert_res
= XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
*eventPP = s;
} while ((convert_res != XML_CONVERT_COMPLETED)
&& (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
} else
parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s,
(int)((XML_Char *)end - (XML_Char *)s));
}
static int
defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
XML_Bool isId, const XML_Char *value, XML_Parser parser) {
DEFAULT_ATTRIBUTE *att;
if (value || isId) {
/* The handling of default attributes gets messed up if we have
a default which duplicates a non-default. */
int i;
for (i = 0; i < type->nDefaultAtts; i++)
if (attId == type->defaultAtts[i].id)
return 1;
if (isId && ! type->idAtt && ! attId->xmlns)
type->idAtt = attId;
}
if (type->nDefaultAtts == type->allocDefaultAtts) {
if (type->allocDefaultAtts == 0) {
type->allocDefaultAtts = 8;
type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(
parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
if (! type->defaultAtts) {
type->allocDefaultAtts = 0;
return 0;
}
} else {
DEFAULT_ATTRIBUTE *temp;
int count = type->allocDefaultAtts * 2;
temp = (DEFAULT_ATTRIBUTE *)REALLOC(parser, type->defaultAtts,
(count * sizeof(DEFAULT_ATTRIBUTE)));
if (temp == NULL)
return 0;
type->allocDefaultAtts = count;
type->defaultAtts = temp;
}
}
att = type->defaultAtts + type->nDefaultAtts;
att->id = attId;
att->value = value;
att->isCdata = isCdata;
if (! isCdata)
attId->maybeTokenized = XML_TRUE;
type->nDefaultAtts += 1;
return 1;
}
static int
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
PREFIX *prefix;
const XML_Char *s;
for (s = elementType->name; s != name; s++) {
if (! poolAppendChar(&dtd->pool, *s))
return 0;
}
if (! poolAppendChar(&dtd->pool, XML_T('\0')))
return 0;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (! prefix)
return 0;
if (prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
break;
}
}
return 1;
}
static ATTRIBUTE_ID *
getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
ATTRIBUTE_ID *id;
const XML_Char *name;
if (! poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
name = poolStoreString(&dtd->pool, enc, start, end);
if (! name)
return NULL;
/* skip quotation mark - its storage will be re-used (like in name[-1]) */
++name;
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,
sizeof(ATTRIBUTE_ID));
if (! id)
return NULL;
if (id->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (! parser->m_ns)
;
else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)
&& name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)
&& name[4] == XML_T(ASCII_s)
&& (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
if (name[5] == XML_T('\0'))
id->prefix = &dtd->defaultPrefix;
else
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,
sizeof(PREFIX));
id->xmlns = XML_TRUE;
} else {
int i;
for (i = 0; name[i]; i++) {
/* attributes without prefix are *not* in the default namespace */
if (name[i] == XML_T(ASCII_COLON)) {
int j;
for (j = 0; j < i; j++) {
if (! poolAppendChar(&dtd->pool, name[j]))
return NULL;
}
if (! poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,
poolStart(&dtd->pool), sizeof(PREFIX));
if (! id->prefix)
return NULL;
if (id->prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
break;
}
}
}
}
return id;
}
#define CONTEXT_SEP XML_T(ASCII_FF)
static const XML_Char *
getContext(XML_Parser parser) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
HASH_TABLE_ITER iter;
XML_Bool needSep = XML_FALSE;
if (dtd->defaultPrefix.binding) {
int i;
int len;
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = dtd->defaultPrefix.binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++) {
if (! poolAppendChar(&parser->m_tempPool,
dtd->defaultPrefix.binding->uri[i])) {
/* Because of memory caching, I don't believe this line can be
* executed.
*
* This is part of a loop copying the default prefix binding
* URI into the parser's temporary string pool. Previously,
* that URI was copied into the same string pool, with a
* terminating NUL character, as part of setContext(). When
* the pool was cleared, that leaves a block definitely big
* enough to hold the URI on the free block list of the pool.
* The URI copy in getContext() therefore cannot run out of
* memory.
*
* If the pool is used between the setContext() and
* getContext() calls, the worst it can do is leave a bigger
* block on the front of the free list. Given that this is
* all somewhat inobvious and program logic can be changed, we
* don't delete the line but we do exclude it from the test
* coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
}
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->prefixes));
for (;;) {
int i;
int len;
const XML_Char *s;
PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
if (! prefix)
break;
if (! prefix->binding) {
/* This test appears to be (justifiable) paranoia. There does
* not seem to be a way of injecting a prefix without a binding
* that doesn't get errored long before this function is called.
* The test should remain for safety's sake, so we instead
* exclude the following line from the coverage statistics.
*/
continue; /* LCOV_EXCL_LINE */
}
if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = prefix->name; *s; s++)
if (! poolAppendChar(&parser->m_tempPool, *s))
return NULL;
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = prefix->binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++)
if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
return NULL;
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->generalEntities));
for (;;) {
const XML_Char *s;
ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
if (! e)
break;
if (! e->open)
continue;
if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = e->name; *s; s++)
if (! poolAppendChar(&parser->m_tempPool, *s))
return 0;
needSep = XML_TRUE;
}
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return NULL;
return parser->m_tempPool.start;
}
static XML_Bool
setContext(XML_Parser parser, const XML_Char *context) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *s = context;
while (*context != XML_T('\0')) {
if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
ENTITY *e;
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
e = (ENTITY *)lookup(parser, &dtd->generalEntities,
poolStart(&parser->m_tempPool), 0);
if (e)
e->open = XML_TRUE;
if (*s != XML_T('\0'))
s++;
context = s;
poolDiscard(&parser->m_tempPool);
} else if (*s == XML_T(ASCII_EQUALS)) {
PREFIX *prefix;
if (poolLength(&parser->m_tempPool) == 0)
prefix = &dtd->defaultPrefix;
else {
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
prefix
= (PREFIX *)lookup(parser, &dtd->prefixes,
poolStart(&parser->m_tempPool), sizeof(PREFIX));
if (! prefix)
return XML_FALSE;
if (prefix->name == poolStart(&parser->m_tempPool)) {
prefix->name = poolCopyString(&dtd->pool, prefix->name);
if (! prefix->name)
return XML_FALSE;
}
poolDiscard(&parser->m_tempPool);
}
for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\0');
context++)
if (! poolAppendChar(&parser->m_tempPool, *context))
return XML_FALSE;
if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
&parser->m_inheritedBindings)
!= XML_ERROR_NONE)
return XML_FALSE;
poolDiscard(&parser->m_tempPool);
if (*context != XML_T('\0'))
++context;
s = context;
} else {
if (! poolAppendChar(&parser->m_tempPool, *s))
return XML_FALSE;
s++;
}
}
return XML_TRUE;
}
static void FASTCALL
normalizePublicId(XML_Char *publicId) {
XML_Char *p = publicId;
XML_Char *s;
for (s = publicId; *s; s++) {
switch (*s) {
case 0x20:
case 0xD:
case 0xA:
if (p != publicId && p[-1] != 0x20)
*p++ = 0x20;
break;
default:
*p++ = *s;
}
}
if (p != publicId && p[-1] == 0x20)
--p;
*p = XML_T('\0');
}
static DTD *
dtdCreate(const XML_Memory_Handling_Suite *ms) {
DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD));
if (p == NULL)
return p;
poolInit(&(p->pool), ms);
poolInit(&(p->entityValuePool), ms);
hashTableInit(&(p->generalEntities), ms);
hashTableInit(&(p->elementTypes), ms);
hashTableInit(&(p->attributeIds), ms);
hashTableInit(&(p->prefixes), ms);
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableInit(&(p->paramEntities), ms);
#endif /* XML_DTD */
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
p->scaffIndex = NULL;
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
return p;
}
static void
dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms) {
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (! e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableClear(&(p->generalEntities));
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableClear(&(p->paramEntities));
#endif /* XML_DTD */
hashTableClear(&(p->elementTypes));
hashTableClear(&(p->attributeIds));
hashTableClear(&(p->prefixes));
poolClear(&(p->pool));
poolClear(&(p->entityValuePool));
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
ms->free_fcn(p->scaffIndex);
p->scaffIndex = NULL;
ms->free_fcn(p->scaffold);
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
}
static void
dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms) {
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (! e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableDestroy(&(p->generalEntities));
#ifdef XML_DTD
hashTableDestroy(&(p->paramEntities));
#endif /* XML_DTD */
hashTableDestroy(&(p->elementTypes));
hashTableDestroy(&(p->attributeIds));
hashTableDestroy(&(p->prefixes));
poolDestroy(&(p->pool));
poolDestroy(&(p->entityValuePool));
if (isDocEntity) {
ms->free_fcn(p->scaffIndex);
ms->free_fcn(p->scaffold);
}
ms->free_fcn(p);
}
/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
The new DTD has already been initialized.
*/
static int
dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
const XML_Memory_Handling_Suite *ms) {
HASH_TABLE_ITER iter;
/* Copy the prefix table. */
hashTableIterInit(&iter, &(oldDtd->prefixes));
for (;;) {
const XML_Char *name;
const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
if (! oldP)
break;
name = poolCopyString(&(newDtd->pool), oldP->name);
if (! name)
return 0;
if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
return 0;
}
hashTableIterInit(&iter, &(oldDtd->attributeIds));
/* Copy the attribute id table. */
for (;;) {
ATTRIBUTE_ID *newA;
const XML_Char *name;
const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
if (! oldA)
break;
/* Remember to allocate the scratch byte before the name. */
if (! poolAppendChar(&(newDtd->pool), XML_T('\0')))
return 0;
name = poolCopyString(&(newDtd->pool), oldA->name);
if (! name)
return 0;
++name;
newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
sizeof(ATTRIBUTE_ID));
if (! newA)
return 0;
newA->maybeTokenized = oldA->maybeTokenized;
if (oldA->prefix) {
newA->xmlns = oldA->xmlns;
if (oldA->prefix == &oldDtd->defaultPrefix)
newA->prefix = &newDtd->defaultPrefix;
else
newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldA->prefix->name, 0);
}
}
/* Copy the element type table. */
hashTableIterInit(&iter, &(oldDtd->elementTypes));
for (;;) {
int i;
ELEMENT_TYPE *newE;
const XML_Char *name;
const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (! oldE)
break;
name = poolCopyString(&(newDtd->pool), oldE->name);
if (! name)
return 0;
newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
sizeof(ELEMENT_TYPE));
if (! newE)
return 0;
if (oldE->nDefaultAtts) {
newE->defaultAtts = (DEFAULT_ATTRIBUTE *)ms->malloc_fcn(
oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
if (! newE->defaultAtts) {
return 0;
}
}
if (oldE->idAtt)
newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),
oldE->idAtt->name, 0);
newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
if (oldE->prefix)
newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldE->prefix->name, 0);
for (i = 0; i < newE->nDefaultAtts; i++) {
newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(
oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
if (oldE->defaultAtts[i].value) {
newE->defaultAtts[i].value
= poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
if (! newE->defaultAtts[i].value)
return 0;
} else
newE->defaultAtts[i].value = NULL;
}
}
/* Copy the entity tables. */
if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),
&(oldDtd->generalEntities)))
return 0;
#ifdef XML_DTD
if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),
&(oldDtd->paramEntities)))
return 0;
newDtd->paramEntityRead = oldDtd->paramEntityRead;
#endif /* XML_DTD */
newDtd->keepProcessing = oldDtd->keepProcessing;
newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
newDtd->standalone = oldDtd->standalone;
/* Don't want deep copying for scaffolding */
newDtd->in_eldecl = oldDtd->in_eldecl;
newDtd->scaffold = oldDtd->scaffold;
newDtd->contentStringLen = oldDtd->contentStringLen;
newDtd->scaffSize = oldDtd->scaffSize;
newDtd->scaffLevel = oldDtd->scaffLevel;
newDtd->scaffIndex = oldDtd->scaffIndex;
return 1;
} /* End dtdCopy */
static int
copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
STRING_POOL *newPool, const HASH_TABLE *oldTable) {
HASH_TABLE_ITER iter;
const XML_Char *cachedOldBase = NULL;
const XML_Char *cachedNewBase = NULL;
hashTableIterInit(&iter, oldTable);
for (;;) {
ENTITY *newE;
const XML_Char *name;
const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
if (! oldE)
break;
name = poolCopyString(newPool, oldE->name);
if (! name)
return 0;
newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
if (! newE)
return 0;
if (oldE->systemId) {
const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
if (! tem)
return 0;
newE->systemId = tem;
if (oldE->base) {
if (oldE->base == cachedOldBase)
newE->base = cachedNewBase;
else {
cachedOldBase = oldE->base;
tem = poolCopyString(newPool, cachedOldBase);
if (! tem)
return 0;
cachedNewBase = newE->base = tem;
}
}
if (oldE->publicId) {
tem = poolCopyString(newPool, oldE->publicId);
if (! tem)
return 0;
newE->publicId = tem;
}
} else {
const XML_Char *tem
= poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);
if (! tem)
return 0;
newE->textPtr = tem;
newE->textLen = oldE->textLen;
}
if (oldE->notation) {
const XML_Char *tem = poolCopyString(newPool, oldE->notation);
if (! tem)
return 0;
newE->notation = tem;
}
newE->is_param = oldE->is_param;
newE->is_internal = oldE->is_internal;
}
return 1;
}
#define INIT_POWER 6
static XML_Bool FASTCALL
keyeq(KEY s1, KEY s2) {
for (; *s1 == *s2; s1++, s2++)
if (*s1 == 0)
return XML_TRUE;
return XML_FALSE;
}
static size_t
keylen(KEY s) {
size_t len = 0;
for (; *s; s++, len++)
;
return len;
}
static void
copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {
key->k[0] = 0;
key->k[1] = get_hash_secret_salt(parser);
}
static unsigned long FASTCALL
hash(XML_Parser parser, KEY s) {
struct siphash state;
struct sipkey key;
(void)sip24_valid;
copy_salt_to_sipkey(parser, &key);
sip24_init(&state, &key);
sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
return (unsigned long)sip24_final(&state);
}
static NAMED *
lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {
size_t i;
if (table->size == 0) {
size_t tsize;
if (! createSize)
return NULL;
table->power = INIT_POWER;
/* table->size is a power of 2 */
table->size = (size_t)1 << INIT_POWER;
tsize = table->size * sizeof(NAMED *);
table->v = (NAMED **)table->mem->malloc_fcn(tsize);
if (! table->v) {
table->size = 0;
return NULL;
}
memset(table->v, 0, tsize);
i = hash(parser, name) & ((unsigned long)table->size - 1);
} else {
unsigned long h = hash(parser, name);
unsigned long mask = (unsigned long)table->size - 1;
unsigned char step = 0;
i = h & mask;
while (table->v[i]) {
if (keyeq(name, table->v[i]->name))
return table->v[i];
if (! step)
step = PROBE_STEP(h, mask, table->power);
i < step ? (i += table->size - step) : (i -= step);
}
if (! createSize)
return NULL;
/* check for overflow (table is half full) */
if (table->used >> (table->power - 1)) {
unsigned char newPower = table->power + 1;
size_t newSize = (size_t)1 << newPower;
unsigned long newMask = (unsigned long)newSize - 1;
size_t tsize = newSize * sizeof(NAMED *);
NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize);
if (! newV)
return NULL;
memset(newV, 0, tsize);
for (i = 0; i < table->size; i++)
if (table->v[i]) {
unsigned long newHash = hash(parser, table->v[i]->name);
size_t j = newHash & newMask;
step = 0;
while (newV[j]) {
if (! step)
step = PROBE_STEP(newHash, newMask, newPower);
j < step ? (j += newSize - step) : (j -= step);
}
newV[j] = table->v[i];
}
table->mem->free_fcn(table->v);
table->v = newV;
table->power = newPower;
table->size = newSize;
i = h & newMask;
step = 0;
while (table->v[i]) {
if (! step)
step = PROBE_STEP(h, newMask, newPower);
i < step ? (i += newSize - step) : (i -= step);
}
}
}
table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize);
if (! table->v[i])
return NULL;
memset(table->v[i], 0, createSize);
table->v[i]->name = name;
(table->used)++;
return table->v[i];
}
static void FASTCALL
hashTableClear(HASH_TABLE *table) {
size_t i;
for (i = 0; i < table->size; i++) {
table->mem->free_fcn(table->v[i]);
table->v[i] = NULL;
}
table->used = 0;
}
static void FASTCALL
hashTableDestroy(HASH_TABLE *table) {
size_t i;
for (i = 0; i < table->size; i++)
table->mem->free_fcn(table->v[i]);
table->mem->free_fcn(table->v);
}
static void FASTCALL
hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms) {
p->power = 0;
p->size = 0;
p->used = 0;
p->v = NULL;
p->mem = ms;
}
static void FASTCALL
hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {
iter->p = table->v;
iter->end = iter->p + table->size;
}
static NAMED *FASTCALL
hashTableIterNext(HASH_TABLE_ITER *iter) {
while (iter->p != iter->end) {
NAMED *tem = *(iter->p)++;
if (tem)
return tem;
}
return NULL;
}
static void FASTCALL
poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) {
pool->blocks = NULL;
pool->freeBlocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
pool->mem = ms;
}
static void FASTCALL
poolClear(STRING_POOL *pool) {
if (! pool->freeBlocks)
pool->freeBlocks = pool->blocks;
else {
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
p->next = pool->freeBlocks;
pool->freeBlocks = p;
p = tem;
}
}
pool->blocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
}
static void FASTCALL
poolDestroy(STRING_POOL *pool) {
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
p = pool->freeBlocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
}
static XML_Char *
poolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
const char *end) {
if (! pool->ptr && ! poolGrow(pool))
return NULL;
for (;;) {
const enum XML_Convert_Result convert_res = XmlConvert(
enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
if ((convert_res == XML_CONVERT_COMPLETED)
|| (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
if (! poolGrow(pool))
return NULL;
}
return pool->start;
}
static const XML_Char *FASTCALL
poolCopyString(STRING_POOL *pool, const XML_Char *s) {
do {
if (! poolAppendChar(pool, *s))
return NULL;
} while (*s++);
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char *
poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {
if (! pool->ptr && ! poolGrow(pool)) {
/* The following line is unreachable given the current usage of
* poolCopyStringN(). Currently it is called from exactly one
* place to copy the text of a simple general entity. By that
* point, the name of the entity is already stored in the pool, so
* pool->ptr cannot be NULL.
*
* If poolCopyStringN() is used elsewhere as it well might be,
* this line may well become executable again. Regardless, this
* sort of check shouldn't be removed lightly, so we just exclude
* it from the coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
for (; n > 0; --n, s++) {
if (! poolAppendChar(pool, *s))
return NULL;
}
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char *FASTCALL
poolAppendString(STRING_POOL *pool, const XML_Char *s) {
while (*s) {
if (! poolAppendChar(pool, *s))
return NULL;
s++;
}
return pool->start;
}
static XML_Char *
poolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
const char *end) {
if (! poolAppend(pool, enc, ptr, end))
return NULL;
if (pool->ptr == pool->end && ! poolGrow(pool))
return NULL;
*(pool->ptr)++ = 0;
return pool->start;
}
static size_t
poolBytesToAllocateFor(int blockSize) {
/* Unprotected math would be:
** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
**
** Detect overflow, avoiding _signed_ overflow undefined behavior
** For a + b * c we check b * c in isolation first, so that addition of a
** on top has no chance of making us accept a small non-negative number
*/
const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
if (blockSize <= 0)
return 0;
if (blockSize > (int)(INT_MAX / stretch))
return 0;
{
const int stretchedBlockSize = blockSize * (int)stretch;
const int bytesToAllocate
= (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
if (bytesToAllocate < 0)
return 0;
return (size_t)bytesToAllocate;
}
}
static XML_Bool FASTCALL
poolGrow(STRING_POOL *pool) {
if (pool->freeBlocks) {
if (pool->start == 0) {
pool->blocks = pool->freeBlocks;
pool->freeBlocks = pool->freeBlocks->next;
pool->blocks->next = NULL;
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
pool->ptr = pool->start;
return XML_TRUE;
}
if (pool->end - pool->start < pool->freeBlocks->size) {
BLOCK *tem = pool->freeBlocks->next;
pool->freeBlocks->next = pool->blocks;
pool->blocks = pool->freeBlocks;
pool->freeBlocks = tem;
memcpy(pool->blocks->s, pool->start,
(pool->end - pool->start) * sizeof(XML_Char));
pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
return XML_TRUE;
}
}
if (pool->blocks && pool->start == pool->blocks->s) {
BLOCK *temp;
int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);
size_t bytesToAllocate;
/* NOTE: Needs to be calculated prior to calling `realloc`
to avoid dangling pointers: */
const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX/2 bytes have already been allocated. This isn't
* readily testable, since it is unlikely that an average
* machine will have that much memory, so we exclude it from the
* coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
temp = (BLOCK *)pool->mem->realloc_fcn(pool->blocks,
(unsigned)bytesToAllocate);
if (temp == NULL)
return XML_FALSE;
pool->blocks = temp;
pool->blocks->size = blockSize;
pool->ptr = pool->blocks->s + offsetInsideBlock;
pool->start = pool->blocks->s;
pool->end = pool->start + blockSize;
} else {
BLOCK *tem;
int blockSize = (int)(pool->end - pool->start);
size_t bytesToAllocate;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX bytes have already been allocated (which is prevented
* by various pieces of program logic, not least this one, never
* mind the unlikelihood of actually having that much memory) or
* the pool control fields have been corrupted (which could
* conceivably happen in an extremely buggy user handler
* function). Either way it isn't readily testable, so we
* exclude it from the coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
if (blockSize < INIT_BLOCK_SIZE)
blockSize = INIT_BLOCK_SIZE;
else {
/* Detect overflow, avoiding _signed_ overflow undefined behavior */
if ((int)((unsigned)blockSize * 2U) < 0) {
return XML_FALSE;
}
blockSize *= 2;
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate);
if (! tem)
return XML_FALSE;
tem->size = blockSize;
tem->next = pool->blocks;
pool->blocks = tem;
if (pool->ptr != pool->start)
memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));
pool->ptr = tem->s + (pool->ptr - pool->start);
pool->start = tem->s;
pool->end = tem->s + blockSize;
}
return XML_TRUE;
}
static int FASTCALL
nextScaffoldPart(XML_Parser parser) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
CONTENT_SCAFFOLD *me;
int next;
if (! dtd->scaffIndex) {
dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
if (! dtd->scaffIndex)
return -1;
dtd->scaffIndex[0] = 0;
}
if (dtd->scaffCount >= dtd->scaffSize) {
CONTENT_SCAFFOLD *temp;
if (dtd->scaffold) {
temp = (CONTENT_SCAFFOLD *)REALLOC(
parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize *= 2;
} else {
temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
* sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
}
dtd->scaffold = temp;
}
next = dtd->scaffCount++;
me = &dtd->scaffold[next];
if (dtd->scaffLevel) {
CONTENT_SCAFFOLD *parent
= &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];
if (parent->lastchild) {
dtd->scaffold[parent->lastchild].nextsib = next;
}
if (! parent->childcnt)
parent->firstchild = next;
parent->lastchild = next;
parent->childcnt++;
}
me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
return next;
}
static void
build_node(XML_Parser parser, int src_node, XML_Content *dest,
XML_Content **contpos, XML_Char **strpos) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
dest->type = dtd->scaffold[src_node].type;
dest->quant = dtd->scaffold[src_node].quant;
if (dest->type == XML_CTYPE_NAME) {
const XML_Char *src;
dest->name = *strpos;
src = dtd->scaffold[src_node].name;
for (;;) {
*(*strpos)++ = *src;
if (! *src)
break;
src++;
}
dest->numchildren = 0;
dest->children = NULL;
} else {
unsigned int i;
int cn;
dest->numchildren = dtd->scaffold[src_node].childcnt;
dest->children = *contpos;
*contpos += dest->numchildren;
for (i = 0, cn = dtd->scaffold[src_node].firstchild; i < dest->numchildren;
i++, cn = dtd->scaffold[cn].nextsib) {
build_node(parser, cn, &(dest->children[i]), contpos, strpos);
}
dest->name = NULL;
}
}
static XML_Content *
build_model(XML_Parser parser) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
XML_Content *ret;
XML_Content *cpos;
XML_Char *str;
int allocsize = (dtd->scaffCount * sizeof(XML_Content)
+ (dtd->contentStringLen * sizeof(XML_Char)));
ret = (XML_Content *)MALLOC(parser, allocsize);
if (! ret)
return NULL;
str = (XML_Char *)(&ret[dtd->scaffCount]);
cpos = &ret[1];
build_node(parser, 0, ret, &cpos, &str);
return ret;
}
static ELEMENT_TYPE *
getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,
const char *end) {
DTD *const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
ELEMENT_TYPE *ret;
if (! name)
return NULL;
ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
sizeof(ELEMENT_TYPE));
if (! ret)
return NULL;
if (ret->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (! setElementTypePrefix(parser, ret))
return NULL;
}
return ret;
}
static XML_Char *
copyString(const XML_Char *s, const XML_Memory_Handling_Suite *memsuite) {
int charsRequired = 0;
XML_Char *result;
/* First determine how long the string is */
while (s[charsRequired] != 0) {
charsRequired++;
}
/* Include the terminator */
charsRequired++;
/* Now allocate space for the copy */
result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
if (result == NULL)
return NULL;
/* Copy the original into place */
memcpy(result, s, charsRequired * sizeof(XML_Char));
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/good_1054_0 |
crossvul-cpp_data_bad_4362_3 | #include <xml_schema.h>
static void dealloc(xmlSchemaPtr schema)
{
NOKOGIRI_DEBUG_START(schema);
xmlSchemaFree(schema);
NOKOGIRI_DEBUG_END(schema);
}
/*
* call-seq:
* validate_document(document)
*
* Validate a Nokogiri::XML::Document against this Schema.
*/
static VALUE validate_document(VALUE self, VALUE document)
{
xmlDocPtr doc;
xmlSchemaPtr schema;
xmlSchemaValidCtxtPtr valid_ctxt;
VALUE errors;
Data_Get_Struct(self, xmlSchema, schema);
Data_Get_Struct(document, xmlDoc, doc);
errors = rb_ary_new();
valid_ctxt = xmlSchemaNewValidCtxt(schema);
if(NULL == valid_ctxt) {
/* we have a problem */
rb_raise(rb_eRuntimeError, "Could not create a validation context");
}
#ifdef HAVE_XMLSCHEMASETVALIDSTRUCTUREDERRORS
xmlSchemaSetValidStructuredErrors(
valid_ctxt,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
xmlSchemaValidateDoc(valid_ctxt, doc);
xmlSchemaFreeValidCtxt(valid_ctxt);
return errors;
}
/*
* call-seq:
* validate_file(filename)
*
* Validate a file against this Schema.
*/
static VALUE validate_file(VALUE self, VALUE rb_filename)
{
xmlSchemaPtr schema;
xmlSchemaValidCtxtPtr valid_ctxt;
const char *filename ;
VALUE errors;
Data_Get_Struct(self, xmlSchema, schema);
filename = (const char*)StringValueCStr(rb_filename) ;
errors = rb_ary_new();
valid_ctxt = xmlSchemaNewValidCtxt(schema);
if(NULL == valid_ctxt) {
/* we have a problem */
rb_raise(rb_eRuntimeError, "Could not create a validation context");
}
#ifdef HAVE_XMLSCHEMASETVALIDSTRUCTUREDERRORS
xmlSchemaSetValidStructuredErrors(
valid_ctxt,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
xmlSchemaValidateFile(valid_ctxt, filename, 0);
xmlSchemaFreeValidCtxt(valid_ctxt);
return errors;
}
/*
* call-seq:
* read_memory(string)
*
* Create a new Schema from the contents of +string+
*/
static VALUE read_memory(VALUE klass, VALUE content)
{
xmlSchemaPtr schema;
xmlSchemaParserCtxtPtr ctx = xmlSchemaNewMemParserCtxt(
(const char *)StringValuePtr(content),
(int)RSTRING_LEN(content)
);
VALUE rb_schema;
VALUE errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
xmlSchemaSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlSchemaParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlSchemaFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
return rb_schema;
}
/* Schema creation will remove and deallocate "blank" nodes.
* If those blank nodes have been exposed to Ruby, they could get freed
* out from under the VALUE pointer. This function checks to see if any of
* those nodes have been exposed to Ruby, and if so we should raise an exception.
*/
static int has_blank_nodes_p(VALUE cache)
{
long i;
if (NIL_P(cache)) {
return 0;
}
for (i = 0; i < RARRAY_LEN(cache); i++) {
xmlNodePtr node;
VALUE element = rb_ary_entry(cache, i);
Data_Get_Struct(element, xmlNode, node);
if (xmlIsBlankNode(node)) {
return 1;
}
}
return 0;
}
/*
* call-seq:
* from_document(doc)
*
* Create a new Schema from the Nokogiri::XML::Document +doc+
*/
static VALUE from_document(VALUE klass, VALUE document)
{
xmlDocPtr doc;
xmlSchemaParserCtxtPtr ctx;
xmlSchemaPtr schema;
VALUE errors;
VALUE rb_schema;
Data_Get_Struct(document, xmlDoc, doc);
/* In case someone passes us a node. ugh. */
doc = doc->doc;
if (has_blank_nodes_p(DOC_NODE_CACHE(doc))) {
rb_raise(rb_eArgError, "Creating a schema from a document that has blank nodes exposed to Ruby is dangerous");
}
ctx = xmlSchemaNewDocParserCtxt(doc);
errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
xmlSchemaSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlSchemaParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlSchemaFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
return rb_schema;
return Qnil;
}
VALUE cNokogiriXmlSchema;
void init_xml_schema()
{
VALUE nokogiri = rb_define_module("Nokogiri");
VALUE xml = rb_define_module_under(nokogiri, "XML");
VALUE klass = rb_define_class_under(xml, "Schema", rb_cObject);
cNokogiriXmlSchema = klass;
rb_define_singleton_method(klass, "read_memory", read_memory, 1);
rb_define_singleton_method(klass, "from_document", from_document, 1);
rb_define_private_method(klass, "validate_document", validate_document, 1);
rb_define_private_method(klass, "validate_file", validate_file, 1);
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/bad_4362_3 |
crossvul-cpp_data_good_537_0 | /* 19ac4776051591216f1874e34ee99b6a43a3784c8bd7d70efeb9258dd22b906a (2.2.6+)
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000-2017 Expat development team
Licensed under the MIT license:
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.
*/
#if !defined(_GNU_SOURCE)
# define _GNU_SOURCE 1 /* syscall prototype */
#endif
#include <stddef.h>
#include <string.h> /* memset(), memcpy() */
#include <assert.h>
#include <limits.h> /* UINT_MAX */
#include <stdio.h> /* fprintf */
#include <stdlib.h> /* getenv */
#ifdef _WIN32
#define getpid GetCurrentProcessId
#else
#include <sys/time.h> /* gettimeofday() */
#include <sys/types.h> /* getpid() */
#include <unistd.h> /* getpid() */
#include <fcntl.h> /* O_RDONLY */
#include <errno.h>
#endif
#define XML_BUILDING_EXPAT 1
#ifdef _WIN32
#include "winconfig.h"
#elif defined(HAVE_EXPAT_CONFIG_H)
#include <expat_config.h>
#endif /* ndef _WIN32 */
#include "ascii.h"
#include "expat.h"
#include "siphash.h"
#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
# if defined(HAVE_GETRANDOM)
# include <sys/random.h> /* getrandom */
# else
# include <unistd.h> /* syscall */
# include <sys/syscall.h> /* SYS_getrandom */
# endif
# if ! defined(GRND_NONBLOCK)
# define GRND_NONBLOCK 0x0001
# endif /* defined(GRND_NONBLOCK) */
#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
#if defined(HAVE_LIBBSD) \
&& (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
# include <bsd/stdlib.h>
#endif
#if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
#if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \
&& !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \
&& !defined(XML_DEV_URANDOM) \
&& !defined(_WIN32) \
&& !defined(XML_POOR_ENTROPY)
# error \
You do not have support for any sources of high quality entropy \
enabled. For end user security, that is probably not what you want. \
\
Your options include: \
* Linux + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
* Linux + glibc <2.25 (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
* BSD / macOS >=10.7 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
* BSD / macOS <10.7 (arc4random): HAVE_ARC4RANDOM, \
* libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
* libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
* Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \
* Windows (RtlGenRandom): _WIN32. \
\
If insist on not using any of these, bypass this error by defining \
XML_POOR_ENTROPY; you have been warned. \
\
If you have reasons to patch this detection code away or need changes \
to the build system, please open a bug. Thank you!
#endif
#ifdef XML_UNICODE
#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
#define XmlConvert XmlUtf16Convert
#define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
#define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
#define XmlEncode XmlUtf16Encode
/* Using pointer subtraction to convert to integer type. */
#define MUST_CONVERT(enc, s) (!(enc)->isUtf16 || (((char *)(s) - (char *)NULL) & 1))
typedef unsigned short ICHAR;
#else
#define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
#define XmlConvert XmlUtf8Convert
#define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
#define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
#define XmlEncode XmlUtf8Encode
#define MUST_CONVERT(enc, s) (!(enc)->isUtf8)
typedef char ICHAR;
#endif
#ifndef XML_NS
#define XmlInitEncodingNS XmlInitEncoding
#define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
#undef XmlGetInternalEncodingNS
#define XmlGetInternalEncodingNS XmlGetInternalEncoding
#define XmlParseXmlDeclNS XmlParseXmlDecl
#endif
#ifdef XML_UNICODE
#ifdef XML_UNICODE_WCHAR_T
#define XML_T(x) (const wchar_t)x
#define XML_L(x) L ## x
#else
#define XML_T(x) (const unsigned short)x
#define XML_L(x) x
#endif
#else
#define XML_T(x) x
#define XML_L(x) x
#endif
/* Round up n to be a multiple of sz, where sz is a power of 2. */
#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
/* Do safe (NULL-aware) pointer arithmetic */
#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
#include "internal.h"
#include "xmltok.h"
#include "xmlrole.h"
typedef const XML_Char *KEY;
typedef struct {
KEY name;
} NAMED;
typedef struct {
NAMED **v;
unsigned char power;
size_t size;
size_t used;
const XML_Memory_Handling_Suite *mem;
} HASH_TABLE;
static size_t
keylen(KEY s);
static void
copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key);
/* For probing (after a collision) we need a step size relative prime
to the hash table size, which is a power of 2. We use double-hashing,
since we can calculate a second hash value cheaply by taking those bits
of the first hash value that were discarded (masked out) when the table
index was calculated: index = hash & mask, where mask = table->size - 1.
We limit the maximum step size to table->size / 4 (mask >> 2) and make
it odd, since odd numbers are always relative prime to a power of 2.
*/
#define SECOND_HASH(hash, mask, power) \
((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2))
#define PROBE_STEP(hash, mask, power) \
((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
typedef struct {
NAMED **p;
NAMED **end;
} HASH_TABLE_ITER;
#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
#define INIT_DATA_BUF_SIZE 1024
#define INIT_ATTS_SIZE 16
#define INIT_ATTS_VERSION 0xFFFFFFFF
#define INIT_BLOCK_SIZE 1024
#define INIT_BUFFER_SIZE 1024
#define EXPAND_SPARE 24
typedef struct binding {
struct prefix *prefix;
struct binding *nextTagBinding;
struct binding *prevPrefixBinding;
const struct attribute_id *attId;
XML_Char *uri;
int uriLen;
int uriAlloc;
} BINDING;
typedef struct prefix {
const XML_Char *name;
BINDING *binding;
} PREFIX;
typedef struct {
const XML_Char *str;
const XML_Char *localPart;
const XML_Char *prefix;
int strLen;
int uriLen;
int prefixLen;
} TAG_NAME;
/* TAG represents an open element.
The name of the element is stored in both the document and API
encodings. The memory buffer 'buf' is a separately-allocated
memory area which stores the name. During the XML_Parse()/
XMLParseBuffer() when the element is open, the memory for the 'raw'
version of the name (in the document encoding) is shared with the
document buffer. If the element is open across calls to
XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to
contain the 'raw' name as well.
A parser re-uses these structures, maintaining a list of allocated
TAG objects in a free list.
*/
typedef struct tag {
struct tag *parent; /* parent of this element */
const char *rawName; /* tagName in the original encoding */
int rawNameLength;
TAG_NAME name; /* tagName in the API encoding */
char *buf; /* buffer for name components */
char *bufEnd; /* end of the buffer */
BINDING *bindings;
} TAG;
typedef struct {
const XML_Char *name;
const XML_Char *textPtr;
int textLen; /* length in XML_Chars */
int processed; /* # of processed bytes - when suspended */
const XML_Char *systemId;
const XML_Char *base;
const XML_Char *publicId;
const XML_Char *notation;
XML_Bool open;
XML_Bool is_param;
XML_Bool is_internal; /* true if declared in internal subset outside PE */
} ENTITY;
typedef struct {
enum XML_Content_Type type;
enum XML_Content_Quant quant;
const XML_Char * name;
int firstchild;
int lastchild;
int childcnt;
int nextsib;
} CONTENT_SCAFFOLD;
#define INIT_SCAFFOLD_ELEMENTS 32
typedef struct block {
struct block *next;
int size;
XML_Char s[1];
} BLOCK;
typedef struct {
BLOCK *blocks;
BLOCK *freeBlocks;
const XML_Char *end;
XML_Char *ptr;
XML_Char *start;
const XML_Memory_Handling_Suite *mem;
} STRING_POOL;
/* The XML_Char before the name is used to determine whether
an attribute has been specified. */
typedef struct attribute_id {
XML_Char *name;
PREFIX *prefix;
XML_Bool maybeTokenized;
XML_Bool xmlns;
} ATTRIBUTE_ID;
typedef struct {
const ATTRIBUTE_ID *id;
XML_Bool isCdata;
const XML_Char *value;
} DEFAULT_ATTRIBUTE;
typedef struct {
unsigned long version;
unsigned long hash;
const XML_Char *uriName;
} NS_ATT;
typedef struct {
const XML_Char *name;
PREFIX *prefix;
const ATTRIBUTE_ID *idAtt;
int nDefaultAtts;
int allocDefaultAtts;
DEFAULT_ATTRIBUTE *defaultAtts;
} ELEMENT_TYPE;
typedef struct {
HASH_TABLE generalEntities;
HASH_TABLE elementTypes;
HASH_TABLE attributeIds;
HASH_TABLE prefixes;
STRING_POOL pool;
STRING_POOL entityValuePool;
/* false once a parameter entity reference has been skipped */
XML_Bool keepProcessing;
/* true once an internal or external PE reference has been encountered;
this includes the reference to an external subset */
XML_Bool hasParamEntityRefs;
XML_Bool standalone;
#ifdef XML_DTD
/* indicates if external PE has been read */
XML_Bool paramEntityRead;
HASH_TABLE paramEntities;
#endif /* XML_DTD */
PREFIX defaultPrefix;
/* === scaffolding for building content model === */
XML_Bool in_eldecl;
CONTENT_SCAFFOLD *scaffold;
unsigned contentStringLen;
unsigned scaffSize;
unsigned scaffCount;
int scaffLevel;
int *scaffIndex;
} DTD;
typedef struct open_internal_entity {
const char *internalEventPtr;
const char *internalEventEndPtr;
struct open_internal_entity *next;
ENTITY *entity;
int startTagLevel;
XML_Bool betweenDecl; /* WFC: PE Between Declarations */
} OPEN_INTERNAL_ENTITY;
typedef enum XML_Error PTRCALL Processor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr);
static Processor prologProcessor;
static Processor prologInitProcessor;
static Processor contentProcessor;
static Processor cdataSectionProcessor;
#ifdef XML_DTD
static Processor ignoreSectionProcessor;
static Processor externalParEntProcessor;
static Processor externalParEntInitProcessor;
static Processor entityValueProcessor;
static Processor entityValueInitProcessor;
#endif /* XML_DTD */
static Processor epilogProcessor;
static Processor errorProcessor;
static Processor externalEntityInitProcessor;
static Processor externalEntityInitProcessor2;
static Processor externalEntityInitProcessor3;
static Processor externalEntityContentProcessor;
static Processor internalEntityProcessor;
static enum XML_Error
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName);
static enum XML_Error
processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
const char *s, const char *next);
static enum XML_Error
initializeEncoding(XML_Parser parser);
static enum XML_Error
doProlog(XML_Parser parser, const ENCODING *enc, const char *s,
const char *end, int tok, const char *next, const char **nextPtr,
XML_Bool haveMore);
static enum XML_Error
processInternalEntity(XML_Parser parser, ENTITY *entity,
XML_Bool betweenDecl);
static enum XML_Error
doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
const char *start, const char *end, const char **endPtr,
XML_Bool haveMore);
static enum XML_Error
doCdataSection(XML_Parser parser, const ENCODING *, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore);
#ifdef XML_DTD
static enum XML_Error
doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore);
#endif /* XML_DTD */
static void
freeBindings(XML_Parser parser, BINDING *bindings);
static enum XML_Error
storeAtts(XML_Parser parser, const ENCODING *, const char *s,
TAG_NAME *tagNamePtr, BINDING **bindingsPtr);
static enum XML_Error
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
const XML_Char *uri, BINDING **bindingsPtr);
static int
defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata,
XML_Bool isId, const XML_Char *dfltValue, XML_Parser parser);
static enum XML_Error
storeAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
const char *, const char *, STRING_POOL *);
static enum XML_Error
appendAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
const char *, const char *, STRING_POOL *);
static ATTRIBUTE_ID *
getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static int
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *);
static enum XML_Error
storeEntityValue(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static int
reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int
reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static void
reportDefault(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static const XML_Char * getContext(XML_Parser parser);
static XML_Bool
setContext(XML_Parser parser, const XML_Char *context);
static void FASTCALL normalizePublicId(XML_Char *s);
static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms);
/* do not call if m_parentParser != NULL */
static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
static void
dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms);
static int
dtdCopy(XML_Parser oldParser,
DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms);
static int
copyEntityTable(XML_Parser oldParser,
HASH_TABLE *, STRING_POOL *, const HASH_TABLE *);
static NAMED *
lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize);
static void FASTCALL
hashTableInit(HASH_TABLE *, const XML_Memory_Handling_Suite *ms);
static void FASTCALL hashTableClear(HASH_TABLE *);
static void FASTCALL hashTableDestroy(HASH_TABLE *);
static void FASTCALL
hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *);
static NAMED * FASTCALL hashTableIterNext(HASH_TABLE_ITER *);
static void FASTCALL
poolInit(STRING_POOL *, const XML_Memory_Handling_Suite *ms);
static void FASTCALL poolClear(STRING_POOL *);
static void FASTCALL poolDestroy(STRING_POOL *);
static XML_Char *
poolAppend(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *
poolStoreString(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
static const XML_Char * FASTCALL
poolCopyString(STRING_POOL *pool, const XML_Char *s);
static const XML_Char *
poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n);
static const XML_Char * FASTCALL
poolAppendString(STRING_POOL *pool, const XML_Char *s);
static int FASTCALL nextScaffoldPart(XML_Parser parser);
static XML_Content * build_model(XML_Parser parser);
static ELEMENT_TYPE *
getElementType(XML_Parser parser, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *copyString(const XML_Char *s,
const XML_Memory_Handling_Suite *memsuite);
static unsigned long generate_hash_secret_salt(XML_Parser parser);
static XML_Bool startParsing(XML_Parser parser);
static XML_Parser
parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep,
DTD *dtd);
static void
parserInit(XML_Parser parser, const XML_Char *encodingName);
#define poolStart(pool) ((pool)->start)
#define poolEnd(pool) ((pool)->ptr)
#define poolLength(pool) ((pool)->ptr - (pool)->start)
#define poolChop(pool) ((void)--(pool->ptr))
#define poolLastChar(pool) (((pool)->ptr)[-1])
#define poolDiscard(pool) ((pool)->ptr = (pool)->start)
#define poolFinish(pool) ((pool)->start = (pool)->ptr)
#define poolAppendChar(pool, c) \
(((pool)->ptr == (pool)->end && !poolGrow(pool)) \
? 0 \
: ((*((pool)->ptr)++ = c), 1))
struct XML_ParserStruct {
/* The first member must be m_userData so that the XML_GetUserData
macro works. */
void *m_userData;
void *m_handlerArg;
char *m_buffer;
const XML_Memory_Handling_Suite m_mem;
/* first character to be parsed */
const char *m_bufferPtr;
/* past last character to be parsed */
char *m_bufferEnd;
/* allocated end of m_buffer */
const char *m_bufferLim;
XML_Index m_parseEndByteIndex;
const char *m_parseEndPtr;
XML_Char *m_dataBuf;
XML_Char *m_dataBufEnd;
XML_StartElementHandler m_startElementHandler;
XML_EndElementHandler m_endElementHandler;
XML_CharacterDataHandler m_characterDataHandler;
XML_ProcessingInstructionHandler m_processingInstructionHandler;
XML_CommentHandler m_commentHandler;
XML_StartCdataSectionHandler m_startCdataSectionHandler;
XML_EndCdataSectionHandler m_endCdataSectionHandler;
XML_DefaultHandler m_defaultHandler;
XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
XML_NotationDeclHandler m_notationDeclHandler;
XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
XML_NotStandaloneHandler m_notStandaloneHandler;
XML_ExternalEntityRefHandler m_externalEntityRefHandler;
XML_Parser m_externalEntityRefHandlerArg;
XML_SkippedEntityHandler m_skippedEntityHandler;
XML_UnknownEncodingHandler m_unknownEncodingHandler;
XML_ElementDeclHandler m_elementDeclHandler;
XML_AttlistDeclHandler m_attlistDeclHandler;
XML_EntityDeclHandler m_entityDeclHandler;
XML_XmlDeclHandler m_xmlDeclHandler;
const ENCODING *m_encoding;
INIT_ENCODING m_initEncoding;
const ENCODING *m_internalEncoding;
const XML_Char *m_protocolEncodingName;
XML_Bool m_ns;
XML_Bool m_ns_triplets;
void *m_unknownEncodingMem;
void *m_unknownEncodingData;
void *m_unknownEncodingHandlerData;
void (XMLCALL *m_unknownEncodingRelease)(void *);
PROLOG_STATE m_prologState;
Processor *m_processor;
enum XML_Error m_errorCode;
const char *m_eventPtr;
const char *m_eventEndPtr;
const char *m_positionPtr;
OPEN_INTERNAL_ENTITY *m_openInternalEntities;
OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
XML_Bool m_defaultExpandInternalEntities;
int m_tagLevel;
ENTITY *m_declEntity;
const XML_Char *m_doctypeName;
const XML_Char *m_doctypeSysid;
const XML_Char *m_doctypePubid;
const XML_Char *m_declAttributeType;
const XML_Char *m_declNotationName;
const XML_Char *m_declNotationPublicId;
ELEMENT_TYPE *m_declElementType;
ATTRIBUTE_ID *m_declAttributeId;
XML_Bool m_declAttributeIsCdata;
XML_Bool m_declAttributeIsId;
DTD *m_dtd;
const XML_Char *m_curBase;
TAG *m_tagStack;
TAG *m_freeTagList;
BINDING *m_inheritedBindings;
BINDING *m_freeBindingList;
int m_attsSize;
int m_nSpecifiedAtts;
int m_idAttIndex;
ATTRIBUTE *m_atts;
NS_ATT *m_nsAtts;
unsigned long m_nsAttsVersion;
unsigned char m_nsAttsPower;
#ifdef XML_ATTR_INFO
XML_AttrInfo *m_attInfo;
#endif
POSITION m_position;
STRING_POOL m_tempPool;
STRING_POOL m_temp2Pool;
char *m_groupConnector;
unsigned int m_groupSize;
XML_Char m_namespaceSeparator;
XML_Parser m_parentParser;
XML_ParsingStatus m_parsingStatus;
#ifdef XML_DTD
XML_Bool m_isParamEntity;
XML_Bool m_useForeignDTD;
enum XML_ParamEntityParsing m_paramEntityParsing;
#endif
unsigned long m_hash_secret_salt;
};
#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p),(s)))
#define FREE(parser, p) (parser->m_mem.free_fcn((p)))
XML_Parser XMLCALL
XML_ParserCreate(const XML_Char *encodingName)
{
return XML_ParserCreate_MM(encodingName, NULL, NULL);
}
XML_Parser XMLCALL
XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep)
{
XML_Char tmp[2];
*tmp = nsSep;
return XML_ParserCreate_MM(encodingName, NULL, tmp);
}
static const XML_Char implicitContext[] = {
ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h, ASCII_t, ASCII_t, ASCII_p,
ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g,
ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9,
ASCII_9, ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,
ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0'
};
/* To avoid warnings about unused functions: */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
/* Obtain entropy on Linux 3.17+ */
static int
writeRandomBytes_getrandom_nonblock(void * target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const unsigned int getrandomFlags = GRND_NONBLOCK;
do {
void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const int bytesWrittenMore =
#if defined(HAVE_GETRANDOM)
getrandom(currentTarget, bytesToWrite, getrandomFlags);
#else
syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
#endif
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
return success;
}
#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
/* Extract entropy from /dev/urandom */
static int
writeRandomBytes_dev_urandom(void * target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
return 0;
}
do {
void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
close(fd);
return success;
}
#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
static void
writeRandomBytes_arc4random(void * target, size_t count) {
size_t bytesWrittenTotal = 0;
while (bytesWrittenTotal < count) {
const uint32_t random32 = arc4random();
size_t i = 0;
for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
i++, bytesWrittenTotal++) {
const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
((uint8_t *)target)[bytesWrittenTotal] = random8;
}
}
}
#endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
#ifdef _WIN32
typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG);
HMODULE _Expat_LoadLibrary(LPCTSTR filename); /* see loadlibrary.c */
/* Obtain entropy on Windows XP / Windows Server 2003 and later.
* Hint on RtlGenRandom and the following article from libsodium.
*
* Michael Howard: Cryptographically Secure Random number on Windows without using CryptoAPI
* https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/
*/
static int
writeRandomBytes_RtlGenRandom(void * target, size_t count) {
int success = 0; /* full count bytes written? */
const HMODULE advapi32 = _Expat_LoadLibrary(TEXT("ADVAPI32.DLL"));
if (advapi32) {
const RTLGENRANDOM_FUNC RtlGenRandom
= (RTLGENRANDOM_FUNC)GetProcAddress(advapi32, "SystemFunction036");
if (RtlGenRandom) {
if (RtlGenRandom((PVOID)target, (ULONG)count) == TRUE) {
success = 1;
}
}
FreeLibrary(advapi32);
}
return success;
}
#endif /* _WIN32 */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
static unsigned long
gather_time_entropy(void)
{
#ifdef _WIN32
FILETIME ft;
GetSystemTimeAsFileTime(&ft); /* never fails */
return ft.dwHighDateTime ^ ft.dwLowDateTime;
#else
struct timeval tv;
int gettimeofday_res;
gettimeofday_res = gettimeofday(&tv, NULL);
#if defined(NDEBUG)
(void)gettimeofday_res;
#else
assert (gettimeofday_res == 0);
#endif /* defined(NDEBUG) */
/* Microseconds time is <20 bits entropy */
return tv.tv_usec;
#endif
}
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
static unsigned long
ENTROPY_DEBUG(const char * label, unsigned long entropy) {
const char * const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) {
fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n",
label,
(int)sizeof(entropy) * 2, entropy,
(unsigned long)sizeof(entropy));
}
return entropy;
}
static unsigned long
generate_hash_secret_salt(XML_Parser parser)
{
unsigned long entropy;
(void)parser;
/* "Failproof" high quality providers: */
#if defined(HAVE_ARC4RANDOM_BUF)
arc4random_buf(&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random_buf", entropy);
#elif defined(HAVE_ARC4RANDOM)
writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random", entropy);
#else
/* Try high quality providers first .. */
#ifdef _WIN32
if (writeRandomBytes_RtlGenRandom((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("RtlGenRandom", entropy);
}
#elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("getrandom", entropy);
}
#endif
#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("/dev/urandom", entropy);
}
#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
/* .. and self-made low quality for backup: */
/* Process ID is 0 bits entropy if attacker has local access */
entropy = gather_time_entropy() ^ getpid();
/* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
if (sizeof(unsigned long) == 4) {
return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
} else {
return ENTROPY_DEBUG("fallback(8)",
entropy * (unsigned long)2305843009213693951ULL);
}
#endif
}
static unsigned long
get_hash_secret_salt(XML_Parser parser) {
if (parser->m_parentParser != NULL)
return get_hash_secret_salt(parser->m_parentParser);
return parser->m_hash_secret_salt;
}
static XML_Bool /* only valid for root parser */
startParsing(XML_Parser parser)
{
/* hash functions must be initialized before setContext() is called */
if (parser->m_hash_secret_salt == 0)
parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
if (parser->m_ns) {
/* implicit context only set for root parser, since child
parsers (i.e. external entity parsers) will inherit it
*/
return setContext(parser, implicitContext);
}
return XML_TRUE;
}
XML_Parser XMLCALL
XML_ParserCreate_MM(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep)
{
return parserCreate(encodingName, memsuite, nameSep, NULL);
}
static XML_Parser
parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep,
DTD *dtd)
{
XML_Parser parser;
if (memsuite) {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)
memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = memsuite->malloc_fcn;
mtemp->realloc_fcn = memsuite->realloc_fcn;
mtemp->free_fcn = memsuite->free_fcn;
}
}
else {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = malloc;
mtemp->realloc_fcn = realloc;
mtemp->free_fcn = free;
}
}
if (!parser)
return parser;
parser->m_buffer = NULL;
parser->m_bufferLim = NULL;
parser->m_attsSize = INIT_ATTS_SIZE;
parser->m_atts = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
if (parser->m_atts == NULL) {
FREE(parser, parser);
return NULL;
}
#ifdef XML_ATTR_INFO
parser->m_attInfo = (XML_AttrInfo*)MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));
if (parser->m_attInfo == NULL) {
FREE(parser, parser->m_atts);
FREE(parser, parser);
return NULL;
}
#endif
parser->m_dataBuf = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
if (parser->m_dataBuf == NULL) {
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
if (dtd)
parser->m_dtd = dtd;
else {
parser->m_dtd = dtdCreate(&parser->m_mem);
if (parser->m_dtd == NULL) {
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
}
parser->m_freeBindingList = NULL;
parser->m_freeTagList = NULL;
parser->m_freeInternalEntities = NULL;
parser->m_groupSize = 0;
parser->m_groupConnector = NULL;
parser->m_unknownEncodingHandler = NULL;
parser->m_unknownEncodingHandlerData = NULL;
parser->m_namespaceSeparator = ASCII_EXCL;
parser->m_ns = XML_FALSE;
parser->m_ns_triplets = XML_FALSE;
parser->m_nsAtts = NULL;
parser->m_nsAttsVersion = 0;
parser->m_nsAttsPower = 0;
parser->m_protocolEncodingName = NULL;
poolInit(&parser->m_tempPool, &(parser->m_mem));
poolInit(&parser->m_temp2Pool, &(parser->m_mem));
parserInit(parser, encodingName);
if (encodingName && !parser->m_protocolEncodingName) {
XML_ParserFree(parser);
return NULL;
}
if (nameSep) {
parser->m_ns = XML_TRUE;
parser->m_internalEncoding = XmlGetInternalEncodingNS();
parser->m_namespaceSeparator = *nameSep;
}
else {
parser->m_internalEncoding = XmlGetInternalEncoding();
}
return parser;
}
static void
parserInit(XML_Parser parser, const XML_Char *encodingName)
{
parser->m_processor = prologInitProcessor;
XmlPrologStateInit(&parser->m_prologState);
if (encodingName != NULL) {
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
}
parser->m_curBase = NULL;
XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
parser->m_userData = NULL;
parser->m_handlerArg = NULL;
parser->m_startElementHandler = NULL;
parser->m_endElementHandler = NULL;
parser->m_characterDataHandler = NULL;
parser->m_processingInstructionHandler = NULL;
parser->m_commentHandler = NULL;
parser->m_startCdataSectionHandler = NULL;
parser->m_endCdataSectionHandler = NULL;
parser->m_defaultHandler = NULL;
parser->m_startDoctypeDeclHandler = NULL;
parser->m_endDoctypeDeclHandler = NULL;
parser->m_unparsedEntityDeclHandler = NULL;
parser->m_notationDeclHandler = NULL;
parser->m_startNamespaceDeclHandler = NULL;
parser->m_endNamespaceDeclHandler = NULL;
parser->m_notStandaloneHandler = NULL;
parser->m_externalEntityRefHandler = NULL;
parser->m_externalEntityRefHandlerArg = parser;
parser->m_skippedEntityHandler = NULL;
parser->m_elementDeclHandler = NULL;
parser->m_attlistDeclHandler = NULL;
parser->m_entityDeclHandler = NULL;
parser->m_xmlDeclHandler = NULL;
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer;
parser->m_parseEndByteIndex = 0;
parser->m_parseEndPtr = NULL;
parser->m_declElementType = NULL;
parser->m_declAttributeId = NULL;
parser->m_declEntity = NULL;
parser->m_doctypeName = NULL;
parser->m_doctypeSysid = NULL;
parser->m_doctypePubid = NULL;
parser->m_declAttributeType = NULL;
parser->m_declNotationName = NULL;
parser->m_declNotationPublicId = NULL;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeIsId = XML_FALSE;
memset(&parser->m_position, 0, sizeof(POSITION));
parser->m_errorCode = XML_ERROR_NONE;
parser->m_eventPtr = NULL;
parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
parser->m_openInternalEntities = NULL;
parser->m_defaultExpandInternalEntities = XML_TRUE;
parser->m_tagLevel = 0;
parser->m_tagStack = NULL;
parser->m_inheritedBindings = NULL;
parser->m_nSpecifiedAtts = 0;
parser->m_unknownEncodingMem = NULL;
parser->m_unknownEncodingRelease = NULL;
parser->m_unknownEncodingData = NULL;
parser->m_parentParser = NULL;
parser->m_parsingStatus.parsing = XML_INITIALIZED;
#ifdef XML_DTD
parser->m_isParamEntity = XML_FALSE;
parser->m_useForeignDTD = XML_FALSE;
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif
parser->m_hash_secret_salt = 0;
}
/* moves list of bindings to m_freeBindingList */
static void FASTCALL
moveToFreeBindingList(XML_Parser parser, BINDING *bindings)
{
while (bindings) {
BINDING *b = bindings;
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
}
}
XML_Bool XMLCALL
XML_ParserReset(XML_Parser parser, const XML_Char *encodingName)
{
TAG *tStk;
OPEN_INTERNAL_ENTITY *openEntityList;
if (parser == NULL)
return XML_FALSE;
if (parser->m_parentParser)
return XML_FALSE;
/* move m_tagStack to m_freeTagList */
tStk = parser->m_tagStack;
while (tStk) {
TAG *tag = tStk;
tStk = tStk->parent;
tag->parent = parser->m_freeTagList;
moveToFreeBindingList(parser, tag->bindings);
tag->bindings = NULL;
parser->m_freeTagList = tag;
}
/* move m_openInternalEntities to m_freeInternalEntities */
openEntityList = parser->m_openInternalEntities;
while (openEntityList) {
OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
openEntityList = openEntity->next;
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
moveToFreeBindingList(parser, parser->m_inheritedBindings);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
poolClear(&parser->m_tempPool);
poolClear(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
parser->m_protocolEncodingName = NULL;
parserInit(parser, encodingName);
dtdReset(parser->m_dtd, &parser->m_mem);
return XML_TRUE;
}
enum XML_Status XMLCALL
XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName)
{
if (parser == NULL)
return XML_STATUS_ERROR;
/* Block after XML_Parse()/XML_ParseBuffer() has been called.
XXX There's no way for the caller to determine which of the
XXX possible error cases caused the XML_STATUS_ERROR return.
*/
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_STATUS_ERROR;
/* Get rid of any previous encoding name */
FREE(parser, (void *)parser->m_protocolEncodingName);
if (encodingName == NULL)
/* No new encoding name */
parser->m_protocolEncodingName = NULL;
else {
/* Copy the new encoding name into allocated memory */
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
if (!parser->m_protocolEncodingName)
return XML_STATUS_ERROR;
}
return XML_STATUS_OK;
}
XML_Parser XMLCALL
XML_ExternalEntityParserCreate(XML_Parser oldParser,
const XML_Char *context,
const XML_Char *encodingName)
{
XML_Parser parser = oldParser;
DTD *newDtd = NULL;
DTD *oldDtd;
XML_StartElementHandler oldStartElementHandler;
XML_EndElementHandler oldEndElementHandler;
XML_CharacterDataHandler oldCharacterDataHandler;
XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
XML_CommentHandler oldCommentHandler;
XML_StartCdataSectionHandler oldStartCdataSectionHandler;
XML_EndCdataSectionHandler oldEndCdataSectionHandler;
XML_DefaultHandler oldDefaultHandler;
XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
XML_NotationDeclHandler oldNotationDeclHandler;
XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
XML_NotStandaloneHandler oldNotStandaloneHandler;
XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
XML_SkippedEntityHandler oldSkippedEntityHandler;
XML_UnknownEncodingHandler oldUnknownEncodingHandler;
XML_ElementDeclHandler oldElementDeclHandler;
XML_AttlistDeclHandler oldAttlistDeclHandler;
XML_EntityDeclHandler oldEntityDeclHandler;
XML_XmlDeclHandler oldXmlDeclHandler;
ELEMENT_TYPE * oldDeclElementType;
void *oldUserData;
void *oldHandlerArg;
XML_Bool oldDefaultExpandInternalEntities;
XML_Parser oldExternalEntityRefHandlerArg;
#ifdef XML_DTD
enum XML_ParamEntityParsing oldParamEntityParsing;
int oldInEntityValue;
#endif
XML_Bool oldns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
unsigned long oldhash_secret_salt;
/* Validate the oldParser parameter before we pull everything out of it */
if (oldParser == NULL)
return NULL;
/* Stash the original parser contents on the stack */
oldDtd = parser->m_dtd;
oldStartElementHandler = parser->m_startElementHandler;
oldEndElementHandler = parser->m_endElementHandler;
oldCharacterDataHandler = parser->m_characterDataHandler;
oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
oldCommentHandler = parser->m_commentHandler;
oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
oldDefaultHandler = parser->m_defaultHandler;
oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
oldNotationDeclHandler = parser->m_notationDeclHandler;
oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
oldNotStandaloneHandler = parser->m_notStandaloneHandler;
oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
oldSkippedEntityHandler = parser->m_skippedEntityHandler;
oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
oldElementDeclHandler = parser->m_elementDeclHandler;
oldAttlistDeclHandler = parser->m_attlistDeclHandler;
oldEntityDeclHandler = parser->m_entityDeclHandler;
oldXmlDeclHandler = parser->m_xmlDeclHandler;
oldDeclElementType = parser->m_declElementType;
oldUserData = parser->m_userData;
oldHandlerArg = parser->m_handlerArg;
oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
#ifdef XML_DTD
oldParamEntityParsing = parser->m_paramEntityParsing;
oldInEntityValue = parser->m_prologState.inEntityValue;
#endif
oldns_triplets = parser->m_ns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
oldhash_secret_salt = parser->m_hash_secret_salt;
#ifdef XML_DTD
if (!context)
newDtd = oldDtd;
#endif /* XML_DTD */
/* Note that the magical uses of the pre-processor to make field
access look more like C++ require that `parser' be overwritten
here. This makes this function more painful to follow than it
would be otherwise.
*/
if (parser->m_ns) {
XML_Char tmp[2];
*tmp = parser->m_namespaceSeparator;
parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
}
else {
parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
}
if (!parser)
return NULL;
parser->m_startElementHandler = oldStartElementHandler;
parser->m_endElementHandler = oldEndElementHandler;
parser->m_characterDataHandler = oldCharacterDataHandler;
parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
parser->m_commentHandler = oldCommentHandler;
parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
parser->m_defaultHandler = oldDefaultHandler;
parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
parser->m_notationDeclHandler = oldNotationDeclHandler;
parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
parser->m_notStandaloneHandler = oldNotStandaloneHandler;
parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
parser->m_skippedEntityHandler = oldSkippedEntityHandler;
parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
parser->m_elementDeclHandler = oldElementDeclHandler;
parser->m_attlistDeclHandler = oldAttlistDeclHandler;
parser->m_entityDeclHandler = oldEntityDeclHandler;
parser->m_xmlDeclHandler = oldXmlDeclHandler;
parser->m_declElementType = oldDeclElementType;
parser->m_userData = oldUserData;
if (oldUserData == oldHandlerArg)
parser->m_handlerArg = parser->m_userData;
else
parser->m_handlerArg = parser;
if (oldExternalEntityRefHandlerArg != oldParser)
parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
parser->m_ns_triplets = oldns_triplets;
parser->m_hash_secret_salt = oldhash_secret_salt;
parser->m_parentParser = oldParser;
#ifdef XML_DTD
parser->m_paramEntityParsing = oldParamEntityParsing;
parser->m_prologState.inEntityValue = oldInEntityValue;
if (context) {
#endif /* XML_DTD */
if (!dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
|| !setContext(parser, context)) {
XML_ParserFree(parser);
return NULL;
}
parser->m_processor = externalEntityInitProcessor;
#ifdef XML_DTD
}
else {
/* The DTD instance referenced by parser->m_dtd is shared between the document's
root parser and external PE parsers, therefore one does not need to
call setContext. In addition, one also *must* not call setContext,
because this would overwrite existing prefix->binding pointers in
parser->m_dtd with ones that get destroyed with the external PE parser.
This would leave those prefixes with dangling pointers.
*/
parser->m_isParamEntity = XML_TRUE;
XmlPrologStateInitExternalEntity(&parser->m_prologState);
parser->m_processor = externalParEntInitProcessor;
}
#endif /* XML_DTD */
return parser;
}
static void FASTCALL
destroyBindings(BINDING *bindings, XML_Parser parser)
{
for (;;) {
BINDING *b = bindings;
if (!b)
break;
bindings = b->nextTagBinding;
FREE(parser, b->uri);
FREE(parser, b);
}
}
void XMLCALL
XML_ParserFree(XML_Parser parser)
{
TAG *tagList;
OPEN_INTERNAL_ENTITY *entityList;
if (parser == NULL)
return;
/* free m_tagStack and m_freeTagList */
tagList = parser->m_tagStack;
for (;;) {
TAG *p;
if (tagList == NULL) {
if (parser->m_freeTagList == NULL)
break;
tagList = parser->m_freeTagList;
parser->m_freeTagList = NULL;
}
p = tagList;
tagList = tagList->parent;
FREE(parser, p->buf);
destroyBindings(p->bindings, parser);
FREE(parser, p);
}
/* free m_openInternalEntities and m_freeInternalEntities */
entityList = parser->m_openInternalEntities;
for (;;) {
OPEN_INTERNAL_ENTITY *openEntity;
if (entityList == NULL) {
if (parser->m_freeInternalEntities == NULL)
break;
entityList = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = NULL;
}
openEntity = entityList;
entityList = entityList->next;
FREE(parser, openEntity);
}
destroyBindings(parser->m_freeBindingList, parser);
destroyBindings(parser->m_inheritedBindings, parser);
poolDestroy(&parser->m_tempPool);
poolDestroy(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
#ifdef XML_DTD
/* external parameter entity parsers share the DTD structure
parser->m_dtd with the root parser, so we must not destroy it
*/
if (!parser->m_isParamEntity && parser->m_dtd)
#else
if (parser->m_dtd)
#endif /* XML_DTD */
dtdDestroy(parser->m_dtd, (XML_Bool)!parser->m_parentParser, &parser->m_mem);
FREE(parser, (void *)parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, (void *)parser->m_attInfo);
#endif
FREE(parser, parser->m_groupConnector);
FREE(parser, parser->m_buffer);
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_nsAtts);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
FREE(parser, parser);
}
void XMLCALL
XML_UseParserAsHandlerArg(XML_Parser parser)
{
if (parser != NULL)
parser->m_handlerArg = parser;
}
enum XML_Error XMLCALL
XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD)
{
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
#ifdef XML_DTD
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
parser->m_useForeignDTD = useDTD;
return XML_ERROR_NONE;
#else
return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
#endif
}
void XMLCALL
XML_SetReturnNSTriplet(XML_Parser parser, int do_nst)
{
if (parser == NULL)
return;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return;
parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
}
void XMLCALL
XML_SetUserData(XML_Parser parser, void *p)
{
if (parser == NULL)
return;
if (parser->m_handlerArg == parser->m_userData)
parser->m_handlerArg = parser->m_userData = p;
else
parser->m_userData = p;
}
enum XML_Status XMLCALL
XML_SetBase(XML_Parser parser, const XML_Char *p)
{
if (parser == NULL)
return XML_STATUS_ERROR;
if (p) {
p = poolCopyString(&parser->m_dtd->pool, p);
if (!p)
return XML_STATUS_ERROR;
parser->m_curBase = p;
}
else
parser->m_curBase = NULL;
return XML_STATUS_OK;
}
const XML_Char * XMLCALL
XML_GetBase(XML_Parser parser)
{
if (parser == NULL)
return NULL;
return parser->m_curBase;
}
int XMLCALL
XML_GetSpecifiedAttributeCount(XML_Parser parser)
{
if (parser == NULL)
return -1;
return parser->m_nSpecifiedAtts;
}
int XMLCALL
XML_GetIdAttributeIndex(XML_Parser parser)
{
if (parser == NULL)
return -1;
return parser->m_idAttIndex;
}
#ifdef XML_ATTR_INFO
const XML_AttrInfo * XMLCALL
XML_GetAttributeInfo(XML_Parser parser)
{
if (parser == NULL)
return NULL;
return parser->m_attInfo;
}
#endif
void XMLCALL
XML_SetElementHandler(XML_Parser parser,
XML_StartElementHandler start,
XML_EndElementHandler end)
{
if (parser == NULL)
return;
parser->m_startElementHandler = start;
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetStartElementHandler(XML_Parser parser,
XML_StartElementHandler start) {
if (parser != NULL)
parser->m_startElementHandler = start;
}
void XMLCALL
XML_SetEndElementHandler(XML_Parser parser,
XML_EndElementHandler end) {
if (parser != NULL)
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetCharacterDataHandler(XML_Parser parser,
XML_CharacterDataHandler handler)
{
if (parser != NULL)
parser->m_characterDataHandler = handler;
}
void XMLCALL
XML_SetProcessingInstructionHandler(XML_Parser parser,
XML_ProcessingInstructionHandler handler)
{
if (parser != NULL)
parser->m_processingInstructionHandler = handler;
}
void XMLCALL
XML_SetCommentHandler(XML_Parser parser,
XML_CommentHandler handler)
{
if (parser != NULL)
parser->m_commentHandler = handler;
}
void XMLCALL
XML_SetCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start,
XML_EndCdataSectionHandler end)
{
if (parser == NULL)
return;
parser->m_startCdataSectionHandler = start;
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetStartCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start) {
if (parser != NULL)
parser->m_startCdataSectionHandler = start;
}
void XMLCALL
XML_SetEndCdataSectionHandler(XML_Parser parser,
XML_EndCdataSectionHandler end) {
if (parser != NULL)
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetDefaultHandler(XML_Parser parser,
XML_DefaultHandler handler)
{
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_FALSE;
}
void XMLCALL
XML_SetDefaultHandlerExpand(XML_Parser parser,
XML_DefaultHandler handler)
{
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_TRUE;
}
void XMLCALL
XML_SetDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start,
XML_EndDoctypeDeclHandler end)
{
if (parser == NULL)
return;
parser->m_startDoctypeDeclHandler = start;
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetStartDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start) {
if (parser != NULL)
parser->m_startDoctypeDeclHandler = start;
}
void XMLCALL
XML_SetEndDoctypeDeclHandler(XML_Parser parser,
XML_EndDoctypeDeclHandler end) {
if (parser != NULL)
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
XML_UnparsedEntityDeclHandler handler)
{
if (parser != NULL)
parser->m_unparsedEntityDeclHandler = handler;
}
void XMLCALL
XML_SetNotationDeclHandler(XML_Parser parser,
XML_NotationDeclHandler handler)
{
if (parser != NULL)
parser->m_notationDeclHandler = handler;
}
void XMLCALL
XML_SetNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start,
XML_EndNamespaceDeclHandler end)
{
if (parser == NULL)
return;
parser->m_startNamespaceDeclHandler = start;
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetStartNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start) {
if (parser != NULL)
parser->m_startNamespaceDeclHandler = start;
}
void XMLCALL
XML_SetEndNamespaceDeclHandler(XML_Parser parser,
XML_EndNamespaceDeclHandler end) {
if (parser != NULL)
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetNotStandaloneHandler(XML_Parser parser,
XML_NotStandaloneHandler handler)
{
if (parser != NULL)
parser->m_notStandaloneHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandler(XML_Parser parser,
XML_ExternalEntityRefHandler handler)
{
if (parser != NULL)
parser->m_externalEntityRefHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg)
{
if (parser == NULL)
return;
if (arg)
parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
else
parser->m_externalEntityRefHandlerArg = parser;
}
void XMLCALL
XML_SetSkippedEntityHandler(XML_Parser parser,
XML_SkippedEntityHandler handler)
{
if (parser != NULL)
parser->m_skippedEntityHandler = handler;
}
void XMLCALL
XML_SetUnknownEncodingHandler(XML_Parser parser,
XML_UnknownEncodingHandler handler,
void *data)
{
if (parser == NULL)
return;
parser->m_unknownEncodingHandler = handler;
parser->m_unknownEncodingHandlerData = data;
}
void XMLCALL
XML_SetElementDeclHandler(XML_Parser parser,
XML_ElementDeclHandler eldecl)
{
if (parser != NULL)
parser->m_elementDeclHandler = eldecl;
}
void XMLCALL
XML_SetAttlistDeclHandler(XML_Parser parser,
XML_AttlistDeclHandler attdecl)
{
if (parser != NULL)
parser->m_attlistDeclHandler = attdecl;
}
void XMLCALL
XML_SetEntityDeclHandler(XML_Parser parser,
XML_EntityDeclHandler handler)
{
if (parser != NULL)
parser->m_entityDeclHandler = handler;
}
void XMLCALL
XML_SetXmlDeclHandler(XML_Parser parser,
XML_XmlDeclHandler handler) {
if (parser != NULL)
parser->m_xmlDeclHandler = handler;
}
int XMLCALL
XML_SetParamEntityParsing(XML_Parser parser,
enum XML_ParamEntityParsing peParsing)
{
if (parser == NULL)
return 0;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
#ifdef XML_DTD
parser->m_paramEntityParsing = peParsing;
return 1;
#else
return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
#endif
}
int XMLCALL
XML_SetHashSalt(XML_Parser parser,
unsigned long hash_salt)
{
if (parser == NULL)
return 0;
if (parser->m_parentParser)
return XML_SetHashSalt(parser->m_parentParser, hash_salt);
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
parser->m_hash_secret_salt = hash_salt;
return 1;
}
enum XML_Status XMLCALL
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
{
if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
if (parser != NULL)
parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
return XML_STATUS_ERROR;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && !startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
if (len == 0) {
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
if (!isFinal)
return XML_STATUS_OK;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
/* If data are left over from last buffer, and we now know that these
data are the final chunk of input, then we have to check them again
to detect errors based on that fact.
*/
parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode == XML_ERROR_NONE) {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
/* It is hard to be certain, but it seems that this case
* cannot occur. This code is cleaning up a previous parse
* with no new data (since len == 0). Changing the parsing
* state requires getting to execute a handler function, and
* there doesn't seem to be an opportunity for that while in
* this circumstance.
*
* Given the uncertainty, we retain the code but exclude it
* from coverage tests.
*
* LCOV_EXCL_START
*/
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return XML_STATUS_SUSPENDED;
/* LCOV_EXCL_STOP */
case XML_INITIALIZED:
case XML_PARSING:
parser->m_parsingStatus.parsing = XML_FINISHED;
/* fall through */
default:
return XML_STATUS_OK;
}
}
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
#ifndef XML_CONTEXT_BYTES
else if (parser->m_bufferPtr == parser->m_bufferEnd) {
const char *end;
int nLeftOver;
enum XML_Status result;
/* Detect overflow (a+b > MAX <==> b > MAX-a) */
if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_parseEndByteIndex += len;
parser->m_positionPtr = s;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return XML_STATUS_OK;
}
/* fall through */
default:
result = XML_STATUS_OK;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position);
nLeftOver = s + len - end;
if (nLeftOver) {
if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) {
/* avoid _signed_ integer overflow */
char *temp = NULL;
const int bytesToAllocate = (int)((unsigned)len * 2U);
if (bytesToAllocate > 0) {
temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate);
}
if (temp == NULL) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_buffer = temp;
parser->m_bufferLim = parser->m_buffer + bytesToAllocate;
}
memcpy(parser->m_buffer, end, nLeftOver);
}
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer + nLeftOver;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_eventPtr = parser->m_bufferPtr;
parser->m_eventEndPtr = parser->m_bufferPtr;
return result;
}
#endif /* not defined XML_CONTEXT_BYTES */
else {
void *buff = XML_GetBuffer(parser, len);
if (buff == NULL)
return XML_STATUS_ERROR;
else {
memcpy(buff, s, len);
return XML_ParseBuffer(parser, len, isFinal);
}
}
}
enum XML_Status XMLCALL
XML_ParseBuffer(XML_Parser parser, int len, int isFinal)
{
const char *start;
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && !startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
start = parser->m_bufferPtr;
parser->m_positionPtr = start;
parser->m_bufferEnd += len;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_parseEndByteIndex += len;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode = parser->m_processor(parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default: ; /* should not happen */
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void * XMLCALL
XML_GetBuffer(XML_Parser parser, int len)
{
if (parser == NULL)
return NULL;
if (len < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return NULL;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return NULL;
default: ;
}
if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) {
#ifdef XML_CONTEXT_BYTES
int keep;
#endif /* defined XML_CONTEXT_BYTES */
/* Do not invoke signed arithmetic overflow: */
int neededSize = (int) ((unsigned)len +
(unsigned)EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd,
parser->m_bufferPtr));
if (neededSize < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
#ifdef XML_CONTEXT_BYTES
keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
neededSize += keep;
#endif /* defined XML_CONTEXT_BYTES */
if (neededSize <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
#ifdef XML_CONTEXT_BYTES
if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
int offset = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer) - keep;
/* The buffer pointers cannot be NULL here; we have at least some bytes in the buffer */
memmove(parser->m_buffer, &parser->m_buffer[offset], parser->m_bufferEnd - parser->m_bufferPtr + keep);
parser->m_bufferEnd -= offset;
parser->m_bufferPtr -= offset;
}
#else
if (parser->m_buffer && parser->m_bufferPtr) {
memmove(parser->m_buffer, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
parser->m_bufferEnd = parser->m_buffer +
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
parser->m_bufferPtr = parser->m_buffer;
}
#endif /* not defined XML_CONTEXT_BYTES */
}
else {
char *newBuf;
int bufferSize = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
if (bufferSize == 0)
bufferSize = INIT_BUFFER_SIZE;
do {
/* Do not invoke signed arithmetic overflow: */
bufferSize = (int) (2U * (unsigned) bufferSize);
} while (bufferSize < neededSize && bufferSize > 0);
if (bufferSize <= 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
newBuf = (char *)MALLOC(parser, bufferSize);
if (newBuf == 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
parser->m_bufferLim = newBuf + bufferSize;
#ifdef XML_CONTEXT_BYTES
if (parser->m_bufferPtr) {
int keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
memcpy(newBuf, &parser->m_bufferPtr[-keep],
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep);
FREE(parser, parser->m_buffer);
parser->m_buffer = newBuf;
parser->m_bufferEnd = parser->m_buffer +
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep;
parser->m_bufferPtr = parser->m_buffer + keep;
}
else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
parser->m_bufferPtr = parser->m_buffer = newBuf;
}
#else
if (parser->m_bufferPtr) {
memcpy(newBuf, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
FREE(parser, parser->m_buffer);
parser->m_bufferEnd = newBuf +
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
}
else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
}
parser->m_bufferPtr = parser->m_buffer = newBuf;
#endif /* not defined XML_CONTEXT_BYTES */
}
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
}
return parser->m_bufferEnd;
}
enum XML_Status XMLCALL
XML_StopParser(XML_Parser parser, XML_Bool resumable)
{
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
if (resumable) {
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_FINISHED;
break;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
default:
if (resumable) {
#ifdef XML_DTD
if (parser->m_isParamEntity) {
parser->m_errorCode = XML_ERROR_SUSPEND_PE;
return XML_STATUS_ERROR;
}
#endif
parser->m_parsingStatus.parsing = XML_SUSPENDED;
}
else
parser->m_parsingStatus.parsing = XML_FINISHED;
}
return XML_STATUS_OK;
}
enum XML_Status XMLCALL
XML_ResumeParser(XML_Parser parser)
{
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_PARSING;
parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (parser->m_parsingStatus.finalBuffer) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default: ;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void XMLCALL
XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status)
{
if (parser == NULL)
return;
assert(status != NULL);
*status = parser->m_parsingStatus;
}
enum XML_Error XMLCALL
XML_GetErrorCode(XML_Parser parser)
{
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
return parser->m_errorCode;
}
XML_Index XMLCALL
XML_GetCurrentByteIndex(XML_Parser parser)
{
if (parser == NULL)
return -1;
if (parser->m_eventPtr)
return (XML_Index)(parser->m_parseEndByteIndex - (parser->m_parseEndPtr - parser->m_eventPtr));
return -1;
}
int XMLCALL
XML_GetCurrentByteCount(XML_Parser parser)
{
if (parser == NULL)
return 0;
if (parser->m_eventEndPtr && parser->m_eventPtr)
return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
return 0;
}
const char * XMLCALL
XML_GetInputContext(XML_Parser parser, int *offset, int *size)
{
#ifdef XML_CONTEXT_BYTES
if (parser == NULL)
return NULL;
if (parser->m_eventPtr && parser->m_buffer) {
if (offset != NULL)
*offset = (int)(parser->m_eventPtr - parser->m_buffer);
if (size != NULL)
*size = (int)(parser->m_bufferEnd - parser->m_buffer);
return parser->m_buffer;
}
#else
(void)parser;
(void)offset;
(void)size;
#endif /* defined XML_CONTEXT_BYTES */
return (char *) 0;
}
XML_Size XMLCALL
XML_GetCurrentLineNumber(XML_Parser parser)
{
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.lineNumber + 1;
}
XML_Size XMLCALL
XML_GetCurrentColumnNumber(XML_Parser parser)
{
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.columnNumber;
}
void XMLCALL
XML_FreeContentModel(XML_Parser parser, XML_Content *model)
{
if (parser != NULL)
FREE(parser, model);
}
void * XMLCALL
XML_MemMalloc(XML_Parser parser, size_t size)
{
if (parser == NULL)
return NULL;
return MALLOC(parser, size);
}
void * XMLCALL
XML_MemRealloc(XML_Parser parser, void *ptr, size_t size)
{
if (parser == NULL)
return NULL;
return REALLOC(parser, ptr, size);
}
void XMLCALL
XML_MemFree(XML_Parser parser, void *ptr)
{
if (parser != NULL)
FREE(parser, ptr);
}
void XMLCALL
XML_DefaultCurrent(XML_Parser parser)
{
if (parser == NULL)
return;
if (parser->m_defaultHandler) {
if (parser->m_openInternalEntities)
reportDefault(parser,
parser->m_internalEncoding,
parser->m_openInternalEntities->internalEventPtr,
parser->m_openInternalEntities->internalEventEndPtr);
else
reportDefault(parser, parser->m_encoding, parser->m_eventPtr, parser->m_eventEndPtr);
}
}
const XML_LChar * XMLCALL
XML_ErrorString(enum XML_Error code)
{
switch (code) {
case XML_ERROR_NONE:
return NULL;
case XML_ERROR_NO_MEMORY:
return XML_L("out of memory");
case XML_ERROR_SYNTAX:
return XML_L("syntax error");
case XML_ERROR_NO_ELEMENTS:
return XML_L("no element found");
case XML_ERROR_INVALID_TOKEN:
return XML_L("not well-formed (invalid token)");
case XML_ERROR_UNCLOSED_TOKEN:
return XML_L("unclosed token");
case XML_ERROR_PARTIAL_CHAR:
return XML_L("partial character");
case XML_ERROR_TAG_MISMATCH:
return XML_L("mismatched tag");
case XML_ERROR_DUPLICATE_ATTRIBUTE:
return XML_L("duplicate attribute");
case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
return XML_L("junk after document element");
case XML_ERROR_PARAM_ENTITY_REF:
return XML_L("illegal parameter entity reference");
case XML_ERROR_UNDEFINED_ENTITY:
return XML_L("undefined entity");
case XML_ERROR_RECURSIVE_ENTITY_REF:
return XML_L("recursive entity reference");
case XML_ERROR_ASYNC_ENTITY:
return XML_L("asynchronous entity");
case XML_ERROR_BAD_CHAR_REF:
return XML_L("reference to invalid character number");
case XML_ERROR_BINARY_ENTITY_REF:
return XML_L("reference to binary entity");
case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
return XML_L("reference to external entity in attribute");
case XML_ERROR_MISPLACED_XML_PI:
return XML_L("XML or text declaration not at start of entity");
case XML_ERROR_UNKNOWN_ENCODING:
return XML_L("unknown encoding");
case XML_ERROR_INCORRECT_ENCODING:
return XML_L("encoding specified in XML declaration is incorrect");
case XML_ERROR_UNCLOSED_CDATA_SECTION:
return XML_L("unclosed CDATA section");
case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
return XML_L("error in processing external entity reference");
case XML_ERROR_NOT_STANDALONE:
return XML_L("document is not standalone");
case XML_ERROR_UNEXPECTED_STATE:
return XML_L("unexpected parser state - please send a bug report");
case XML_ERROR_ENTITY_DECLARED_IN_PE:
return XML_L("entity declared in parameter entity");
case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
return XML_L("requested feature requires XML_DTD support in Expat");
case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
return XML_L("cannot change setting once parsing has begun");
/* Added in 1.95.7. */
case XML_ERROR_UNBOUND_PREFIX:
return XML_L("unbound prefix");
/* Added in 1.95.8. */
case XML_ERROR_UNDECLARING_PREFIX:
return XML_L("must not undeclare prefix");
case XML_ERROR_INCOMPLETE_PE:
return XML_L("incomplete markup in parameter entity");
case XML_ERROR_XML_DECL:
return XML_L("XML declaration not well-formed");
case XML_ERROR_TEXT_DECL:
return XML_L("text declaration not well-formed");
case XML_ERROR_PUBLICID:
return XML_L("illegal character(s) in public id");
case XML_ERROR_SUSPENDED:
return XML_L("parser suspended");
case XML_ERROR_NOT_SUSPENDED:
return XML_L("parser not suspended");
case XML_ERROR_ABORTED:
return XML_L("parsing aborted");
case XML_ERROR_FINISHED:
return XML_L("parsing finished");
case XML_ERROR_SUSPEND_PE:
return XML_L("cannot suspend in external parameter entity");
/* Added in 2.0.0. */
case XML_ERROR_RESERVED_PREFIX_XML:
return XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name");
case XML_ERROR_RESERVED_PREFIX_XMLNS:
return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
case XML_ERROR_RESERVED_NAMESPACE_URI:
return XML_L("prefix must not be bound to one of the reserved namespace names");
/* Added in 2.2.5. */
case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
return XML_L("invalid argument");
}
return NULL;
}
const XML_LChar * XMLCALL
XML_ExpatVersion(void) {
/* V1 is used to string-ize the version number. However, it would
string-ize the actual version macro *names* unless we get them
substituted before being passed to V1. CPP is defined to expand
a macro, then rescan for more expansions. Thus, we use V2 to expand
the version macros, then CPP will expand the resulting V1() macro
with the correct numerals. */
/* ### I'm assuming cpp is portable in this respect... */
#define V1(a,b,c) XML_L(#a)XML_L(".")XML_L(#b)XML_L(".")XML_L(#c)
#define V2(a,b,c) XML_L("expat_")V1(a,b,c)
return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
#undef V1
#undef V2
}
XML_Expat_Version XMLCALL
XML_ExpatVersionInfo(void)
{
XML_Expat_Version version;
version.major = XML_MAJOR_VERSION;
version.minor = XML_MINOR_VERSION;
version.micro = XML_MICRO_VERSION;
return version;
}
const XML_Feature * XMLCALL
XML_GetFeatureList(void)
{
static const XML_Feature features[] = {
{XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
sizeof(XML_Char)},
{XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
sizeof(XML_LChar)},
#ifdef XML_UNICODE
{XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
#endif
#ifdef XML_UNICODE_WCHAR_T
{XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
#endif
#ifdef XML_DTD
{XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
#endif
#ifdef XML_CONTEXT_BYTES
{XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
XML_CONTEXT_BYTES},
#endif
#ifdef XML_MIN_SIZE
{XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
#endif
#ifdef XML_NS
{XML_FEATURE_NS, XML_L("XML_NS"), 0},
#endif
#ifdef XML_LARGE_SIZE
{XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
#endif
#ifdef XML_ATTR_INFO
{XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
#endif
{XML_FEATURE_END, NULL, 0}
};
return features;
}
/* Initially tag->rawName always points into the parse buffer;
for those TAG instances opened while the current parse buffer was
processed, and not yet closed, we need to store tag->rawName in a more
permanent location, since the parse buffer is about to be discarded.
*/
static XML_Bool
storeRawNames(XML_Parser parser)
{
TAG *tag = parser->m_tagStack;
while (tag) {
int bufSize;
int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
char *rawNameBuf = tag->buf + nameLen;
/* Stop if already stored. Since m_tagStack is a stack, we can stop
at the first entry that has already been copied; everything
below it in the stack is already been accounted for in a
previous call to this function.
*/
if (tag->rawName == rawNameBuf)
break;
/* For re-use purposes we need to ensure that the
size of tag->buf is a multiple of sizeof(XML_Char).
*/
bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
if (bufSize > tag->bufEnd - tag->buf) {
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_FALSE;
/* if tag->name.str points to tag->buf (only when namespace
processing is off) then we have to update it
*/
if (tag->name.str == (XML_Char *)tag->buf)
tag->name.str = (XML_Char *)temp;
/* if tag->name.localPart is set (when namespace processing is on)
then update it as well, since it will always point into tag->buf
*/
if (tag->name.localPart)
tag->name.localPart = (XML_Char *)temp + (tag->name.localPart -
(XML_Char *)tag->buf);
tag->buf = temp;
tag->bufEnd = temp + bufSize;
rawNameBuf = temp + nameLen;
}
memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
tag->rawName = rawNameBuf;
tag = tag->parent;
}
return XML_TRUE;
}
static enum XML_Error PTRCALL
contentProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doContent(parser, 0, parser->m_encoding, start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (!storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error PTRCALL
externalEntityInitProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = externalEntityInitProcessor2;
return externalEntityInitProcessor2(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor2(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
const char *next = start; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(parser->m_encoding, start, end, &next);
switch (tok) {
case XML_TOK_BOM:
/* If we are at the end of the buffer, this would cause the next stage,
i.e. externalEntityInitProcessor3, to pass control directly to
doContent (by detecting XML_TOK_NONE) without processing any xml text
declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
*/
if (next == end && !parser->m_parsingStatus.finalBuffer) {
*endPtr = next;
return XML_ERROR_NONE;
}
start = next;
break;
case XML_TOK_PARTIAL:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityInitProcessor3;
return externalEntityInitProcessor3(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor3(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
int tok;
const char *next = start; /* XmlContentTok doesn't always set the last arg */
parser->m_eventPtr = start;
tok = XmlContentTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
case XML_TOK_XML_DECL:
{
enum XML_Error result;
result = processXmlDecl(parser, 1, start, next);
if (result != XML_ERROR_NONE)
return result;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*endPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
start = next;
}
}
break;
case XML_TOK_PARTIAL:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityContentProcessor;
parser->m_tagLevel = 1;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityContentProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doContent(parser, 1, parser->m_encoding, start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (!storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error
doContent(XML_Parser parser,
int startTagLevel,
const ENCODING *enc,
const char *s,
const char *end,
const char **nextPtr,
XML_Bool haveMore)
{
/* save one level of indirection */
DTD * const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
}
else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
for (;;) {
const char *next = s; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_TRAILING_CR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
*eventEndPP = end;
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0)
return XML_ERROR_NO_ELEMENTS;
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (startTagLevel > 0) {
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_NO_ELEMENTS;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_ENTITY_REF:
{
const XML_Char *name;
ENTITY *entity;
XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (ch) {
if (parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
name = poolStoreString(&dtd->pool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&dtd->pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity or default handler.
*/
if (!dtd->hasParamEntityRefs || dtd->standalone) {
if (!entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (!entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
}
else if (!entity) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->notation)
return XML_ERROR_BINARY_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
if (!parser->m_defaultExpandInternalEntities) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name, 0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
result = processInternalEntity(parser, entity, XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
}
else if (parser->m_externalEntityRefHandler) {
const XML_Char *context;
entity->open = XML_TRUE;
context = getContext(parser);
entity->open = XML_FALSE;
if (!context)
return XML_ERROR_NO_MEMORY;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
context,
entity->base,
entity->systemId,
entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
poolDiscard(&parser->m_tempPool);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
case XML_TOK_START_TAG_NO_ATTS:
/* fall through */
case XML_TOK_START_TAG_WITH_ATTS:
{
TAG *tag;
enum XML_Error result;
XML_Char *toPtr;
if (parser->m_freeTagList) {
tag = parser->m_freeTagList;
parser->m_freeTagList = parser->m_freeTagList->parent;
}
else {
tag = (TAG *)MALLOC(parser, sizeof(TAG));
if (!tag)
return XML_ERROR_NO_MEMORY;
tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
if (!tag->buf) {
FREE(parser, tag);
return XML_ERROR_NO_MEMORY;
}
tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
}
tag->bindings = NULL;
tag->parent = parser->m_tagStack;
parser->m_tagStack = tag;
tag->name.localPart = NULL;
tag->name.prefix = NULL;
tag->rawName = s + enc->minBytesPerChar;
tag->rawNameLength = XmlNameLength(enc, tag->rawName);
++parser->m_tagLevel;
{
const char *rawNameEnd = tag->rawName + tag->rawNameLength;
const char *fromPtr = tag->rawName;
toPtr = (XML_Char *)tag->buf;
for (;;) {
int bufSize;
int convLen;
const enum XML_Convert_Result convert_res = XmlConvert(enc,
&fromPtr, rawNameEnd,
(ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1);
convLen = (int)(toPtr - (XML_Char *)tag->buf);
if ((fromPtr >= rawNameEnd) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
tag->name.strLen = convLen;
break;
}
bufSize = (int)(tag->bufEnd - tag->buf) << 1;
{
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
tag->buf = temp;
tag->bufEnd = temp + bufSize;
toPtr = (XML_Char *)temp + convLen;
}
}
}
tag->name.str = (XML_Char *)tag->buf;
*toPtr = XML_T('\0');
result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
if (result)
return result;
if (parser->m_startElementHandler)
parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
(const XML_Char **)parser->m_atts);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
break;
}
case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
/* fall through */
case XML_TOK_EMPTY_ELEMENT_WITH_ATTS:
{
const char *rawName = s + enc->minBytesPerChar;
enum XML_Error result;
BINDING *bindings = NULL;
XML_Bool noElmHandlers = XML_TRUE;
TAG_NAME name;
name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
rawName + XmlNameLength(enc, rawName));
if (!name.str)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
result = storeAtts(parser, enc, s, &name, &bindings);
if (result != XML_ERROR_NONE) {
freeBindings(parser, bindings);
return result;
}
poolFinish(&parser->m_tempPool);
if (parser->m_startElementHandler) {
parser->m_startElementHandler(parser->m_handlerArg, name.str, (const XML_Char **)parser->m_atts);
noElmHandlers = XML_FALSE;
}
if (parser->m_endElementHandler) {
if (parser->m_startElementHandler)
*eventPP = *eventEndPP;
parser->m_endElementHandler(parser->m_handlerArg, name.str);
noElmHandlers = XML_FALSE;
}
if (noElmHandlers && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
freeBindings(parser, bindings);
}
if ((parser->m_tagLevel == 0) && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
parser->m_processor = epilogProcessor;
else
return epilogProcessor(parser, next, end, nextPtr);
}
break;
case XML_TOK_END_TAG:
if (parser->m_tagLevel == startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
else {
int len;
const char *rawName;
TAG *tag = parser->m_tagStack;
parser->m_tagStack = tag->parent;
tag->parent = parser->m_freeTagList;
parser->m_freeTagList = tag;
rawName = s + enc->minBytesPerChar*2;
len = XmlNameLength(enc, rawName);
if (len != tag->rawNameLength
|| memcmp(tag->rawName, rawName, len) != 0) {
*eventPP = rawName;
return XML_ERROR_TAG_MISMATCH;
}
--parser->m_tagLevel;
if (parser->m_endElementHandler) {
const XML_Char *localPart;
const XML_Char *prefix;
XML_Char *uri;
localPart = tag->name.localPart;
if (parser->m_ns && localPart) {
/* localPart and prefix may have been overwritten in
tag->name.str, since this points to the binding->uri
buffer which gets re-used; so we have to add them again
*/
uri = (XML_Char *)tag->name.str + tag->name.uriLen;
/* don't need to check for space - already done in storeAtts() */
while (*localPart) *uri++ = *localPart++;
prefix = (XML_Char *)tag->name.prefix;
if (parser->m_ns_triplets && prefix) {
*uri++ = parser->m_namespaceSeparator;
while (*prefix) *uri++ = *prefix++;
}
*uri = XML_T('\0');
}
parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
while (tag->bindings) {
BINDING *b = tag->bindings;
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
tag->bindings = tag->bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
if (parser->m_tagLevel == 0)
return epilogProcessor(parser, next, end, nextPtr);
}
break;
case XML_TOK_CHAR_REF:
{
int n = XmlCharRefNumber(enc, s);
if (n < 0)
return XML_ERROR_BAD_CHAR_REF;
if (parser->m_characterDataHandler) {
XML_Char buf[XML_ENCODE_MAX];
parser->m_characterDataHandler(parser->m_handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_CDATA_SECT_OPEN:
{
enum XML_Error result;
if (parser->m_startCdataSectionHandler)
parser->m_startCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* Suppose you doing a transformation on a document that involves
changing only the character data. You set up a defaultHandler
and a characterDataHandler. The defaultHandler simply copies
characters through. The characterDataHandler does the
transformation and writes the characters out escaping them as
necessary. This case will fail to work if we leave out the
following two lines (because & and < inside CDATA sections will
be incorrectly escaped).
However, now we have a start/endCdataSectionHandler, so it seems
easier to let the user deal with this.
*/
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (!next) {
parser->m_processor = cdataSectionProcessor;
return result;
}
}
break;
case XML_TOK_TRAILING_RSQB:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (parser->m_characterDataHandler) {
if (MUST_CONVERT(enc, s)) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
}
else
parser->m_characterDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)end - (XML_Char *)s));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0) {
*eventPP = end;
return XML_ERROR_NO_ELEMENTS;
}
if (parser->m_tagLevel != startTagLevel) {
*eventPP = end;
return XML_ERROR_ASYNC_ENTITY;
}
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_DATA_CHARS:
{
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
}
else
charDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
case XML_TOK_PI:
if (!reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (!reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
default:
/* All of the tokens produced by XmlContentTok() have their own
* explicit cases, so this default is not strictly necessary.
* However it is a useful safety net, so we retain the code and
* simply exclude it from the coverage tests.
*
* LCOV_EXCL_START
*/
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default: ;
}
}
/* not reached */
}
/* This function does not call free() on the allocated memory, merely
* moving it to the parser's m_freeBindingList where it can be freed or
* reused as appropriate.
*/
static void
freeBindings(XML_Parser parser, BINDING *bindings)
{
while (bindings) {
BINDING *b = bindings;
/* m_startNamespaceDeclHandler will have been called for this
* binding in addBindings(), so call the end handler now.
*/
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
}
/* Precondition: all arguments must be non-NULL;
Purpose:
- normalize attributes
- check attributes for well-formedness
- generate namespace aware attribute names (URI, prefix)
- build list of attributes for startElementHandler
- default attributes
- process namespace declarations (check and report them)
- generate namespace aware element name (URI, prefix)
*/
static enum XML_Error
storeAtts(XML_Parser parser, const ENCODING *enc,
const char *attStr, TAG_NAME *tagNamePtr,
BINDING **bindingsPtr)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
ELEMENT_TYPE *elementType;
int nDefaultAtts;
const XML_Char **appAtts; /* the attribute list for the application */
int attIndex = 0;
int prefixLen;
int i;
int n;
XML_Char *uri;
int nPrefixes = 0;
BINDING *binding;
const XML_Char *localPart;
/* lookup the element type name */
elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str,0);
if (!elementType) {
const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
if (!name)
return XML_ERROR_NO_MEMORY;
elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
sizeof(ELEMENT_TYPE));
if (!elementType)
return XML_ERROR_NO_MEMORY;
if (parser->m_ns && !setElementTypePrefix(parser, elementType))
return XML_ERROR_NO_MEMORY;
}
nDefaultAtts = elementType->nDefaultAtts;
/* get the attributes from the tokenizer */
n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
if (n + nDefaultAtts > parser->m_attsSize) {
int oldAttsSize = parser->m_attsSize;
ATTRIBUTE *temp;
#ifdef XML_ATTR_INFO
XML_AttrInfo *temp2;
#endif
parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts, parser->m_attsSize * sizeof(ATTRIBUTE));
if (temp == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_atts = temp;
#ifdef XML_ATTR_INFO
temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo, parser->m_attsSize * sizeof(XML_AttrInfo));
if (temp2 == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_attInfo = temp2;
#endif
if (n > oldAttsSize)
XmlGetAttributes(enc, attStr, n, parser->m_atts);
}
appAtts = (const XML_Char **)parser->m_atts;
for (i = 0; i < n; i++) {
ATTRIBUTE *currAtt = &parser->m_atts[i];
#ifdef XML_ATTR_INFO
XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
#endif
/* add the name and value to the attribute list */
ATTRIBUTE_ID *attId = getAttributeId(parser, enc, currAtt->name,
currAtt->name
+ XmlNameLength(enc, currAtt->name));
if (!attId)
return XML_ERROR_NO_MEMORY;
#ifdef XML_ATTR_INFO
currAttInfo->nameStart = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
currAttInfo->nameEnd = currAttInfo->nameStart +
XmlNameLength(enc, currAtt->name);
currAttInfo->valueStart = parser->m_parseEndByteIndex -
(parser->m_parseEndPtr - currAtt->valuePtr);
currAttInfo->valueEnd = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->valueEnd);
#endif
/* Detect duplicate attributes by their QNames. This does not work when
namespace processing is turned on and different prefixes for the same
namespace are used. For this case we have a check further down.
*/
if ((attId->name)[-1]) {
if (enc == parser->m_encoding)
parser->m_eventPtr = parser->m_atts[i].name;
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
(attId->name)[-1] = 1;
appAtts[attIndex++] = attId->name;
if (!parser->m_atts[i].normalized) {
enum XML_Error result;
XML_Bool isCdata = XML_TRUE;
/* figure out whether declared as other than CDATA */
if (attId->maybeTokenized) {
int j;
for (j = 0; j < nDefaultAtts; j++) {
if (attId == elementType->defaultAtts[j].id) {
isCdata = elementType->defaultAtts[j].isCdata;
break;
}
}
}
/* normalize the attribute value */
result = storeAttributeValue(parser, enc, isCdata,
parser->m_atts[i].valuePtr, parser->m_atts[i].valueEnd,
&parser->m_tempPool);
if (result)
return result;
appAtts[attIndex] = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
}
else {
/* the value did not need normalizing */
appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc, parser->m_atts[i].valuePtr,
parser->m_atts[i].valueEnd);
if (appAtts[attIndex] == 0)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
}
/* handle prefixed attribute names */
if (attId->prefix) {
if (attId->xmlns) {
/* deal with namespace declarations here */
enum XML_Error result = addBinding(parser, attId->prefix, attId,
appAtts[attIndex], bindingsPtr);
if (result)
return result;
--attIndex;
}
else {
/* deal with other prefixed names later */
attIndex++;
nPrefixes++;
(attId->name)[-1] = 2;
}
}
else
attIndex++;
}
/* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
parser->m_nSpecifiedAtts = attIndex;
if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
for (i = 0; i < attIndex; i += 2)
if (appAtts[i] == elementType->idAtt->name) {
parser->m_idAttIndex = i;
break;
}
}
else
parser->m_idAttIndex = -1;
/* do attribute defaulting */
for (i = 0; i < nDefaultAtts; i++) {
const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
if (!(da->id->name)[-1] && da->value) {
if (da->id->prefix) {
if (da->id->xmlns) {
enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
da->value, bindingsPtr);
if (result)
return result;
}
else {
(da->id->name)[-1] = 2;
nPrefixes++;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
}
else {
(da->id->name)[-1] = 1;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
}
}
appAtts[attIndex] = 0;
/* expand prefixed attribute names, check for duplicates,
and clear flags that say whether attributes were specified */
i = 0;
if (nPrefixes) {
int j; /* hash table index */
unsigned long version = parser->m_nsAttsVersion;
int nsAttsSize = (int)1 << parser->m_nsAttsPower;
unsigned char oldNsAttsPower = parser->m_nsAttsPower;
/* size of hash table must be at least 2 * (# of prefixed attributes) */
if ((nPrefixes << 1) >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
NS_ATT *temp;
/* hash table size must also be a power of 2 and >= 8 */
while (nPrefixes >> parser->m_nsAttsPower++);
if (parser->m_nsAttsPower < 3)
parser->m_nsAttsPower = 3;
nsAttsSize = (int)1 << parser->m_nsAttsPower;
temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));
if (!temp) {
/* Restore actual size of memory in m_nsAtts */
parser->m_nsAttsPower = oldNsAttsPower;
return XML_ERROR_NO_MEMORY;
}
parser->m_nsAtts = temp;
version = 0; /* force re-initialization of m_nsAtts hash table */
}
/* using a version flag saves us from initializing m_nsAtts every time */
if (!version) { /* initialize version flags when version wraps around */
version = INIT_ATTS_VERSION;
for (j = nsAttsSize; j != 0; )
parser->m_nsAtts[--j].version = version;
}
parser->m_nsAttsVersion = --version;
/* expand prefixed names and check for duplicates */
for (; i < attIndex; i += 2) {
const XML_Char *s = appAtts[i];
if (s[-1] == 2) { /* prefixed */
ATTRIBUTE_ID *id;
const BINDING *b;
unsigned long uriHash;
struct siphash sip_state;
struct sipkey sip_key;
copy_salt_to_sipkey(parser, &sip_key);
sip24_init(&sip_state, &sip_key);
((XML_Char *)s)[-1] = 0; /* clear flag */
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
if (!id || !id->prefix) {
/* This code is walking through the appAtts array, dealing
* with (in this case) a prefixed attribute name. To be in
* the array, the attribute must have already been bound, so
* has to have passed through the hash table lookup once
* already. That implies that an entry for it already
* exists, so the lookup above will return a pointer to
* already allocated memory. There is no opportunaity for
* the allocator to fail, so the condition above cannot be
* fulfilled.
*
* Since it is difficult to be certain that the above
* analysis is complete, we retain the test and merely
* remove the code from coverage tests.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
b = id->prefix->binding;
if (!b)
return XML_ERROR_UNBOUND_PREFIX;
for (j = 0; j < b->uriLen; j++) {
const XML_Char c = b->uri[j];
if (!poolAppendChar(&parser->m_tempPool, c))
return XML_ERROR_NO_MEMORY;
}
sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
while (*s++ != XML_T(ASCII_COLON))
;
sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
do { /* copies null terminator */
if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
uriHash = (unsigned long)sip24_final(&sip_state);
{ /* Check hash table for duplicate of expanded name (uriName).
Derived from code in lookup(parser, HASH_TABLE *table, ...).
*/
unsigned char step = 0;
unsigned long mask = nsAttsSize - 1;
j = uriHash & mask; /* index into hash table */
while (parser->m_nsAtts[j].version == version) {
/* for speed we compare stored hash values first */
if (uriHash == parser->m_nsAtts[j].hash) {
const XML_Char *s1 = poolStart(&parser->m_tempPool);
const XML_Char *s2 = parser->m_nsAtts[j].uriName;
/* s1 is null terminated, but not s2 */
for (; *s1 == *s2 && *s1 != 0; s1++, s2++);
if (*s1 == 0)
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
if (!step)
step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
j < step ? (j += nsAttsSize - step) : (j -= step);
}
}
if (parser->m_ns_triplets) { /* append namespace separator and prefix */
parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
s = b->prefix->name;
do {
if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
}
/* store expanded name in attribute list */
s = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
appAtts[i] = s;
/* fill empty slot with new version, uriName and hash value */
parser->m_nsAtts[j].version = version;
parser->m_nsAtts[j].hash = uriHash;
parser->m_nsAtts[j].uriName = s;
if (!--nPrefixes) {
i += 2;
break;
}
}
else /* not prefixed */
((XML_Char *)s)[-1] = 0; /* clear flag */
}
}
/* clear flags for the remaining attributes */
for (; i < attIndex; i += 2)
((XML_Char *)(appAtts[i]))[-1] = 0;
for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
binding->attId->name[-1] = 0;
if (!parser->m_ns)
return XML_ERROR_NONE;
/* expand the element type name */
if (elementType->prefix) {
binding = elementType->prefix->binding;
if (!binding)
return XML_ERROR_UNBOUND_PREFIX;
localPart = tagNamePtr->str;
while (*localPart++ != XML_T(ASCII_COLON))
;
}
else if (dtd->defaultPrefix.binding) {
binding = dtd->defaultPrefix.binding;
localPart = tagNamePtr->str;
}
else
return XML_ERROR_NONE;
prefixLen = 0;
if (parser->m_ns_triplets && binding->prefix->name) {
for (; binding->prefix->name[prefixLen++];)
; /* prefixLen includes null terminator */
}
tagNamePtr->localPart = localPart;
tagNamePtr->uriLen = binding->uriLen;
tagNamePtr->prefix = binding->prefix->name;
tagNamePtr->prefixLen = prefixLen;
for (i = 0; localPart[i++];)
; /* i includes null terminator */
n = i + binding->uriLen + prefixLen;
if (n > binding->uriAlloc) {
TAG *p;
uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
if (!uri)
return XML_ERROR_NO_MEMORY;
binding->uriAlloc = n + EXPAND_SPARE;
memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
for (p = parser->m_tagStack; p; p = p->parent)
if (p->name.str == binding->uri)
p->name.str = uri;
FREE(parser, binding->uri);
binding->uri = uri;
}
/* if m_namespaceSeparator != '\0' then uri includes it already */
uri = binding->uri + binding->uriLen;
memcpy(uri, localPart, i * sizeof(XML_Char));
/* we always have a namespace separator between localPart and prefix */
if (prefixLen) {
uri += i - 1;
*uri = parser->m_namespaceSeparator; /* replace null terminator */
memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
}
tagNamePtr->str = binding->uri;
return XML_ERROR_NONE;
}
/* addBinding() overwrites the value of prefix->binding without checking.
Therefore one must keep track of the old value outside of addBinding().
*/
static enum XML_Error
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
const XML_Char *uri, BINDING **bindingsPtr)
{
static const XML_Char xmlNamespace[] = {
ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH,
ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD,
ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,
ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8, ASCII_SLASH,
ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
ASCII_e, '\0'
};
static const int xmlLen =
(int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1;
static const XML_Char xmlnsNamespace[] = {
ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH,
ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD,
ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0,
ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s,
ASCII_SLASH, '\0'
};
static const int xmlnsLen =
(int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1;
XML_Bool mustBeXML = XML_FALSE;
XML_Bool isXML = XML_TRUE;
XML_Bool isXMLNS = XML_TRUE;
BINDING *b;
int len;
/* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
if (*uri == XML_T('\0') && prefix->name)
return XML_ERROR_UNDECLARING_PREFIX;
if (prefix->name
&& prefix->name[0] == XML_T(ASCII_x)
&& prefix->name[1] == XML_T(ASCII_m)
&& prefix->name[2] == XML_T(ASCII_l)) {
/* Not allowed to bind xmlns */
if (prefix->name[3] == XML_T(ASCII_n)
&& prefix->name[4] == XML_T(ASCII_s)
&& prefix->name[5] == XML_T('\0'))
return XML_ERROR_RESERVED_PREFIX_XMLNS;
if (prefix->name[3] == XML_T('\0'))
mustBeXML = XML_TRUE;
}
for (len = 0; uri[len]; len++) {
if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
isXML = XML_FALSE;
if (!mustBeXML && isXMLNS
&& (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
isXMLNS = XML_FALSE;
}
isXML = isXML && len == xmlLen;
isXMLNS = isXMLNS && len == xmlnsLen;
if (mustBeXML != isXML)
return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
: XML_ERROR_RESERVED_NAMESPACE_URI;
if (isXMLNS)
return XML_ERROR_RESERVED_NAMESPACE_URI;
if (parser->m_namespaceSeparator)
len++;
if (parser->m_freeBindingList) {
b = parser->m_freeBindingList;
if (len > b->uriAlloc) {
XML_Char *temp = (XML_Char *)REALLOC(parser, b->uri,
sizeof(XML_Char) * (len + EXPAND_SPARE));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
b->uri = temp;
b->uriAlloc = len + EXPAND_SPARE;
}
parser->m_freeBindingList = b->nextTagBinding;
}
else {
b = (BINDING *)MALLOC(parser, sizeof(BINDING));
if (!b)
return XML_ERROR_NO_MEMORY;
b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
if (!b->uri) {
FREE(parser, b);
return XML_ERROR_NO_MEMORY;
}
b->uriAlloc = len + EXPAND_SPARE;
}
b->uriLen = len;
memcpy(b->uri, uri, len * sizeof(XML_Char));
if (parser->m_namespaceSeparator)
b->uri[len - 1] = parser->m_namespaceSeparator;
b->prefix = prefix;
b->attId = attId;
b->prevPrefixBinding = prefix->binding;
/* NULL binding when default namespace undeclared */
if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
prefix->binding = NULL;
else
prefix->binding = b;
b->nextTagBinding = *bindingsPtr;
*bindingsPtr = b;
/* if attId == NULL then we are not starting a namespace scope */
if (attId && parser->m_startNamespaceDeclHandler)
parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
prefix->binding ? uri : 0);
return XML_ERROR_NONE;
}
/* The idea here is to avoid using stack for each CDATA section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
cdataSectionProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doCdataSection(parser, parser->m_encoding, &start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
if (parser->m_parentParser) { /* we are parsing an external entity */
parser->m_processor = externalEntityContentProcessor;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
else {
parser->m_processor = contentProcessor;
return contentProcessor(parser, start, end, endPtr);
}
}
return result;
}
/* startPtr gets set to non-null if the section is closed, and to null if
the section is not yet closed.
*/
static enum XML_Error
doCdataSection(XML_Parser parser,
const ENCODING *enc,
const char **startPtr,
const char *end,
const char **nextPtr,
XML_Bool haveMore)
{
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
}
else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
*startPtr = NULL;
for (;;) {
const char *next;
int tok = XmlCdataSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_CDATA_SECT_CLOSE:
if (parser->m_endCdataSectionHandler)
parser->m_endCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* see comment under XML_TOK_CDATA_SECT_OPEN */
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_DATA_CHARS:
{
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = next;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
}
else
charDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_CDATA_SECTION;
default:
/* Every token returned by XmlCdataSectionTok() has its own
* explicit case, so this default case will never be executed.
* We retain it as a safety net and exclude it from the coverage
* statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default: ;
}
}
/* not reached */
}
#ifdef XML_DTD
/* The idea here is to avoid using stack for each IGNORE section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
ignoreSectionProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doIgnoreSection(parser, parser->m_encoding, &start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
parser->m_processor = prologProcessor;
return prologProcessor(parser, start, end, endPtr);
}
return result;
}
/* startPtr gets set to non-null is the section is closed, and to null
if the section is not yet closed.
*/
static enum XML_Error
doIgnoreSection(XML_Parser parser,
const ENCODING *enc,
const char **startPtr,
const char *end,
const char **nextPtr,
XML_Bool haveMore)
{
const char *next;
int tok;
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
}
else {
/* It's not entirely clear, but it seems the following two lines
* of code cannot be executed. The only occasions on which 'enc'
* is not 'encoding' are when this function is called
* from the internal entity processing, and IGNORE sections are an
* error in internal entities.
*
* Since it really isn't clear that this is true, we keep the code
* and just remove it from our coverage tests.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
*eventPP = s;
*startPtr = NULL;
tok = XmlIgnoreSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_IGNORE_SECT:
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
default:
/* All of the tokens that XmlIgnoreSectionTok() returns have
* explicit cases to handle them, so this default case is never
* executed. We keep it as a safety net anyway, and remove it
* from our test coverage statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
/* not reached */
}
#endif /* XML_DTD */
static enum XML_Error
initializeEncoding(XML_Parser parser)
{
const char *s;
#ifdef XML_UNICODE
char encodingBuf[128];
/* See comments abount `protoclEncodingName` in parserInit() */
if (!parser->m_protocolEncodingName)
s = NULL;
else {
int i;
for (i = 0; parser->m_protocolEncodingName[i]; i++) {
if (i == sizeof(encodingBuf) - 1
|| (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
encodingBuf[0] = '\0';
break;
}
encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
}
encodingBuf[i] = '\0';
s = encodingBuf;
}
#else
s = parser->m_protocolEncodingName;
#endif
if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(&parser->m_initEncoding, &parser->m_encoding, s))
return XML_ERROR_NONE;
return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
}
static enum XML_Error
processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
const char *s, const char *next)
{
const char *encodingName = NULL;
const XML_Char *storedEncName = NULL;
const ENCODING *newEncoding = NULL;
const char *version = NULL;
const char *versionend;
const XML_Char *storedversion = NULL;
int standalone = -1;
if (!(parser->m_ns
? XmlParseXmlDeclNS
: XmlParseXmlDecl)(isGeneralTextEntity,
parser->m_encoding,
s,
next,
&parser->m_eventPtr,
&version,
&versionend,
&encodingName,
&newEncoding,
&standalone)) {
if (isGeneralTextEntity)
return XML_ERROR_TEXT_DECL;
else
return XML_ERROR_XML_DECL;
}
if (!isGeneralTextEntity && standalone == 1) {
parser->m_dtd->standalone = XML_TRUE;
#ifdef XML_DTD
if (parser->m_paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif /* XML_DTD */
}
if (parser->m_xmlDeclHandler) {
if (encodingName != NULL) {
storedEncName = poolStoreString(&parser->m_temp2Pool,
parser->m_encoding,
encodingName,
encodingName
+ XmlNameLength(parser->m_encoding, encodingName));
if (!storedEncName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_temp2Pool);
}
if (version) {
storedversion = poolStoreString(&parser->m_temp2Pool,
parser->m_encoding,
version,
versionend - parser->m_encoding->minBytesPerChar);
if (!storedversion)
return XML_ERROR_NO_MEMORY;
}
parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName, standalone);
}
else if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_protocolEncodingName == NULL) {
if (newEncoding) {
/* Check that the specified encoding does not conflict with what
* the parser has already deduced. Do we have the same number
* of bytes in the smallest representation of a character? If
* this is UTF-16, is it the same endianness?
*/
if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
|| (newEncoding->minBytesPerChar == 2 &&
newEncoding != parser->m_encoding)) {
parser->m_eventPtr = encodingName;
return XML_ERROR_INCORRECT_ENCODING;
}
parser->m_encoding = newEncoding;
}
else if (encodingName) {
enum XML_Error result;
if (!storedEncName) {
storedEncName = poolStoreString(
&parser->m_temp2Pool, parser->m_encoding, encodingName,
encodingName + XmlNameLength(parser->m_encoding, encodingName));
if (!storedEncName)
return XML_ERROR_NO_MEMORY;
}
result = handleUnknownEncoding(parser, storedEncName);
poolClear(&parser->m_temp2Pool);
if (result == XML_ERROR_UNKNOWN_ENCODING)
parser->m_eventPtr = encodingName;
return result;
}
}
if (storedEncName || storedversion)
poolClear(&parser->m_temp2Pool);
return XML_ERROR_NONE;
}
static enum XML_Error
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
{
if (parser->m_unknownEncodingHandler) {
XML_Encoding info;
int i;
for (i = 0; i < 256; i++)
info.map[i] = -1;
info.convert = NULL;
info.data = NULL;
info.release = NULL;
if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName,
&info)) {
ENCODING *enc;
parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
if (!parser->m_unknownEncodingMem) {
if (info.release)
info.release(info.data);
return XML_ERROR_NO_MEMORY;
}
enc = (parser->m_ns
? XmlInitUnknownEncodingNS
: XmlInitUnknownEncoding)(parser->m_unknownEncodingMem,
info.map,
info.convert,
info.data);
if (enc) {
parser->m_unknownEncodingData = info.data;
parser->m_unknownEncodingRelease = info.release;
parser->m_encoding = enc;
return XML_ERROR_NONE;
}
}
if (info.release != NULL)
info.release(info.data);
}
return XML_ERROR_UNKNOWN_ENCODING;
}
static enum XML_Error PTRCALL
prologInitProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = prologProcessor;
return prologProcessor(parser, s, end, nextPtr);
}
#ifdef XML_DTD
static enum XML_Error PTRCALL
externalParEntInitProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
/* we know now that XML_Parse(Buffer) has been called,
so we consider the external parameter entity read */
parser->m_dtd->paramEntityRead = XML_TRUE;
if (parser->m_prologState.inEntityValue) {
parser->m_processor = entityValueInitProcessor;
return entityValueInitProcessor(parser, s, end, nextPtr);
}
else {
parser->m_processor = externalParEntProcessor;
return externalParEntProcessor(parser, s, end, nextPtr);
}
}
static enum XML_Error PTRCALL
entityValueInitProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
int tok;
const char *start = s;
const char *next = start;
parser->m_eventPtr = start;
for (;;) {
tok = XmlPrologTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
if (tok <= 0) {
if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, parser->m_encoding, s, end);
}
else if (tok == XML_TOK_XML_DECL) {
enum XML_Error result;
result = processXmlDecl(parser, 0, start, next);
if (result != XML_ERROR_NONE)
return result;
/* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For that
* to happen, a parameter entity parsing handler must have
* attempted to suspend the parser, which fails and raises an
* error. The parser can be aborted, but can't be suspended.
*/
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
*nextPtr = next;
/* stop scanning for text declaration - we found one */
parser->m_processor = entityValueProcessor;
return entityValueProcessor(parser, next, end, nextPtr);
}
/* If we are at the end of the buffer, this would cause XmlPrologTok to
return XML_TOK_NONE on the next call, which would then cause the
function to exit with *nextPtr set to s - that is what we want for other
tokens, but not for the BOM - we would rather like to skip it;
then, when this routine is entered the next time, XmlPrologTok will
return XML_TOK_INVALID, since the BOM is still in the buffer
*/
else if (tok == XML_TOK_BOM && next == end && !parser->m_parsingStatus.finalBuffer) {
*nextPtr = next;
return XML_ERROR_NONE;
}
/* If we get this token, we have the start of what might be a
normal tag, but not a declaration (i.e. it doesn't begin with
"<!"). In a DTD context, that isn't legal.
*/
else if (tok == XML_TOK_INSTANCE_START) {
*nextPtr = next;
return XML_ERROR_SYNTAX;
}
start = next;
parser->m_eventPtr = start;
}
}
static enum XML_Error PTRCALL
externalParEntProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next,
nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error PTRCALL
entityValueProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
const char *start = s;
const char *next = s;
const ENCODING *enc = parser->m_encoding;
int tok;
for (;;) {
tok = XmlPrologTok(enc, start, end, &next);
if (tok <= 0) {
if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, enc, s, end);
}
start = next;
}
}
#endif /* XML_DTD */
static enum XML_Error PTRCALL
prologProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
const char *next = s;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next,
nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error
doProlog(XML_Parser parser,
const ENCODING *enc,
const char *s,
const char *end,
int tok,
const char *next,
const char **nextPtr,
XML_Bool haveMore)
{
#ifdef XML_DTD
static const XML_Char externalSubsetName[] = { ASCII_HASH , '\0' };
#endif /* XML_DTD */
static const XML_Char atypeCDATA[] =
{ ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' };
static const XML_Char atypeID[] = { ASCII_I, ASCII_D, '\0' };
static const XML_Char atypeIDREF[] =
{ ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' };
static const XML_Char atypeIDREFS[] =
{ ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' };
static const XML_Char atypeENTITY[] =
{ ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' };
static const XML_Char atypeENTITIES[] = { ASCII_E, ASCII_N,
ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\0' };
static const XML_Char atypeNMTOKEN[] = {
ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' };
static const XML_Char atypeNMTOKENS[] = { ASCII_N, ASCII_M, ASCII_T,
ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\0' };
static const XML_Char notationPrefix[] = { ASCII_N, ASCII_O, ASCII_T,
ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0' };
static const XML_Char enumValueSep[] = { ASCII_PIPE, '\0' };
static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' };
/* save one level of indirection */
DTD * const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
enum XML_Content_Quant quant;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
}
else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
for (;;) {
int role;
XML_Bool handleDefault = XML_TRUE;
*eventPP = s;
*eventEndPP = next;
if (tok <= 0) {
if (haveMore && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case -XML_TOK_PROLOG_S:
tok = -tok;
break;
case XML_TOK_NONE:
#ifdef XML_DTD
/* for internal PE NOT referenced between declarations */
if (enc != parser->m_encoding && !parser->m_openInternalEntities->betweenDecl) {
*nextPtr = s;
return XML_ERROR_NONE;
}
/* WFC: PE Between Declarations - must check that PE contains
complete markup, not only for external PEs, but also for
internal PEs if the reference occurs between declarations.
*/
if (parser->m_isParamEntity || enc != parser->m_encoding) {
if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
== XML_ROLE_ERROR)
return XML_ERROR_INCOMPLETE_PE;
*nextPtr = s;
return XML_ERROR_NONE;
}
#endif /* XML_DTD */
return XML_ERROR_NO_ELEMENTS;
default:
tok = -tok;
next = end;
break;
}
}
role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
switch (role) {
case XML_ROLE_XML_DECL:
{
enum XML_Error result = processXmlDecl(parser, 0, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_NAME:
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next);
if (!parser->m_doctypeName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = NULL;
handleDefault = XML_FALSE;
}
parser->m_doctypeSysid = NULL; /* always initialize to NULL */
break;
case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
if (parser->m_startDoctypeDeclHandler) {
parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 1);
parser->m_doctypeName = NULL;
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
#ifdef XML_DTD
case XML_ROLE_TEXT_DECL:
{
enum XML_Error result = processXmlDecl(parser, 1, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
}
break;
#endif /* XML_DTD */
case XML_ROLE_DOCTYPE_PUBLIC_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
parser->m_declEntity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
XML_Char *pubId;
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
pubId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!pubId)
return XML_ERROR_NO_MEMORY;
normalizePublicId(pubId);
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = pubId;
handleDefault = XML_FALSE;
goto alreadyChecked;
}
/* fall through */
case XML_ROLE_ENTITY_PUBLIC_ID:
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
alreadyChecked:
if (dtd->keepProcessing && parser->m_declEntity) {
XML_Char *tem = poolStoreString(&dtd->pool,
enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declEntity->publicId = tem;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_PUBLIC_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_CLOSE:
if (parser->m_doctypeName) {
parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName,
parser->m_doctypeSysid, parser->m_doctypePubid, 0);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
/* parser->m_doctypeSysid will be non-NULL in the case of a previous
XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
was not set, indicating an external subset
*/
#ifdef XML_DTD
if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!entity) {
/* The external subset name "#" will have already been
* inserted into the hash table at the start of the
* external entity parsing, so no allocation will happen
* and lookup() cannot fail.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
if (parser->m_useForeignDTD)
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (!dtd->standalone &&
parser->m_notStandaloneHandler &&
!parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else if (!parser->m_doctypeSysid)
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
parser->m_useForeignDTD = XML_FALSE;
}
#endif /* XML_DTD */
if (parser->m_endDoctypeDeclHandler) {
parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_INSTANCE_START:
#ifdef XML_DTD
/* if there is no DOCTYPE declaration then now is the
last chance to read the foreign DTD
*/
if (parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!entity)
return XML_ERROR_NO_MEMORY;
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (!dtd->standalone &&
parser->m_notStandaloneHandler &&
!parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
}
#endif /* XML_DTD */
parser->m_processor = contentProcessor;
return contentProcessor(parser, s, end, nextPtr);
case XML_ROLE_ATTLIST_ELEMENT_NAME:
parser->m_declElementType = getElementType(parser, enc, s, next);
if (!parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_NAME:
parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
if (!parser->m_declAttributeId)
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeType = NULL;
parser->m_declAttributeIsId = XML_FALSE;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
parser->m_declAttributeIsCdata = XML_TRUE;
parser->m_declAttributeType = atypeCDATA;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ID:
parser->m_declAttributeIsId = XML_TRUE;
parser->m_declAttributeType = atypeID;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
parser->m_declAttributeType = atypeIDREF;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
parser->m_declAttributeType = atypeIDREFS;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
parser->m_declAttributeType = atypeENTITY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
parser->m_declAttributeType = atypeENTITIES;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
parser->m_declAttributeType = atypeNMTOKEN;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
parser->m_declAttributeType = atypeNMTOKENS;
checkAttListDeclHandler:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
const XML_Char *prefix;
if (parser->m_declAttributeType) {
prefix = enumValueSep;
}
else {
prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE
? notationPrefix
: enumValueStart);
}
if (!poolAppendString(&parser->m_tempPool, prefix))
return XML_ERROR_NO_MEMORY;
if (!poolAppend(&parser->m_tempPool, enc, s, next))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
parser->m_declAttributeIsCdata, parser->m_declAttributeIsId,
0, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType,
0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
const XML_Char *attVal;
enum XML_Error result =
storeAttributeValue(parser, enc, parser->m_declAttributeIsCdata,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar,
&dtd->pool);
if (result)
return result;
attVal = poolStart(&dtd->pool);
poolFinish(&dtd->pool);
/* ID attributes aren't allowed to have a default */
if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType,
attVal,
role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_ENTITY_VALUE:
if (dtd->keepProcessing) {
enum XML_Error result = storeEntityValue(parser, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (parser->m_declEntity) {
parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
poolFinish(&dtd->entityValuePool);
if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
parser->m_declEntity->is_param,
parser->m_declEntity->textPtr,
parser->m_declEntity->textLen,
parser->m_curBase, 0, 0, 0);
handleDefault = XML_FALSE;
}
}
else
poolDiscard(&dtd->entityValuePool);
if (result != XML_ERROR_NONE)
return result;
}
break;
case XML_ROLE_DOCTYPE_SYSTEM_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (parser->m_doctypeSysid == NULL)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
#ifdef XML_DTD
else
/* use externalSubsetName to make parser->m_doctypeSysid non-NULL
for the case where no parser->m_startDoctypeDeclHandler is set */
parser->m_doctypeSysid = externalSubsetName;
#endif /* XML_DTD */
if (!dtd->standalone
#ifdef XML_DTD
&& !parser->m_paramEntityParsing
#endif /* XML_DTD */
&& parser->m_notStandaloneHandler
&& !parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
#ifndef XML_DTD
break;
#else /* XML_DTD */
if (!parser->m_declEntity) {
parser->m_declEntity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->publicId = NULL;
}
#endif /* XML_DTD */
/* fall through */
case XML_ROLE_ENTITY_SYSTEM_ID:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!parser->m_declEntity->systemId)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->base = parser->m_curBase;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_SYSTEM_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_COMPLETE:
if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
parser->m_declEntity->is_param,
0,0,
parser->m_declEntity->base,
parser->m_declEntity->systemId,
parser->m_declEntity->publicId,
0);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_NOTATION_NAME:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
if (!parser->m_declEntity->notation)
return XML_ERROR_NO_MEMORY;
poolFinish(&dtd->pool);
if (parser->m_unparsedEntityDeclHandler) {
*eventEndPP = s;
parser->m_unparsedEntityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
parser->m_declEntity->base,
parser->m_declEntity->systemId,
parser->m_declEntity->publicId,
parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
else if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
0,0,0,
parser->m_declEntity->base,
parser->m_declEntity->systemId,
parser->m_declEntity->publicId,
parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_GENERAL_ENTITY_NAME:
{
if (XmlPredefinedEntityName(enc, s, next)) {
parser->m_declEntity = NULL;
break;
}
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (!name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name,
sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_FALSE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
}
else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
}
break;
case XML_ROLE_PARAM_ENTITY_NAME:
#ifdef XML_DTD
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (!name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
name, sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_TRUE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
}
else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
#else /* not XML_DTD */
parser->m_declEntity = NULL;
#endif /* XML_DTD */
break;
case XML_ROLE_NOTATION_NAME:
parser->m_declNotationPublicId = NULL;
parser->m_declNotationName = NULL;
if (parser->m_notationDeclHandler) {
parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next);
if (!parser->m_declNotationName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_PUBLIC_ID:
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
if (parser->m_declNotationName) { /* means m_notationDeclHandler != NULL */
XML_Char *tem = poolStoreString(&parser->m_tempPool,
enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declNotationPublicId = tem;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_SYSTEM_ID:
if (parser->m_declNotationName && parser->m_notationDeclHandler) {
const XML_Char *systemId
= poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!systemId)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_notationDeclHandler(parser->m_handlerArg,
parser->m_declNotationName,
parser->m_curBase,
systemId,
parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_NOTATION_NO_SYSTEM_ID:
if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
*eventEndPP = s;
parser->m_notationDeclHandler(parser->m_handlerArg,
parser->m_declNotationName,
parser->m_curBase,
0,
parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_ERROR:
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
/* PE references in internal subset are
not allowed within declarations. */
return XML_ERROR_PARAM_ENTITY_REF;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
default:
return XML_ERROR_SYNTAX;
}
#ifdef XML_DTD
case XML_ROLE_IGNORE_SECT:
{
enum XML_Error result;
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
handleDefault = XML_FALSE;
result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (!next) {
parser->m_processor = ignoreSectionProcessor;
return result;
}
}
break;
#endif /* XML_DTD */
case XML_ROLE_GROUP_OPEN:
if (parser->m_prologState.level >= parser->m_groupSize) {
if (parser->m_groupSize) {
char *temp = (char *)REALLOC(parser, parser->m_groupConnector, parser->m_groupSize *= 2);
if (temp == NULL) {
parser->m_groupSize /= 2;
return XML_ERROR_NO_MEMORY;
}
parser->m_groupConnector = temp;
if (dtd->scaffIndex) {
int *temp = (int *)REALLOC(parser, dtd->scaffIndex,
parser->m_groupSize * sizeof(int));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex = temp;
}
}
else {
parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32);
if (!parser->m_groupConnector) {
parser->m_groupSize = 0;
return XML_ERROR_NO_MEMORY;
}
}
}
parser->m_groupConnector[parser->m_prologState.level] = 0;
if (dtd->in_eldecl) {
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex[dtd->scaffLevel] = myindex;
dtd->scaffLevel++;
dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_SEQUENCE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
return XML_ERROR_SYNTAX;
parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
if (dtd->in_eldecl && parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_GROUP_CHOICE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
return XML_ERROR_SYNTAX;
if (dtd->in_eldecl
&& !parser->m_groupConnector[parser->m_prologState.level]
&& (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
!= XML_CTYPE_MIXED)
) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_CHOICE;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
break;
case XML_ROLE_PARAM_ENTITY_REF:
#ifdef XML_DTD
case XML_ROLE_INNER_PARAM_ENTITY_REF:
dtd->hasParamEntityRefs = XML_TRUE;
if (!parser->m_paramEntityParsing)
dtd->keepProcessing = dtd->standalone;
else {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&dtd->pool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&dtd->pool);
/* first, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity handler
*/
if (parser->m_prologState.documentEntity &&
(dtd->standalone
? !parser->m_openInternalEntities
: !dtd->hasParamEntityRefs)) {
if (!entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (!entity->is_internal) {
/* It's hard to exhaustively search the code to be sure,
* but there doesn't seem to be a way of executing the
* following line. There are two cases:
*
* If 'standalone' is false, the DTD must have no
* parameter entities or we wouldn't have passed the outer
* 'if' statement. That measn the only entity in the hash
* table is the external subset name "#" which cannot be
* given as a parameter entity name in XML syntax, so the
* lookup must have returned NULL and we don't even reach
* the test for an internal entity.
*
* If 'standalone' is true, it does not seem to be
* possible to create entities taking this code path that
* are not internal entities, so fail the test above.
*
* Because this analysis is very uncertain, the code is
* being left in place and merely removed from the
* coverage test statistics.
*/
return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
}
}
else if (!entity) {
dtd->keepProcessing = dtd->standalone;
/* cannot report skipped entities in declarations */
if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) {
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
handleDefault = XML_FALSE;
}
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
XML_Bool betweenDecl =
(role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
result = processInternalEntity(parser, entity, betweenDecl);
if (result != XML_ERROR_NONE)
return result;
handleDefault = XML_FALSE;
break;
}
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId)) {
entity->open = XML_FALSE;
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
entity->open = XML_FALSE;
handleDefault = XML_FALSE;
if (!dtd->paramEntityRead) {
dtd->keepProcessing = dtd->standalone;
break;
}
}
else {
dtd->keepProcessing = dtd->standalone;
break;
}
}
#endif /* XML_DTD */
if (!dtd->standalone &&
parser->m_notStandaloneHandler &&
!parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
break;
/* Element declaration stuff */
case XML_ROLE_ELEMENT_NAME:
if (parser->m_elementDeclHandler) {
parser->m_declElementType = getElementType(parser, enc, s, next);
if (!parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
dtd->scaffLevel = 0;
dtd->scaffCount = 0;
dtd->in_eldecl = XML_TRUE;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ANY:
case XML_ROLE_CONTENT_EMPTY:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler) {
XML_Content * content = (XML_Content *) MALLOC(parser, sizeof(XML_Content));
if (!content)
return XML_ERROR_NO_MEMORY;
content->quant = XML_CQUANT_NONE;
content->name = NULL;
content->numchildren = 0;
content->children = NULL;
content->type = ((role == XML_ROLE_CONTENT_ANY) ?
XML_CTYPE_ANY :
XML_CTYPE_EMPTY);
*eventEndPP = s;
parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, content);
handleDefault = XML_FALSE;
}
dtd->in_eldecl = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_PCDATA:
if (dtd->in_eldecl) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_MIXED;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ELEMENT:
quant = XML_CQUANT_NONE;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_OPT:
quant = XML_CQUANT_OPT;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_REP:
quant = XML_CQUANT_REP;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_PLUS:
quant = XML_CQUANT_PLUS;
elementContent:
if (dtd->in_eldecl) {
ELEMENT_TYPE *el;
const XML_Char *name;
int nameLen;
const char *nxt = (quant == XML_CQUANT_NONE
? next
: next - enc->minBytesPerChar);
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
dtd->scaffold[myindex].type = XML_CTYPE_NAME;
dtd->scaffold[myindex].quant = quant;
el = getElementType(parser, enc, s, nxt);
if (!el)
return XML_ERROR_NO_MEMORY;
name = el->name;
dtd->scaffold[myindex].name = name;
nameLen = 0;
for (; name[nameLen++]; );
dtd->contentStringLen += nameLen;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_CLOSE:
quant = XML_CQUANT_NONE;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_OPT:
quant = XML_CQUANT_OPT;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_REP:
quant = XML_CQUANT_REP;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_PLUS:
quant = XML_CQUANT_PLUS;
closeGroup:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
dtd->scaffLevel--;
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
if (dtd->scaffLevel == 0) {
if (!handleDefault) {
XML_Content *model = build_model(parser);
if (!model)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, model);
}
dtd->in_eldecl = XML_FALSE;
dtd->contentStringLen = 0;
}
}
break;
/* End element declaration stuff */
case XML_ROLE_PI:
if (!reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_COMMENT:
if (!reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_NONE:
switch (tok) {
case XML_TOK_BOM:
handleDefault = XML_FALSE;
break;
}
break;
case XML_ROLE_DOCTYPE_NONE:
if (parser->m_startDoctypeDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ENTITY_NONE:
if (dtd->keepProcessing && parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_NOTATION_NONE:
if (parser->m_notationDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTLIST_NONE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ELEMENT_NONE:
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
} /* end of big switch */
if (handleDefault && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
s = next;
tok = XmlPrologTok(enc, s, end, &next);
}
}
/* not reached */
}
static enum XML_Error PTRCALL
epilogProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
parser->m_processor = epilogProcessor;
parser->m_eventPtr = s;
for (;;) {
const char *next = NULL;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
/* report partial linebreak - it might be the last token */
case -XML_TOK_PROLOG_S:
if (parser->m_defaultHandler) {
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
}
*nextPtr = next;
return XML_ERROR_NONE;
case XML_TOK_NONE:
*nextPtr = s;
return XML_ERROR_NONE;
case XML_TOK_PROLOG_S:
if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
break;
case XML_TOK_PI:
if (!reportProcessingInstruction(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (!reportComment(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_INVALID:
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (!parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (!parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
default:
return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
}
parser->m_eventPtr = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default: ;
}
}
}
static enum XML_Error
processInternalEntity(XML_Parser parser, ENTITY *entity,
XML_Bool betweenDecl)
{
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
}
else {
openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (!openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
next, &next, XML_FALSE);
}
else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart,
textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
}
else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
static enum XML_Error PTRCALL
internalEntityProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
ENTITY *entity;
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
if (!openEntity)
return XML_ERROR_UNEXPECTED_STATE;
entity = openEntity->entity;
textStart = ((char *)entity->textPtr) + entity->processed;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
next, &next, XML_FALSE);
}
else
#endif /* XML_DTD */
result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - (char *)entity->textPtr);
return result;
}
else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
#ifdef XML_DTD
if (entity->is_param) {
int tok;
parser->m_processor = prologProcessor;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
else
#endif /* XML_DTD */
{
parser->m_processor = contentProcessor;
/* see externalEntityContentProcessor vs contentProcessor */
return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end,
nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
}
static enum XML_Error PTRCALL
errorProcessor(XML_Parser parser,
const char *UNUSED_P(s),
const char *UNUSED_P(end),
const char **UNUSED_P(nextPtr))
{
return parser->m_errorCode;
}
static enum XML_Error
storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end,
STRING_POOL *pool)
{
enum XML_Error result = appendAttributeValue(parser, enc, isCdata, ptr,
end, pool);
if (result)
return result;
if (!isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
poolChop(pool);
if (!poolAppendChar(pool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
return XML_ERROR_NONE;
}
static enum XML_Error
appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end,
STRING_POOL *pool)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
for (;;) {
const char *next;
int tok = XmlAttributeValueTok(enc, ptr, end, &next);
switch (tok) {
case XML_TOK_NONE:
return XML_ERROR_NONE;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_CHAR_REF:
{
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, ptr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BAD_CHAR_REF;
}
if (!isCdata
&& n == 0x20 /* space */
&& (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (!poolAppendChar(pool, buf[i]))
return XML_ERROR_NO_MEMORY;
}
}
break;
case XML_TOK_DATA_CHARS:
if (!poolAppend(pool, enc, ptr, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_TRAILING_CR:
next = ptr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_ATTRIBUTE_VALUE_S:
case XML_TOK_DATA_NEWLINE:
if (!isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
if (!poolAppendChar(pool, 0x20))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_ENTITY_REF:
{
const XML_Char *name;
ENTITY *entity;
char checkEntityDecl;
XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
ptr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (ch) {
if (!poolAppendChar(pool, ch))
return XML_ERROR_NO_MEMORY;
break;
}
name = poolStoreString(&parser->m_temp2Pool, enc,
ptr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&parser->m_temp2Pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal.
*/
if (pool == &dtd->pool) /* are we called from prolog? */
checkEntityDecl =
#ifdef XML_DTD
parser->m_prologState.documentEntity &&
#endif /* XML_DTD */
(dtd->standalone
? !parser->m_openInternalEntities
: !dtd->hasParamEntityRefs);
else /* if (pool == &parser->m_tempPool): we are called from content */
checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone;
if (checkEntityDecl) {
if (!entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (!entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
}
else if (!entity) {
/* Cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler.
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
/* Cannot call the default handler because this would be
out of sync with the call to the startElementHandler.
if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
reportDefault(parser, enc, ptr, next);
*/
break;
}
if (entity->open) {
if (enc == parser->m_encoding) {
/* It does not appear that this line can be executed.
*
* The "if (entity->open)" check catches recursive entity
* definitions. In order to be called with an open
* entity, it must have gone through this code before and
* been through the recursive call to
* appendAttributeValue() some lines below. That call
* sets the local encoding ("enc") to the parser's
* internal encoding (internal_utf8 or internal_utf16),
* which can never be the same as the principle encoding.
* It doesn't appear there is another code path that gets
* here with entity->open being TRUE.
*
* Since it is not certain that this logic is watertight,
* we keep the line and merely exclude it from coverage
* tests.
*/
parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
}
return XML_ERROR_RECURSIVE_ENTITY_REF;
}
if (entity->notation) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BINARY_ENTITY_REF;
}
if (!entity->textPtr) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
}
else {
enum XML_Error result;
const XML_Char *textEnd = entity->textPtr + entity->textLen;
entity->open = XML_TRUE;
result = appendAttributeValue(parser, parser->m_internalEncoding, isCdata,
(char *)entity->textPtr,
(char *)textEnd, pool);
entity->open = XML_FALSE;
if (result)
return result;
}
}
break;
default:
/* The only token returned by XmlAttributeValueTok() that does
* not have an explicit case here is XML_TOK_PARTIAL_CHAR.
* Getting that would require an entity name to contain an
* incomplete XML character (e.g. \xE2\x82); however previous
* tokenisers will have already recognised and rejected such
* names before XmlAttributeValueTok() gets a look-in. This
* default case should be retained as a safety net, but the code
* excluded from coverage tests.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
ptr = next;
}
/* not reached */
}
static enum XML_Error
storeEntityValue(XML_Parser parser,
const ENCODING *enc,
const char *entityTextPtr,
const char *entityTextEnd)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
STRING_POOL *pool = &(dtd->entityValuePool);
enum XML_Error result = XML_ERROR_NONE;
#ifdef XML_DTD
int oldInEntityValue = parser->m_prologState.inEntityValue;
parser->m_prologState.inEntityValue = 1;
#endif /* XML_DTD */
/* never return Null for the value argument in EntityDeclHandler,
since this would indicate an external entity; therefore we
have to make sure that entityValuePool.start is not null */
if (!pool->blocks) {
if (!poolGrow(pool))
return XML_ERROR_NO_MEMORY;
}
for (;;) {
const char *next;
int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
#ifdef XML_DTD
if (parser->m_isParamEntity || enc != parser->m_encoding) {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&parser->m_tempPool, enc,
entityTextPtr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&parser->m_tempPool);
if (!entity) {
/* not a well-formedness error - see XML 1.0: WFC Entity Declared */
/* cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
dtd->keepProcessing = dtd->standalone;
goto endEntityValue;
}
if (entity->open) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_RECURSIVE_ENTITY_REF;
goto endEntityValue;
}
if (entity->systemId) {
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId)) {
entity->open = XML_FALSE;
result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
goto endEntityValue;
}
entity->open = XML_FALSE;
if (!dtd->paramEntityRead)
dtd->keepProcessing = dtd->standalone;
}
else
dtd->keepProcessing = dtd->standalone;
}
else {
entity->open = XML_TRUE;
result = storeEntityValue(parser,
parser->m_internalEncoding,
(char *)entity->textPtr,
(char *)(entity->textPtr
+ entity->textLen));
entity->open = XML_FALSE;
if (result)
goto endEntityValue;
}
break;
}
#endif /* XML_DTD */
/* In the internal subset, PE references are not legal
within markup declarations, e.g entity values in this case. */
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_PARAM_ENTITY_REF;
goto endEntityValue;
case XML_TOK_NONE:
result = XML_ERROR_NONE;
goto endEntityValue;
case XML_TOK_ENTITY_REF:
case XML_TOK_DATA_CHARS:
if (!poolAppend(pool, enc, entityTextPtr, next)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
break;
case XML_TOK_TRAILING_CR:
next = entityTextPtr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_DATA_NEWLINE:
if (pool->end == pool->ptr && !poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = 0xA;
break;
case XML_TOK_CHAR_REF:
{
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, entityTextPtr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_BAD_CHAR_REF;
goto endEntityValue;
}
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (pool->end == pool->ptr && !poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = buf[i];
}
}
break;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
default:
/* This default case should be unnecessary -- all the tokens
* that XmlEntityValueTok() can return have their own explicit
* cases -- but should be retained for safety. We do however
* exclude it from the coverage statistics.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_UNEXPECTED_STATE;
goto endEntityValue;
/* LCOV_EXCL_STOP */
}
entityTextPtr = next;
}
endEntityValue:
#ifdef XML_DTD
parser->m_prologState.inEntityValue = oldInEntityValue;
#endif /* XML_DTD */
return result;
}
static void FASTCALL
normalizeLines(XML_Char *s)
{
XML_Char *p;
for (;; s++) {
if (*s == XML_T('\0'))
return;
if (*s == 0xD)
break;
}
p = s;
do {
if (*s == 0xD) {
*p++ = 0xA;
if (*++s == 0xA)
s++;
}
else
*p++ = *s++;
} while (*s);
*p = XML_T('\0');
}
static int
reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
const XML_Char *target;
XML_Char *data;
const char *tem;
if (!parser->m_processingInstructionHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
start += enc->minBytesPerChar * 2;
tem = start + XmlNameLength(enc, start);
target = poolStoreString(&parser->m_tempPool, enc, start, tem);
if (!target)
return 0;
poolFinish(&parser->m_tempPool);
data = poolStoreString(&parser->m_tempPool, enc,
XmlSkipS(enc, tem),
end - enc->minBytesPerChar*2);
if (!data)
return 0;
normalizeLines(data);
parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
poolClear(&parser->m_tempPool);
return 1;
}
static int
reportComment(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
XML_Char *data;
if (!parser->m_commentHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
data = poolStoreString(&parser->m_tempPool,
enc,
start + enc->minBytesPerChar * 4,
end - enc->minBytesPerChar * 3);
if (!data)
return 0;
normalizeLines(data);
parser->m_commentHandler(parser->m_handlerArg, data);
poolClear(&parser->m_tempPool);
return 1;
}
static void
reportDefault(XML_Parser parser, const ENCODING *enc,
const char *s, const char *end)
{
if (MUST_CONVERT(enc, s)) {
enum XML_Convert_Result convert_res;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
}
else {
/* To get here, two things must be true; the parser must be
* using a character encoding that is not the same as the
* encoding passed in, and the encoding passed in must need
* conversion to the internal format (UTF-8 unless XML_UNICODE
* is defined). The only occasions on which the encoding passed
* in is not the same as the parser's encoding are when it is
* the internal encoding (e.g. a previously defined parameter
* entity, already converted to internal format). This by
* definition doesn't need conversion, so the whole branch never
* gets executed.
*
* For safety's sake we don't delete these lines and merely
* exclude them from coverage statistics.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
do {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf, (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
*eventPP = s;
} while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
}
else
parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
}
static int
defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
XML_Bool isId, const XML_Char *value, XML_Parser parser)
{
DEFAULT_ATTRIBUTE *att;
if (value || isId) {
/* The handling of default attributes gets messed up if we have
a default which duplicates a non-default. */
int i;
for (i = 0; i < type->nDefaultAtts; i++)
if (attId == type->defaultAtts[i].id)
return 1;
if (isId && !type->idAtt && !attId->xmlns)
type->idAtt = attId;
}
if (type->nDefaultAtts == type->allocDefaultAtts) {
if (type->allocDefaultAtts == 0) {
type->allocDefaultAtts = 8;
type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(parser, type->allocDefaultAtts
* sizeof(DEFAULT_ATTRIBUTE));
if (!type->defaultAtts) {
type->allocDefaultAtts = 0;
return 0;
}
}
else {
DEFAULT_ATTRIBUTE *temp;
int count = type->allocDefaultAtts * 2;
temp = (DEFAULT_ATTRIBUTE *)
REALLOC(parser, type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
if (temp == NULL)
return 0;
type->allocDefaultAtts = count;
type->defaultAtts = temp;
}
}
att = type->defaultAtts + type->nDefaultAtts;
att->id = attId;
att->value = value;
att->isCdata = isCdata;
if (!isCdata)
attId->maybeTokenized = XML_TRUE;
type->nDefaultAtts += 1;
return 1;
}
static int
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
PREFIX *prefix;
const XML_Char *s;
for (s = elementType->name; s != name; s++) {
if (!poolAppendChar(&dtd->pool, *s))
return 0;
}
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return 0;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (!prefix)
return 0;
if (prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
break;
}
}
return 1;
}
static ATTRIBUTE_ID *
getAttributeId(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
ATTRIBUTE_ID *id;
const XML_Char *name;
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
name = poolStoreString(&dtd->pool, enc, start, end);
if (!name)
return NULL;
/* skip quotation mark - its storage will be re-used (like in name[-1]) */
++name;
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name, sizeof(ATTRIBUTE_ID));
if (!id)
return NULL;
if (id->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (!parser->m_ns)
;
else if (name[0] == XML_T(ASCII_x)
&& name[1] == XML_T(ASCII_m)
&& name[2] == XML_T(ASCII_l)
&& name[3] == XML_T(ASCII_n)
&& name[4] == XML_T(ASCII_s)
&& (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
if (name[5] == XML_T('\0'))
id->prefix = &dtd->defaultPrefix;
else
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6, sizeof(PREFIX));
id->xmlns = XML_TRUE;
}
else {
int i;
for (i = 0; name[i]; i++) {
/* attributes without prefix are *not* in the default namespace */
if (name[i] == XML_T(ASCII_COLON)) {
int j;
for (j = 0; j < i; j++) {
if (!poolAppendChar(&dtd->pool, name[j]))
return NULL;
}
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (!id->prefix)
return NULL;
if (id->prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
break;
}
}
}
}
return id;
}
#define CONTEXT_SEP XML_T(ASCII_FF)
static const XML_Char *
getContext(XML_Parser parser)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
HASH_TABLE_ITER iter;
XML_Bool needSep = XML_FALSE;
if (dtd->defaultPrefix.binding) {
int i;
int len;
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = dtd->defaultPrefix.binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++) {
if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) {
/* Because of memory caching, I don't believe this line can be
* executed.
*
* This is part of a loop copying the default prefix binding
* URI into the parser's temporary string pool. Previously,
* that URI was copied into the same string pool, with a
* terminating NUL character, as part of setContext(). When
* the pool was cleared, that leaves a block definitely big
* enough to hold the URI on the free block list of the pool.
* The URI copy in getContext() therefore cannot run out of
* memory.
*
* If the pool is used between the setContext() and
* getContext() calls, the worst it can do is leave a bigger
* block on the front of the free list. Given that this is
* all somewhat inobvious and program logic can be changed, we
* don't delete the line but we do exclude it from the test
* coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
}
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->prefixes));
for (;;) {
int i;
int len;
const XML_Char *s;
PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
if (!prefix)
break;
if (!prefix->binding) {
/* This test appears to be (justifiable) paranoia. There does
* not seem to be a way of injecting a prefix without a binding
* that doesn't get errored long before this function is called.
* The test should remain for safety's sake, so we instead
* exclude the following line from the coverage statistics.
*/
continue; /* LCOV_EXCL_LINE */
}
if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = prefix->name; *s; s++)
if (!poolAppendChar(&parser->m_tempPool, *s))
return NULL;
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = prefix->binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++)
if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
return NULL;
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->generalEntities));
for (;;) {
const XML_Char *s;
ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
if (!e)
break;
if (!e->open)
continue;
if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = e->name; *s; s++)
if (!poolAppendChar(&parser->m_tempPool, *s))
return 0;
needSep = XML_TRUE;
}
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return NULL;
return parser->m_tempPool.start;
}
static XML_Bool
setContext(XML_Parser parser, const XML_Char *context)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *s = context;
while (*context != XML_T('\0')) {
if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
ENTITY *e;
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&parser->m_tempPool), 0);
if (e)
e->open = XML_TRUE;
if (*s != XML_T('\0'))
s++;
context = s;
poolDiscard(&parser->m_tempPool);
}
else if (*s == XML_T(ASCII_EQUALS)) {
PREFIX *prefix;
if (poolLength(&parser->m_tempPool) == 0)
prefix = &dtd->defaultPrefix;
else {
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&parser->m_tempPool),
sizeof(PREFIX));
if (!prefix)
return XML_FALSE;
if (prefix->name == poolStart(&parser->m_tempPool)) {
prefix->name = poolCopyString(&dtd->pool, prefix->name);
if (!prefix->name)
return XML_FALSE;
}
poolDiscard(&parser->m_tempPool);
}
for (context = s + 1;
*context != CONTEXT_SEP && *context != XML_T('\0');
context++)
if (!poolAppendChar(&parser->m_tempPool, *context))
return XML_FALSE;
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
&parser->m_inheritedBindings) != XML_ERROR_NONE)
return XML_FALSE;
poolDiscard(&parser->m_tempPool);
if (*context != XML_T('\0'))
++context;
s = context;
}
else {
if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_FALSE;
s++;
}
}
return XML_TRUE;
}
static void FASTCALL
normalizePublicId(XML_Char *publicId)
{
XML_Char *p = publicId;
XML_Char *s;
for (s = publicId; *s; s++) {
switch (*s) {
case 0x20:
case 0xD:
case 0xA:
if (p != publicId && p[-1] != 0x20)
*p++ = 0x20;
break;
default:
*p++ = *s;
}
}
if (p != publicId && p[-1] == 0x20)
--p;
*p = XML_T('\0');
}
static DTD *
dtdCreate(const XML_Memory_Handling_Suite *ms)
{
DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD));
if (p == NULL)
return p;
poolInit(&(p->pool), ms);
poolInit(&(p->entityValuePool), ms);
hashTableInit(&(p->generalEntities), ms);
hashTableInit(&(p->elementTypes), ms);
hashTableInit(&(p->attributeIds), ms);
hashTableInit(&(p->prefixes), ms);
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableInit(&(p->paramEntities), ms);
#endif /* XML_DTD */
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
p->scaffIndex = NULL;
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
return p;
}
static void
dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms)
{
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (!e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableClear(&(p->generalEntities));
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableClear(&(p->paramEntities));
#endif /* XML_DTD */
hashTableClear(&(p->elementTypes));
hashTableClear(&(p->attributeIds));
hashTableClear(&(p->prefixes));
poolClear(&(p->pool));
poolClear(&(p->entityValuePool));
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
ms->free_fcn(p->scaffIndex);
p->scaffIndex = NULL;
ms->free_fcn(p->scaffold);
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
}
static void
dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms)
{
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (!e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableDestroy(&(p->generalEntities));
#ifdef XML_DTD
hashTableDestroy(&(p->paramEntities));
#endif /* XML_DTD */
hashTableDestroy(&(p->elementTypes));
hashTableDestroy(&(p->attributeIds));
hashTableDestroy(&(p->prefixes));
poolDestroy(&(p->pool));
poolDestroy(&(p->entityValuePool));
if (isDocEntity) {
ms->free_fcn(p->scaffIndex);
ms->free_fcn(p->scaffold);
}
ms->free_fcn(p);
}
/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
The new DTD has already been initialized.
*/
static int
dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms)
{
HASH_TABLE_ITER iter;
/* Copy the prefix table. */
hashTableIterInit(&iter, &(oldDtd->prefixes));
for (;;) {
const XML_Char *name;
const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
if (!oldP)
break;
name = poolCopyString(&(newDtd->pool), oldP->name);
if (!name)
return 0;
if (!lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
return 0;
}
hashTableIterInit(&iter, &(oldDtd->attributeIds));
/* Copy the attribute id table. */
for (;;) {
ATTRIBUTE_ID *newA;
const XML_Char *name;
const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
if (!oldA)
break;
/* Remember to allocate the scratch byte before the name. */
if (!poolAppendChar(&(newDtd->pool), XML_T('\0')))
return 0;
name = poolCopyString(&(newDtd->pool), oldA->name);
if (!name)
return 0;
++name;
newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
sizeof(ATTRIBUTE_ID));
if (!newA)
return 0;
newA->maybeTokenized = oldA->maybeTokenized;
if (oldA->prefix) {
newA->xmlns = oldA->xmlns;
if (oldA->prefix == &oldDtd->defaultPrefix)
newA->prefix = &newDtd->defaultPrefix;
else
newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldA->prefix->name, 0);
}
}
/* Copy the element type table. */
hashTableIterInit(&iter, &(oldDtd->elementTypes));
for (;;) {
int i;
ELEMENT_TYPE *newE;
const XML_Char *name;
const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (!oldE)
break;
name = poolCopyString(&(newDtd->pool), oldE->name);
if (!name)
return 0;
newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
sizeof(ELEMENT_TYPE));
if (!newE)
return 0;
if (oldE->nDefaultAtts) {
newE->defaultAtts = (DEFAULT_ATTRIBUTE *)
ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
if (!newE->defaultAtts) {
return 0;
}
}
if (oldE->idAtt)
newE->idAtt = (ATTRIBUTE_ID *)
lookup(oldParser, &(newDtd->attributeIds), oldE->idAtt->name, 0);
newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
if (oldE->prefix)
newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldE->prefix->name, 0);
for (i = 0; i < newE->nDefaultAtts; i++) {
newE->defaultAtts[i].id = (ATTRIBUTE_ID *)
lookup(oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
if (oldE->defaultAtts[i].value) {
newE->defaultAtts[i].value
= poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
if (!newE->defaultAtts[i].value)
return 0;
}
else
newE->defaultAtts[i].value = NULL;
}
}
/* Copy the entity tables. */
if (!copyEntityTable(oldParser,
&(newDtd->generalEntities),
&(newDtd->pool),
&(oldDtd->generalEntities)))
return 0;
#ifdef XML_DTD
if (!copyEntityTable(oldParser,
&(newDtd->paramEntities),
&(newDtd->pool),
&(oldDtd->paramEntities)))
return 0;
newDtd->paramEntityRead = oldDtd->paramEntityRead;
#endif /* XML_DTD */
newDtd->keepProcessing = oldDtd->keepProcessing;
newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
newDtd->standalone = oldDtd->standalone;
/* Don't want deep copying for scaffolding */
newDtd->in_eldecl = oldDtd->in_eldecl;
newDtd->scaffold = oldDtd->scaffold;
newDtd->contentStringLen = oldDtd->contentStringLen;
newDtd->scaffSize = oldDtd->scaffSize;
newDtd->scaffLevel = oldDtd->scaffLevel;
newDtd->scaffIndex = oldDtd->scaffIndex;
return 1;
} /* End dtdCopy */
static int
copyEntityTable(XML_Parser oldParser,
HASH_TABLE *newTable,
STRING_POOL *newPool,
const HASH_TABLE *oldTable)
{
HASH_TABLE_ITER iter;
const XML_Char *cachedOldBase = NULL;
const XML_Char *cachedNewBase = NULL;
hashTableIterInit(&iter, oldTable);
for (;;) {
ENTITY *newE;
const XML_Char *name;
const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
if (!oldE)
break;
name = poolCopyString(newPool, oldE->name);
if (!name)
return 0;
newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
if (!newE)
return 0;
if (oldE->systemId) {
const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
if (!tem)
return 0;
newE->systemId = tem;
if (oldE->base) {
if (oldE->base == cachedOldBase)
newE->base = cachedNewBase;
else {
cachedOldBase = oldE->base;
tem = poolCopyString(newPool, cachedOldBase);
if (!tem)
return 0;
cachedNewBase = newE->base = tem;
}
}
if (oldE->publicId) {
tem = poolCopyString(newPool, oldE->publicId);
if (!tem)
return 0;
newE->publicId = tem;
}
}
else {
const XML_Char *tem = poolCopyStringN(newPool, oldE->textPtr,
oldE->textLen);
if (!tem)
return 0;
newE->textPtr = tem;
newE->textLen = oldE->textLen;
}
if (oldE->notation) {
const XML_Char *tem = poolCopyString(newPool, oldE->notation);
if (!tem)
return 0;
newE->notation = tem;
}
newE->is_param = oldE->is_param;
newE->is_internal = oldE->is_internal;
}
return 1;
}
#define INIT_POWER 6
static XML_Bool FASTCALL
keyeq(KEY s1, KEY s2)
{
for (; *s1 == *s2; s1++, s2++)
if (*s1 == 0)
return XML_TRUE;
return XML_FALSE;
}
static size_t
keylen(KEY s)
{
size_t len = 0;
for (; *s; s++, len++);
return len;
}
static void
copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key)
{
key->k[0] = 0;
key->k[1] = get_hash_secret_salt(parser);
}
static unsigned long FASTCALL
hash(XML_Parser parser, KEY s)
{
struct siphash state;
struct sipkey key;
(void)sip24_valid;
copy_salt_to_sipkey(parser, &key);
sip24_init(&state, &key);
sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
return (unsigned long)sip24_final(&state);
}
static NAMED *
lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize)
{
size_t i;
if (table->size == 0) {
size_t tsize;
if (!createSize)
return NULL;
table->power = INIT_POWER;
/* table->size is a power of 2 */
table->size = (size_t)1 << INIT_POWER;
tsize = table->size * sizeof(NAMED *);
table->v = (NAMED **)table->mem->malloc_fcn(tsize);
if (!table->v) {
table->size = 0;
return NULL;
}
memset(table->v, 0, tsize);
i = hash(parser, name) & ((unsigned long)table->size - 1);
}
else {
unsigned long h = hash(parser, name);
unsigned long mask = (unsigned long)table->size - 1;
unsigned char step = 0;
i = h & mask;
while (table->v[i]) {
if (keyeq(name, table->v[i]->name))
return table->v[i];
if (!step)
step = PROBE_STEP(h, mask, table->power);
i < step ? (i += table->size - step) : (i -= step);
}
if (!createSize)
return NULL;
/* check for overflow (table is half full) */
if (table->used >> (table->power - 1)) {
unsigned char newPower = table->power + 1;
size_t newSize = (size_t)1 << newPower;
unsigned long newMask = (unsigned long)newSize - 1;
size_t tsize = newSize * sizeof(NAMED *);
NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize);
if (!newV)
return NULL;
memset(newV, 0, tsize);
for (i = 0; i < table->size; i++)
if (table->v[i]) {
unsigned long newHash = hash(parser, table->v[i]->name);
size_t j = newHash & newMask;
step = 0;
while (newV[j]) {
if (!step)
step = PROBE_STEP(newHash, newMask, newPower);
j < step ? (j += newSize - step) : (j -= step);
}
newV[j] = table->v[i];
}
table->mem->free_fcn(table->v);
table->v = newV;
table->power = newPower;
table->size = newSize;
i = h & newMask;
step = 0;
while (table->v[i]) {
if (!step)
step = PROBE_STEP(h, newMask, newPower);
i < step ? (i += newSize - step) : (i -= step);
}
}
}
table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize);
if (!table->v[i])
return NULL;
memset(table->v[i], 0, createSize);
table->v[i]->name = name;
(table->used)++;
return table->v[i];
}
static void FASTCALL
hashTableClear(HASH_TABLE *table)
{
size_t i;
for (i = 0; i < table->size; i++) {
table->mem->free_fcn(table->v[i]);
table->v[i] = NULL;
}
table->used = 0;
}
static void FASTCALL
hashTableDestroy(HASH_TABLE *table)
{
size_t i;
for (i = 0; i < table->size; i++)
table->mem->free_fcn(table->v[i]);
table->mem->free_fcn(table->v);
}
static void FASTCALL
hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms)
{
p->power = 0;
p->size = 0;
p->used = 0;
p->v = NULL;
p->mem = ms;
}
static void FASTCALL
hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table)
{
iter->p = table->v;
iter->end = iter->p + table->size;
}
static NAMED * FASTCALL
hashTableIterNext(HASH_TABLE_ITER *iter)
{
while (iter->p != iter->end) {
NAMED *tem = *(iter->p)++;
if (tem)
return tem;
}
return NULL;
}
static void FASTCALL
poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms)
{
pool->blocks = NULL;
pool->freeBlocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
pool->mem = ms;
}
static void FASTCALL
poolClear(STRING_POOL *pool)
{
if (!pool->freeBlocks)
pool->freeBlocks = pool->blocks;
else {
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
p->next = pool->freeBlocks;
pool->freeBlocks = p;
p = tem;
}
}
pool->blocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
}
static void FASTCALL
poolDestroy(STRING_POOL *pool)
{
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
p = pool->freeBlocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
}
static XML_Char *
poolAppend(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end)
{
if (!pool->ptr && !poolGrow(pool))
return NULL;
for (;;) {
const enum XML_Convert_Result convert_res = XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
if (!poolGrow(pool))
return NULL;
}
return pool->start;
}
static const XML_Char * FASTCALL
poolCopyString(STRING_POOL *pool, const XML_Char *s)
{
do {
if (!poolAppendChar(pool, *s))
return NULL;
} while (*s++);
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char *
poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n)
{
if (!pool->ptr && !poolGrow(pool)) {
/* The following line is unreachable given the current usage of
* poolCopyStringN(). Currently it is called from exactly one
* place to copy the text of a simple general entity. By that
* point, the name of the entity is already stored in the pool, so
* pool->ptr cannot be NULL.
*
* If poolCopyStringN() is used elsewhere as it well might be,
* this line may well become executable again. Regardless, this
* sort of check shouldn't be removed lightly, so we just exclude
* it from the coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
for (; n > 0; --n, s++) {
if (!poolAppendChar(pool, *s))
return NULL;
}
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char * FASTCALL
poolAppendString(STRING_POOL *pool, const XML_Char *s)
{
while (*s) {
if (!poolAppendChar(pool, *s))
return NULL;
s++;
}
return pool->start;
}
static XML_Char *
poolStoreString(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end)
{
if (!poolAppend(pool, enc, ptr, end))
return NULL;
if (pool->ptr == pool->end && !poolGrow(pool))
return NULL;
*(pool->ptr)++ = 0;
return pool->start;
}
static size_t
poolBytesToAllocateFor(int blockSize)
{
/* Unprotected math would be:
** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
**
** Detect overflow, avoiding _signed_ overflow undefined behavior
** For a + b * c we check b * c in isolation first, so that addition of a
** on top has no chance of making us accept a small non-negative number
*/
const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
if (blockSize <= 0)
return 0;
if (blockSize > (int)(INT_MAX / stretch))
return 0;
{
const int stretchedBlockSize = blockSize * (int)stretch;
const int bytesToAllocate = (int)(
offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
if (bytesToAllocate < 0)
return 0;
return (size_t)bytesToAllocate;
}
}
static XML_Bool FASTCALL
poolGrow(STRING_POOL *pool)
{
if (pool->freeBlocks) {
if (pool->start == 0) {
pool->blocks = pool->freeBlocks;
pool->freeBlocks = pool->freeBlocks->next;
pool->blocks->next = NULL;
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
pool->ptr = pool->start;
return XML_TRUE;
}
if (pool->end - pool->start < pool->freeBlocks->size) {
BLOCK *tem = pool->freeBlocks->next;
pool->freeBlocks->next = pool->blocks;
pool->blocks = pool->freeBlocks;
pool->freeBlocks = tem;
memcpy(pool->blocks->s, pool->start,
(pool->end - pool->start) * sizeof(XML_Char));
pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
return XML_TRUE;
}
}
if (pool->blocks && pool->start == pool->blocks->s) {
BLOCK *temp;
int blockSize = (int)((unsigned)(pool->end - pool->start)*2U);
size_t bytesToAllocate;
/* NOTE: Needs to be calculated prior to calling `realloc`
to avoid dangling pointers: */
const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX/2 bytes have already been allocated. This isn't
* readily testable, since it is unlikely that an average
* machine will have that much memory, so we exclude it from the
* coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
temp = (BLOCK *)
pool->mem->realloc_fcn(pool->blocks, (unsigned)bytesToAllocate);
if (temp == NULL)
return XML_FALSE;
pool->blocks = temp;
pool->blocks->size = blockSize;
pool->ptr = pool->blocks->s + offsetInsideBlock;
pool->start = pool->blocks->s;
pool->end = pool->start + blockSize;
}
else {
BLOCK *tem;
int blockSize = (int)(pool->end - pool->start);
size_t bytesToAllocate;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX bytes have already been allocated (which is prevented
* by various pieces of program logic, not least this one, never
* mind the unlikelihood of actually having that much memory) or
* the pool control fields have been corrupted (which could
* conceivably happen in an extremely buggy user handler
* function). Either way it isn't readily testable, so we
* exclude it from the coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
if (blockSize < INIT_BLOCK_SIZE)
blockSize = INIT_BLOCK_SIZE;
else {
/* Detect overflow, avoiding _signed_ overflow undefined behavior */
if ((int)((unsigned)blockSize * 2U) < 0) {
return XML_FALSE;
}
blockSize *= 2;
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate);
if (!tem)
return XML_FALSE;
tem->size = blockSize;
tem->next = pool->blocks;
pool->blocks = tem;
if (pool->ptr != pool->start)
memcpy(tem->s, pool->start,
(pool->ptr - pool->start) * sizeof(XML_Char));
pool->ptr = tem->s + (pool->ptr - pool->start);
pool->start = tem->s;
pool->end = tem->s + blockSize;
}
return XML_TRUE;
}
static int FASTCALL
nextScaffoldPart(XML_Parser parser)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
CONTENT_SCAFFOLD * me;
int next;
if (!dtd->scaffIndex) {
dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
if (!dtd->scaffIndex)
return -1;
dtd->scaffIndex[0] = 0;
}
if (dtd->scaffCount >= dtd->scaffSize) {
CONTENT_SCAFFOLD *temp;
if (dtd->scaffold) {
temp = (CONTENT_SCAFFOLD *)
REALLOC(parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize *= 2;
}
else {
temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
* sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
}
dtd->scaffold = temp;
}
next = dtd->scaffCount++;
me = &dtd->scaffold[next];
if (dtd->scaffLevel) {
CONTENT_SCAFFOLD *parent = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel-1]];
if (parent->lastchild) {
dtd->scaffold[parent->lastchild].nextsib = next;
}
if (!parent->childcnt)
parent->firstchild = next;
parent->lastchild = next;
parent->childcnt++;
}
me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
return next;
}
static void
build_node(XML_Parser parser,
int src_node,
XML_Content *dest,
XML_Content **contpos,
XML_Char **strpos)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
dest->type = dtd->scaffold[src_node].type;
dest->quant = dtd->scaffold[src_node].quant;
if (dest->type == XML_CTYPE_NAME) {
const XML_Char *src;
dest->name = *strpos;
src = dtd->scaffold[src_node].name;
for (;;) {
*(*strpos)++ = *src;
if (!*src)
break;
src++;
}
dest->numchildren = 0;
dest->children = NULL;
}
else {
unsigned int i;
int cn;
dest->numchildren = dtd->scaffold[src_node].childcnt;
dest->children = *contpos;
*contpos += dest->numchildren;
for (i = 0, cn = dtd->scaffold[src_node].firstchild;
i < dest->numchildren;
i++, cn = dtd->scaffold[cn].nextsib) {
build_node(parser, cn, &(dest->children[i]), contpos, strpos);
}
dest->name = NULL;
}
}
static XML_Content *
build_model (XML_Parser parser)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
XML_Content *ret;
XML_Content *cpos;
XML_Char * str;
int allocsize = (dtd->scaffCount * sizeof(XML_Content)
+ (dtd->contentStringLen * sizeof(XML_Char)));
ret = (XML_Content *)MALLOC(parser, allocsize);
if (!ret)
return NULL;
str = (XML_Char *) (&ret[dtd->scaffCount]);
cpos = &ret[1];
build_node(parser, 0, ret, &cpos, &str);
return ret;
}
static ELEMENT_TYPE *
getElementType(XML_Parser parser,
const ENCODING *enc,
const char *ptr,
const char *end)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
ELEMENT_TYPE *ret;
if (!name)
return NULL;
ret = (ELEMENT_TYPE *) lookup(parser, &dtd->elementTypes, name, sizeof(ELEMENT_TYPE));
if (!ret)
return NULL;
if (ret->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (!setElementTypePrefix(parser, ret))
return NULL;
}
return ret;
}
static XML_Char *
copyString(const XML_Char *s,
const XML_Memory_Handling_Suite *memsuite)
{
int charsRequired = 0;
XML_Char *result;
/* First determine how long the string is */
while (s[charsRequired] != 0) {
charsRequired++;
}
/* Include the terminator */
charsRequired++;
/* Now allocate space for the copy */
result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
if (result == NULL)
return NULL;
/* Copy the original into place */
memcpy(result, s, charsRequired * sizeof(XML_Char));
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/good_537_0 |
crossvul-cpp_data_good_4362_2 | #include <xml_relax_ng.h>
static void dealloc(xmlRelaxNGPtr schema)
{
NOKOGIRI_DEBUG_START(schema);
xmlRelaxNGFree(schema);
NOKOGIRI_DEBUG_END(schema);
}
/*
* call-seq:
* validate_document(document)
*
* Validate a Nokogiri::XML::Document against this RelaxNG schema.
*/
static VALUE validate_document(VALUE self, VALUE document)
{
xmlDocPtr doc;
xmlRelaxNGPtr schema;
VALUE errors;
xmlRelaxNGValidCtxtPtr valid_ctxt;
Data_Get_Struct(self, xmlRelaxNG, schema);
Data_Get_Struct(document, xmlDoc, doc);
errors = rb_ary_new();
valid_ctxt = xmlRelaxNGNewValidCtxt(schema);
if(NULL == valid_ctxt) {
/* we have a problem */
rb_raise(rb_eRuntimeError, "Could not create a validation context");
}
#ifdef HAVE_XMLRELAXNGSETVALIDSTRUCTUREDERRORS
xmlRelaxNGSetValidStructuredErrors(
valid_ctxt,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
xmlRelaxNGValidateDoc(valid_ctxt, doc);
xmlRelaxNGFreeValidCtxt(valid_ctxt);
return errors;
}
/*
* call-seq:
* read_memory(string)
*
* Create a new RelaxNG from the contents of +string+
*/
static VALUE read_memory(int argc, VALUE *argv, VALUE klass)
{
VALUE content;
VALUE parse_options;
xmlRelaxNGParserCtxtPtr ctx;
xmlRelaxNGPtr schema;
VALUE errors;
VALUE rb_schema;
int scanned_args = 0;
scanned_args = rb_scan_args(argc, argv, "11", &content, &parse_options);
if (scanned_args == 1) {
parse_options = rb_const_get(rb_const_get(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
}
ctx = xmlRelaxNGNewMemParserCtxt((const char *)StringValuePtr(content), (int)RSTRING_LEN(content));
errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS
xmlRelaxNGSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlRelaxNGParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlRelaxNGFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
rb_iv_set(rb_schema, "@parse_options", parse_options);
return rb_schema;
}
/*
* call-seq:
* from_document(doc)
*
* Create a new RelaxNG schema from the Nokogiri::XML::Document +doc+
*/
static VALUE from_document(int argc, VALUE *argv, VALUE klass)
{
VALUE document;
VALUE parse_options;
xmlDocPtr doc;
xmlRelaxNGParserCtxtPtr ctx;
xmlRelaxNGPtr schema;
VALUE errors;
VALUE rb_schema;
int scanned_args = 0;
scanned_args = rb_scan_args(argc, argv, "11", &document, &parse_options);
Data_Get_Struct(document, xmlDoc, doc);
doc = doc->doc; /* In case someone passes us a node. ugh. */
if (scanned_args == 1) {
parse_options = rb_const_get(rb_const_get(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
}
ctx = xmlRelaxNGNewDocParserCtxt(doc);
errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS
xmlRelaxNGSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlRelaxNGParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlRelaxNGFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
rb_iv_set(rb_schema, "@parse_options", parse_options);
return rb_schema;
}
VALUE cNokogiriXmlRelaxNG;
void init_xml_relax_ng()
{
VALUE nokogiri = rb_define_module("Nokogiri");
VALUE xml = rb_define_module_under(nokogiri, "XML");
VALUE klass = rb_define_class_under(xml, "RelaxNG", cNokogiriXmlSchema);
cNokogiriXmlRelaxNG = klass;
rb_define_singleton_method(klass, "read_memory", read_memory, -1);
rb_define_singleton_method(klass, "from_document", from_document, -1);
rb_define_private_method(klass, "validate_document", validate_document, 1);
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/good_4362_2 |
crossvul-cpp_data_good_4362_3 | #include <xml_schema.h>
static void dealloc(xmlSchemaPtr schema)
{
NOKOGIRI_DEBUG_START(schema);
xmlSchemaFree(schema);
NOKOGIRI_DEBUG_END(schema);
}
/*
* call-seq:
* validate_document(document)
*
* Validate a Nokogiri::XML::Document against this Schema.
*/
static VALUE validate_document(VALUE self, VALUE document)
{
xmlDocPtr doc;
xmlSchemaPtr schema;
xmlSchemaValidCtxtPtr valid_ctxt;
VALUE errors;
Data_Get_Struct(self, xmlSchema, schema);
Data_Get_Struct(document, xmlDoc, doc);
errors = rb_ary_new();
valid_ctxt = xmlSchemaNewValidCtxt(schema);
if(NULL == valid_ctxt) {
/* we have a problem */
rb_raise(rb_eRuntimeError, "Could not create a validation context");
}
#ifdef HAVE_XMLSCHEMASETVALIDSTRUCTUREDERRORS
xmlSchemaSetValidStructuredErrors(
valid_ctxt,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
xmlSchemaValidateDoc(valid_ctxt, doc);
xmlSchemaFreeValidCtxt(valid_ctxt);
return errors;
}
/*
* call-seq:
* validate_file(filename)
*
* Validate a file against this Schema.
*/
static VALUE validate_file(VALUE self, VALUE rb_filename)
{
xmlSchemaPtr schema;
xmlSchemaValidCtxtPtr valid_ctxt;
const char *filename ;
VALUE errors;
Data_Get_Struct(self, xmlSchema, schema);
filename = (const char*)StringValueCStr(rb_filename) ;
errors = rb_ary_new();
valid_ctxt = xmlSchemaNewValidCtxt(schema);
if(NULL == valid_ctxt) {
/* we have a problem */
rb_raise(rb_eRuntimeError, "Could not create a validation context");
}
#ifdef HAVE_XMLSCHEMASETVALIDSTRUCTUREDERRORS
xmlSchemaSetValidStructuredErrors(
valid_ctxt,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
xmlSchemaValidateFile(valid_ctxt, filename, 0);
xmlSchemaFreeValidCtxt(valid_ctxt);
return errors;
}
/*
* call-seq:
* read_memory(string)
*
* Create a new Schema from the contents of +string+
*/
static VALUE read_memory(int argc, VALUE *argv, VALUE klass)
{
VALUE content;
VALUE parse_options;
int parse_options_int;
xmlSchemaParserCtxtPtr ctx;
xmlSchemaPtr schema;
VALUE errors;
VALUE rb_schema;
int scanned_args = 0;
scanned_args = rb_scan_args(argc, argv, "11", &content, &parse_options);
if (scanned_args == 1) {
parse_options = rb_const_get(rb_const_get(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
}
parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0));
ctx = xmlSchemaNewMemParserCtxt((const char *)StringValuePtr(content), (int)RSTRING_LEN(content));
errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
xmlSchemaSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlSchemaParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlSchemaFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
rb_iv_set(rb_schema, "@parse_options", parse_options);
return rb_schema;
}
/* Schema creation will remove and deallocate "blank" nodes.
* If those blank nodes have been exposed to Ruby, they could get freed
* out from under the VALUE pointer. This function checks to see if any of
* those nodes have been exposed to Ruby, and if so we should raise an exception.
*/
static int has_blank_nodes_p(VALUE cache)
{
long i;
if (NIL_P(cache)) {
return 0;
}
for (i = 0; i < RARRAY_LEN(cache); i++) {
xmlNodePtr node;
VALUE element = rb_ary_entry(cache, i);
Data_Get_Struct(element, xmlNode, node);
if (xmlIsBlankNode(node)) {
return 1;
}
}
return 0;
}
/*
* call-seq:
* from_document(doc)
*
* Create a new Schema from the Nokogiri::XML::Document +doc+
*/
static VALUE from_document(int argc, VALUE *argv, VALUE klass)
{
VALUE document;
VALUE parse_options;
int parse_options_int;
xmlDocPtr doc;
xmlSchemaParserCtxtPtr ctx;
xmlSchemaPtr schema;
VALUE errors;
VALUE rb_schema;
int scanned_args = 0;
scanned_args = rb_scan_args(argc, argv, "11", &document, &parse_options);
Data_Get_Struct(document, xmlDoc, doc);
doc = doc->doc; /* In case someone passes us a node. ugh. */
if (scanned_args == 1) {
parse_options = rb_const_get(rb_const_get(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
}
parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0));
if (has_blank_nodes_p(DOC_NODE_CACHE(doc))) {
rb_raise(rb_eArgError, "Creating a schema from a document that has blank nodes exposed to Ruby is dangerous");
}
ctx = xmlSchemaNewDocParserCtxt(doc);
errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
xmlSchemaSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlSchemaParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlSchemaFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
rb_iv_set(rb_schema, "@parse_options", parse_options);
return rb_schema;
return Qnil;
}
VALUE cNokogiriXmlSchema;
void init_xml_schema()
{
VALUE nokogiri = rb_define_module("Nokogiri");
VALUE xml = rb_define_module_under(nokogiri, "XML");
VALUE klass = rb_define_class_under(xml, "Schema", rb_cObject);
cNokogiriXmlSchema = klass;
rb_define_singleton_method(klass, "read_memory", read_memory, -1);
rb_define_singleton_method(klass, "from_document", from_document, -1);
rb_define_private_method(klass, "validate_document", validate_document, 1);
rb_define_private_method(klass, "validate_file", validate_file, 1);
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/good_4362_3 |
crossvul-cpp_data_bad_537_0 | /* 19ac4776051591216f1874e34ee99b6a43a3784c8bd7d70efeb9258dd22b906a (2.2.6+)
__ __ _
___\ \/ /_ __ __ _| |_
/ _ \\ /| '_ \ / _` | __|
| __// \| |_) | (_| | |_
\___/_/\_\ .__/ \__,_|\__|
|_| XML parser
Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
Copyright (c) 2000-2017 Expat development team
Licensed under the MIT license:
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.
*/
#if !defined(_GNU_SOURCE)
# define _GNU_SOURCE 1 /* syscall prototype */
#endif
#include <stddef.h>
#include <string.h> /* memset(), memcpy() */
#include <assert.h>
#include <limits.h> /* UINT_MAX */
#include <stdio.h> /* fprintf */
#include <stdlib.h> /* getenv */
#ifdef _WIN32
#define getpid GetCurrentProcessId
#else
#include <sys/time.h> /* gettimeofday() */
#include <sys/types.h> /* getpid() */
#include <unistd.h> /* getpid() */
#include <fcntl.h> /* O_RDONLY */
#include <errno.h>
#endif
#define XML_BUILDING_EXPAT 1
#ifdef _WIN32
#include "winconfig.h"
#elif defined(HAVE_EXPAT_CONFIG_H)
#include <expat_config.h>
#endif /* ndef _WIN32 */
#include "ascii.h"
#include "expat.h"
#include "siphash.h"
#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
# if defined(HAVE_GETRANDOM)
# include <sys/random.h> /* getrandom */
# else
# include <unistd.h> /* syscall */
# include <sys/syscall.h> /* SYS_getrandom */
# endif
# if ! defined(GRND_NONBLOCK)
# define GRND_NONBLOCK 0x0001
# endif /* defined(GRND_NONBLOCK) */
#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
#if defined(HAVE_LIBBSD) \
&& (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
# include <bsd/stdlib.h>
#endif
#if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
#if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \
&& !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \
&& !defined(XML_DEV_URANDOM) \
&& !defined(_WIN32) \
&& !defined(XML_POOR_ENTROPY)
# error \
You do not have support for any sources of high quality entropy \
enabled. For end user security, that is probably not what you want. \
\
Your options include: \
* Linux + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
* Linux + glibc <2.25 (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
* BSD / macOS >=10.7 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
* BSD / macOS <10.7 (arc4random): HAVE_ARC4RANDOM, \
* libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
* libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
* Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \
* Windows (RtlGenRandom): _WIN32. \
\
If insist on not using any of these, bypass this error by defining \
XML_POOR_ENTROPY; you have been warned. \
\
If you have reasons to patch this detection code away or need changes \
to the build system, please open a bug. Thank you!
#endif
#ifdef XML_UNICODE
#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
#define XmlConvert XmlUtf16Convert
#define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
#define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
#define XmlEncode XmlUtf16Encode
/* Using pointer subtraction to convert to integer type. */
#define MUST_CONVERT(enc, s) (!(enc)->isUtf16 || (((char *)(s) - (char *)NULL) & 1))
typedef unsigned short ICHAR;
#else
#define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
#define XmlConvert XmlUtf8Convert
#define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
#define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
#define XmlEncode XmlUtf8Encode
#define MUST_CONVERT(enc, s) (!(enc)->isUtf8)
typedef char ICHAR;
#endif
#ifndef XML_NS
#define XmlInitEncodingNS XmlInitEncoding
#define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
#undef XmlGetInternalEncodingNS
#define XmlGetInternalEncodingNS XmlGetInternalEncoding
#define XmlParseXmlDeclNS XmlParseXmlDecl
#endif
#ifdef XML_UNICODE
#ifdef XML_UNICODE_WCHAR_T
#define XML_T(x) (const wchar_t)x
#define XML_L(x) L ## x
#else
#define XML_T(x) (const unsigned short)x
#define XML_L(x) x
#endif
#else
#define XML_T(x) x
#define XML_L(x) x
#endif
/* Round up n to be a multiple of sz, where sz is a power of 2. */
#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
/* Do safe (NULL-aware) pointer arithmetic */
#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
#include "internal.h"
#include "xmltok.h"
#include "xmlrole.h"
typedef const XML_Char *KEY;
typedef struct {
KEY name;
} NAMED;
typedef struct {
NAMED **v;
unsigned char power;
size_t size;
size_t used;
const XML_Memory_Handling_Suite *mem;
} HASH_TABLE;
static size_t
keylen(KEY s);
static void
copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key);
/* For probing (after a collision) we need a step size relative prime
to the hash table size, which is a power of 2. We use double-hashing,
since we can calculate a second hash value cheaply by taking those bits
of the first hash value that were discarded (masked out) when the table
index was calculated: index = hash & mask, where mask = table->size - 1.
We limit the maximum step size to table->size / 4 (mask >> 2) and make
it odd, since odd numbers are always relative prime to a power of 2.
*/
#define SECOND_HASH(hash, mask, power) \
((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2))
#define PROBE_STEP(hash, mask, power) \
((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
typedef struct {
NAMED **p;
NAMED **end;
} HASH_TABLE_ITER;
#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
#define INIT_DATA_BUF_SIZE 1024
#define INIT_ATTS_SIZE 16
#define INIT_ATTS_VERSION 0xFFFFFFFF
#define INIT_BLOCK_SIZE 1024
#define INIT_BUFFER_SIZE 1024
#define EXPAND_SPARE 24
typedef struct binding {
struct prefix *prefix;
struct binding *nextTagBinding;
struct binding *prevPrefixBinding;
const struct attribute_id *attId;
XML_Char *uri;
int uriLen;
int uriAlloc;
} BINDING;
typedef struct prefix {
const XML_Char *name;
BINDING *binding;
} PREFIX;
typedef struct {
const XML_Char *str;
const XML_Char *localPart;
const XML_Char *prefix;
int strLen;
int uriLen;
int prefixLen;
} TAG_NAME;
/* TAG represents an open element.
The name of the element is stored in both the document and API
encodings. The memory buffer 'buf' is a separately-allocated
memory area which stores the name. During the XML_Parse()/
XMLParseBuffer() when the element is open, the memory for the 'raw'
version of the name (in the document encoding) is shared with the
document buffer. If the element is open across calls to
XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to
contain the 'raw' name as well.
A parser re-uses these structures, maintaining a list of allocated
TAG objects in a free list.
*/
typedef struct tag {
struct tag *parent; /* parent of this element */
const char *rawName; /* tagName in the original encoding */
int rawNameLength;
TAG_NAME name; /* tagName in the API encoding */
char *buf; /* buffer for name components */
char *bufEnd; /* end of the buffer */
BINDING *bindings;
} TAG;
typedef struct {
const XML_Char *name;
const XML_Char *textPtr;
int textLen; /* length in XML_Chars */
int processed; /* # of processed bytes - when suspended */
const XML_Char *systemId;
const XML_Char *base;
const XML_Char *publicId;
const XML_Char *notation;
XML_Bool open;
XML_Bool is_param;
XML_Bool is_internal; /* true if declared in internal subset outside PE */
} ENTITY;
typedef struct {
enum XML_Content_Type type;
enum XML_Content_Quant quant;
const XML_Char * name;
int firstchild;
int lastchild;
int childcnt;
int nextsib;
} CONTENT_SCAFFOLD;
#define INIT_SCAFFOLD_ELEMENTS 32
typedef struct block {
struct block *next;
int size;
XML_Char s[1];
} BLOCK;
typedef struct {
BLOCK *blocks;
BLOCK *freeBlocks;
const XML_Char *end;
XML_Char *ptr;
XML_Char *start;
const XML_Memory_Handling_Suite *mem;
} STRING_POOL;
/* The XML_Char before the name is used to determine whether
an attribute has been specified. */
typedef struct attribute_id {
XML_Char *name;
PREFIX *prefix;
XML_Bool maybeTokenized;
XML_Bool xmlns;
} ATTRIBUTE_ID;
typedef struct {
const ATTRIBUTE_ID *id;
XML_Bool isCdata;
const XML_Char *value;
} DEFAULT_ATTRIBUTE;
typedef struct {
unsigned long version;
unsigned long hash;
const XML_Char *uriName;
} NS_ATT;
typedef struct {
const XML_Char *name;
PREFIX *prefix;
const ATTRIBUTE_ID *idAtt;
int nDefaultAtts;
int allocDefaultAtts;
DEFAULT_ATTRIBUTE *defaultAtts;
} ELEMENT_TYPE;
typedef struct {
HASH_TABLE generalEntities;
HASH_TABLE elementTypes;
HASH_TABLE attributeIds;
HASH_TABLE prefixes;
STRING_POOL pool;
STRING_POOL entityValuePool;
/* false once a parameter entity reference has been skipped */
XML_Bool keepProcessing;
/* true once an internal or external PE reference has been encountered;
this includes the reference to an external subset */
XML_Bool hasParamEntityRefs;
XML_Bool standalone;
#ifdef XML_DTD
/* indicates if external PE has been read */
XML_Bool paramEntityRead;
HASH_TABLE paramEntities;
#endif /* XML_DTD */
PREFIX defaultPrefix;
/* === scaffolding for building content model === */
XML_Bool in_eldecl;
CONTENT_SCAFFOLD *scaffold;
unsigned contentStringLen;
unsigned scaffSize;
unsigned scaffCount;
int scaffLevel;
int *scaffIndex;
} DTD;
typedef struct open_internal_entity {
const char *internalEventPtr;
const char *internalEventEndPtr;
struct open_internal_entity *next;
ENTITY *entity;
int startTagLevel;
XML_Bool betweenDecl; /* WFC: PE Between Declarations */
} OPEN_INTERNAL_ENTITY;
typedef enum XML_Error PTRCALL Processor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr);
static Processor prologProcessor;
static Processor prologInitProcessor;
static Processor contentProcessor;
static Processor cdataSectionProcessor;
#ifdef XML_DTD
static Processor ignoreSectionProcessor;
static Processor externalParEntProcessor;
static Processor externalParEntInitProcessor;
static Processor entityValueProcessor;
static Processor entityValueInitProcessor;
#endif /* XML_DTD */
static Processor epilogProcessor;
static Processor errorProcessor;
static Processor externalEntityInitProcessor;
static Processor externalEntityInitProcessor2;
static Processor externalEntityInitProcessor3;
static Processor externalEntityContentProcessor;
static Processor internalEntityProcessor;
static enum XML_Error
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName);
static enum XML_Error
processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
const char *s, const char *next);
static enum XML_Error
initializeEncoding(XML_Parser parser);
static enum XML_Error
doProlog(XML_Parser parser, const ENCODING *enc, const char *s,
const char *end, int tok, const char *next, const char **nextPtr,
XML_Bool haveMore);
static enum XML_Error
processInternalEntity(XML_Parser parser, ENTITY *entity,
XML_Bool betweenDecl);
static enum XML_Error
doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
const char *start, const char *end, const char **endPtr,
XML_Bool haveMore);
static enum XML_Error
doCdataSection(XML_Parser parser, const ENCODING *, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore);
#ifdef XML_DTD
static enum XML_Error
doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr,
const char *end, const char **nextPtr, XML_Bool haveMore);
#endif /* XML_DTD */
static void
freeBindings(XML_Parser parser, BINDING *bindings);
static enum XML_Error
storeAtts(XML_Parser parser, const ENCODING *, const char *s,
TAG_NAME *tagNamePtr, BINDING **bindingsPtr);
static enum XML_Error
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
const XML_Char *uri, BINDING **bindingsPtr);
static int
defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata,
XML_Bool isId, const XML_Char *dfltValue, XML_Parser parser);
static enum XML_Error
storeAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
const char *, const char *, STRING_POOL *);
static enum XML_Error
appendAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
const char *, const char *, STRING_POOL *);
static ATTRIBUTE_ID *
getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static int
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *);
static enum XML_Error
storeEntityValue(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static int
reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end);
static int
reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static void
reportDefault(XML_Parser parser, const ENCODING *enc, const char *start,
const char *end);
static const XML_Char * getContext(XML_Parser parser);
static XML_Bool
setContext(XML_Parser parser, const XML_Char *context);
static void FASTCALL normalizePublicId(XML_Char *s);
static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms);
/* do not call if m_parentParser != NULL */
static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
static void
dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms);
static int
dtdCopy(XML_Parser oldParser,
DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms);
static int
copyEntityTable(XML_Parser oldParser,
HASH_TABLE *, STRING_POOL *, const HASH_TABLE *);
static NAMED *
lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize);
static void FASTCALL
hashTableInit(HASH_TABLE *, const XML_Memory_Handling_Suite *ms);
static void FASTCALL hashTableClear(HASH_TABLE *);
static void FASTCALL hashTableDestroy(HASH_TABLE *);
static void FASTCALL
hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *);
static NAMED * FASTCALL hashTableIterNext(HASH_TABLE_ITER *);
static void FASTCALL
poolInit(STRING_POOL *, const XML_Memory_Handling_Suite *ms);
static void FASTCALL poolClear(STRING_POOL *);
static void FASTCALL poolDestroy(STRING_POOL *);
static XML_Char *
poolAppend(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *
poolStoreString(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
static const XML_Char * FASTCALL
poolCopyString(STRING_POOL *pool, const XML_Char *s);
static const XML_Char *
poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n);
static const XML_Char * FASTCALL
poolAppendString(STRING_POOL *pool, const XML_Char *s);
static int FASTCALL nextScaffoldPart(XML_Parser parser);
static XML_Content * build_model(XML_Parser parser);
static ELEMENT_TYPE *
getElementType(XML_Parser parser, const ENCODING *enc,
const char *ptr, const char *end);
static XML_Char *copyString(const XML_Char *s,
const XML_Memory_Handling_Suite *memsuite);
static unsigned long generate_hash_secret_salt(XML_Parser parser);
static XML_Bool startParsing(XML_Parser parser);
static XML_Parser
parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep,
DTD *dtd);
static void
parserInit(XML_Parser parser, const XML_Char *encodingName);
#define poolStart(pool) ((pool)->start)
#define poolEnd(pool) ((pool)->ptr)
#define poolLength(pool) ((pool)->ptr - (pool)->start)
#define poolChop(pool) ((void)--(pool->ptr))
#define poolLastChar(pool) (((pool)->ptr)[-1])
#define poolDiscard(pool) ((pool)->ptr = (pool)->start)
#define poolFinish(pool) ((pool)->start = (pool)->ptr)
#define poolAppendChar(pool, c) \
(((pool)->ptr == (pool)->end && !poolGrow(pool)) \
? 0 \
: ((*((pool)->ptr)++ = c), 1))
struct XML_ParserStruct {
/* The first member must be m_userData so that the XML_GetUserData
macro works. */
void *m_userData;
void *m_handlerArg;
char *m_buffer;
const XML_Memory_Handling_Suite m_mem;
/* first character to be parsed */
const char *m_bufferPtr;
/* past last character to be parsed */
char *m_bufferEnd;
/* allocated end of m_buffer */
const char *m_bufferLim;
XML_Index m_parseEndByteIndex;
const char *m_parseEndPtr;
XML_Char *m_dataBuf;
XML_Char *m_dataBufEnd;
XML_StartElementHandler m_startElementHandler;
XML_EndElementHandler m_endElementHandler;
XML_CharacterDataHandler m_characterDataHandler;
XML_ProcessingInstructionHandler m_processingInstructionHandler;
XML_CommentHandler m_commentHandler;
XML_StartCdataSectionHandler m_startCdataSectionHandler;
XML_EndCdataSectionHandler m_endCdataSectionHandler;
XML_DefaultHandler m_defaultHandler;
XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
XML_NotationDeclHandler m_notationDeclHandler;
XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
XML_NotStandaloneHandler m_notStandaloneHandler;
XML_ExternalEntityRefHandler m_externalEntityRefHandler;
XML_Parser m_externalEntityRefHandlerArg;
XML_SkippedEntityHandler m_skippedEntityHandler;
XML_UnknownEncodingHandler m_unknownEncodingHandler;
XML_ElementDeclHandler m_elementDeclHandler;
XML_AttlistDeclHandler m_attlistDeclHandler;
XML_EntityDeclHandler m_entityDeclHandler;
XML_XmlDeclHandler m_xmlDeclHandler;
const ENCODING *m_encoding;
INIT_ENCODING m_initEncoding;
const ENCODING *m_internalEncoding;
const XML_Char *m_protocolEncodingName;
XML_Bool m_ns;
XML_Bool m_ns_triplets;
void *m_unknownEncodingMem;
void *m_unknownEncodingData;
void *m_unknownEncodingHandlerData;
void (XMLCALL *m_unknownEncodingRelease)(void *);
PROLOG_STATE m_prologState;
Processor *m_processor;
enum XML_Error m_errorCode;
const char *m_eventPtr;
const char *m_eventEndPtr;
const char *m_positionPtr;
OPEN_INTERNAL_ENTITY *m_openInternalEntities;
OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
XML_Bool m_defaultExpandInternalEntities;
int m_tagLevel;
ENTITY *m_declEntity;
const XML_Char *m_doctypeName;
const XML_Char *m_doctypeSysid;
const XML_Char *m_doctypePubid;
const XML_Char *m_declAttributeType;
const XML_Char *m_declNotationName;
const XML_Char *m_declNotationPublicId;
ELEMENT_TYPE *m_declElementType;
ATTRIBUTE_ID *m_declAttributeId;
XML_Bool m_declAttributeIsCdata;
XML_Bool m_declAttributeIsId;
DTD *m_dtd;
const XML_Char *m_curBase;
TAG *m_tagStack;
TAG *m_freeTagList;
BINDING *m_inheritedBindings;
BINDING *m_freeBindingList;
int m_attsSize;
int m_nSpecifiedAtts;
int m_idAttIndex;
ATTRIBUTE *m_atts;
NS_ATT *m_nsAtts;
unsigned long m_nsAttsVersion;
unsigned char m_nsAttsPower;
#ifdef XML_ATTR_INFO
XML_AttrInfo *m_attInfo;
#endif
POSITION m_position;
STRING_POOL m_tempPool;
STRING_POOL m_temp2Pool;
char *m_groupConnector;
unsigned int m_groupSize;
XML_Char m_namespaceSeparator;
XML_Parser m_parentParser;
XML_ParsingStatus m_parsingStatus;
#ifdef XML_DTD
XML_Bool m_isParamEntity;
XML_Bool m_useForeignDTD;
enum XML_ParamEntityParsing m_paramEntityParsing;
#endif
unsigned long m_hash_secret_salt;
};
#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p),(s)))
#define FREE(parser, p) (parser->m_mem.free_fcn((p)))
XML_Parser XMLCALL
XML_ParserCreate(const XML_Char *encodingName)
{
return XML_ParserCreate_MM(encodingName, NULL, NULL);
}
XML_Parser XMLCALL
XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep)
{
XML_Char tmp[2];
*tmp = nsSep;
return XML_ParserCreate_MM(encodingName, NULL, tmp);
}
static const XML_Char implicitContext[] = {
ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h, ASCII_t, ASCII_t, ASCII_p,
ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g,
ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9,
ASCII_9, ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,
ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0'
};
/* To avoid warnings about unused functions: */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
/* Obtain entropy on Linux 3.17+ */
static int
writeRandomBytes_getrandom_nonblock(void * target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const unsigned int getrandomFlags = GRND_NONBLOCK;
do {
void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const int bytesWrittenMore =
#if defined(HAVE_GETRANDOM)
getrandom(currentTarget, bytesToWrite, getrandomFlags);
#else
syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
#endif
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
return success;
}
#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
/* Extract entropy from /dev/urandom */
static int
writeRandomBytes_dev_urandom(void * target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
const int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
return 0;
}
do {
void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
const size_t bytesToWrite = count - bytesWrittenTotal;
const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
if (bytesWrittenMore > 0) {
bytesWrittenTotal += bytesWrittenMore;
if (bytesWrittenTotal >= count)
success = 1;
}
} while (! success && (errno == EINTR));
close(fd);
return success;
}
#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
static void
writeRandomBytes_arc4random(void * target, size_t count) {
size_t bytesWrittenTotal = 0;
while (bytesWrittenTotal < count) {
const uint32_t random32 = arc4random();
size_t i = 0;
for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
i++, bytesWrittenTotal++) {
const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
((uint8_t *)target)[bytesWrittenTotal] = random8;
}
}
}
#endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
#ifdef _WIN32
typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG);
HMODULE _Expat_LoadLibrary(LPCTSTR filename); /* see loadlibrary.c */
/* Obtain entropy on Windows XP / Windows Server 2003 and later.
* Hint on RtlGenRandom and the following article from libsodium.
*
* Michael Howard: Cryptographically Secure Random number on Windows without using CryptoAPI
* https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/
*/
static int
writeRandomBytes_RtlGenRandom(void * target, size_t count) {
int success = 0; /* full count bytes written? */
const HMODULE advapi32 = _Expat_LoadLibrary(TEXT("ADVAPI32.DLL"));
if (advapi32) {
const RTLGENRANDOM_FUNC RtlGenRandom
= (RTLGENRANDOM_FUNC)GetProcAddress(advapi32, "SystemFunction036");
if (RtlGenRandom) {
if (RtlGenRandom((PVOID)target, (ULONG)count) == TRUE) {
success = 1;
}
}
FreeLibrary(advapi32);
}
return success;
}
#endif /* _WIN32 */
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
static unsigned long
gather_time_entropy(void)
{
#ifdef _WIN32
FILETIME ft;
GetSystemTimeAsFileTime(&ft); /* never fails */
return ft.dwHighDateTime ^ ft.dwLowDateTime;
#else
struct timeval tv;
int gettimeofday_res;
gettimeofday_res = gettimeofday(&tv, NULL);
#if defined(NDEBUG)
(void)gettimeofday_res;
#else
assert (gettimeofday_res == 0);
#endif /* defined(NDEBUG) */
/* Microseconds time is <20 bits entropy */
return tv.tv_usec;
#endif
}
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
static unsigned long
ENTROPY_DEBUG(const char * label, unsigned long entropy) {
const char * const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) {
fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n",
label,
(int)sizeof(entropy) * 2, entropy,
(unsigned long)sizeof(entropy));
}
return entropy;
}
static unsigned long
generate_hash_secret_salt(XML_Parser parser)
{
unsigned long entropy;
(void)parser;
/* "Failproof" high quality providers: */
#if defined(HAVE_ARC4RANDOM_BUF)
arc4random_buf(&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random_buf", entropy);
#elif defined(HAVE_ARC4RANDOM)
writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random", entropy);
#else
/* Try high quality providers first .. */
#ifdef _WIN32
if (writeRandomBytes_RtlGenRandom((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("RtlGenRandom", entropy);
}
#elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("getrandom", entropy);
}
#endif
#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("/dev/urandom", entropy);
}
#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
/* .. and self-made low quality for backup: */
/* Process ID is 0 bits entropy if attacker has local access */
entropy = gather_time_entropy() ^ getpid();
/* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
if (sizeof(unsigned long) == 4) {
return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
} else {
return ENTROPY_DEBUG("fallback(8)",
entropy * (unsigned long)2305843009213693951ULL);
}
#endif
}
static unsigned long
get_hash_secret_salt(XML_Parser parser) {
if (parser->m_parentParser != NULL)
return get_hash_secret_salt(parser->m_parentParser);
return parser->m_hash_secret_salt;
}
static XML_Bool /* only valid for root parser */
startParsing(XML_Parser parser)
{
/* hash functions must be initialized before setContext() is called */
if (parser->m_hash_secret_salt == 0)
parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
if (parser->m_ns) {
/* implicit context only set for root parser, since child
parsers (i.e. external entity parsers) will inherit it
*/
return setContext(parser, implicitContext);
}
return XML_TRUE;
}
XML_Parser XMLCALL
XML_ParserCreate_MM(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep)
{
return parserCreate(encodingName, memsuite, nameSep, NULL);
}
static XML_Parser
parserCreate(const XML_Char *encodingName,
const XML_Memory_Handling_Suite *memsuite,
const XML_Char *nameSep,
DTD *dtd)
{
XML_Parser parser;
if (memsuite) {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)
memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = memsuite->malloc_fcn;
mtemp->realloc_fcn = memsuite->realloc_fcn;
mtemp->free_fcn = memsuite->free_fcn;
}
}
else {
XML_Memory_Handling_Suite *mtemp;
parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
if (parser != NULL) {
mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
mtemp->malloc_fcn = malloc;
mtemp->realloc_fcn = realloc;
mtemp->free_fcn = free;
}
}
if (!parser)
return parser;
parser->m_buffer = NULL;
parser->m_bufferLim = NULL;
parser->m_attsSize = INIT_ATTS_SIZE;
parser->m_atts = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
if (parser->m_atts == NULL) {
FREE(parser, parser);
return NULL;
}
#ifdef XML_ATTR_INFO
parser->m_attInfo = (XML_AttrInfo*)MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));
if (parser->m_attInfo == NULL) {
FREE(parser, parser->m_atts);
FREE(parser, parser);
return NULL;
}
#endif
parser->m_dataBuf = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
if (parser->m_dataBuf == NULL) {
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
if (dtd)
parser->m_dtd = dtd;
else {
parser->m_dtd = dtdCreate(&parser->m_mem);
if (parser->m_dtd == NULL) {
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, parser->m_attInfo);
#endif
FREE(parser, parser);
return NULL;
}
}
parser->m_freeBindingList = NULL;
parser->m_freeTagList = NULL;
parser->m_freeInternalEntities = NULL;
parser->m_groupSize = 0;
parser->m_groupConnector = NULL;
parser->m_unknownEncodingHandler = NULL;
parser->m_unknownEncodingHandlerData = NULL;
parser->m_namespaceSeparator = ASCII_EXCL;
parser->m_ns = XML_FALSE;
parser->m_ns_triplets = XML_FALSE;
parser->m_nsAtts = NULL;
parser->m_nsAttsVersion = 0;
parser->m_nsAttsPower = 0;
parser->m_protocolEncodingName = NULL;
poolInit(&parser->m_tempPool, &(parser->m_mem));
poolInit(&parser->m_temp2Pool, &(parser->m_mem));
parserInit(parser, encodingName);
if (encodingName && !parser->m_protocolEncodingName) {
XML_ParserFree(parser);
return NULL;
}
if (nameSep) {
parser->m_ns = XML_TRUE;
parser->m_internalEncoding = XmlGetInternalEncodingNS();
parser->m_namespaceSeparator = *nameSep;
}
else {
parser->m_internalEncoding = XmlGetInternalEncoding();
}
return parser;
}
static void
parserInit(XML_Parser parser, const XML_Char *encodingName)
{
parser->m_processor = prologInitProcessor;
XmlPrologStateInit(&parser->m_prologState);
if (encodingName != NULL) {
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
}
parser->m_curBase = NULL;
XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
parser->m_userData = NULL;
parser->m_handlerArg = NULL;
parser->m_startElementHandler = NULL;
parser->m_endElementHandler = NULL;
parser->m_characterDataHandler = NULL;
parser->m_processingInstructionHandler = NULL;
parser->m_commentHandler = NULL;
parser->m_startCdataSectionHandler = NULL;
parser->m_endCdataSectionHandler = NULL;
parser->m_defaultHandler = NULL;
parser->m_startDoctypeDeclHandler = NULL;
parser->m_endDoctypeDeclHandler = NULL;
parser->m_unparsedEntityDeclHandler = NULL;
parser->m_notationDeclHandler = NULL;
parser->m_startNamespaceDeclHandler = NULL;
parser->m_endNamespaceDeclHandler = NULL;
parser->m_notStandaloneHandler = NULL;
parser->m_externalEntityRefHandler = NULL;
parser->m_externalEntityRefHandlerArg = parser;
parser->m_skippedEntityHandler = NULL;
parser->m_elementDeclHandler = NULL;
parser->m_attlistDeclHandler = NULL;
parser->m_entityDeclHandler = NULL;
parser->m_xmlDeclHandler = NULL;
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer;
parser->m_parseEndByteIndex = 0;
parser->m_parseEndPtr = NULL;
parser->m_declElementType = NULL;
parser->m_declAttributeId = NULL;
parser->m_declEntity = NULL;
parser->m_doctypeName = NULL;
parser->m_doctypeSysid = NULL;
parser->m_doctypePubid = NULL;
parser->m_declAttributeType = NULL;
parser->m_declNotationName = NULL;
parser->m_declNotationPublicId = NULL;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeIsId = XML_FALSE;
memset(&parser->m_position, 0, sizeof(POSITION));
parser->m_errorCode = XML_ERROR_NONE;
parser->m_eventPtr = NULL;
parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
parser->m_openInternalEntities = NULL;
parser->m_defaultExpandInternalEntities = XML_TRUE;
parser->m_tagLevel = 0;
parser->m_tagStack = NULL;
parser->m_inheritedBindings = NULL;
parser->m_nSpecifiedAtts = 0;
parser->m_unknownEncodingMem = NULL;
parser->m_unknownEncodingRelease = NULL;
parser->m_unknownEncodingData = NULL;
parser->m_parentParser = NULL;
parser->m_parsingStatus.parsing = XML_INITIALIZED;
#ifdef XML_DTD
parser->m_isParamEntity = XML_FALSE;
parser->m_useForeignDTD = XML_FALSE;
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif
parser->m_hash_secret_salt = 0;
}
/* moves list of bindings to m_freeBindingList */
static void FASTCALL
moveToFreeBindingList(XML_Parser parser, BINDING *bindings)
{
while (bindings) {
BINDING *b = bindings;
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
}
}
XML_Bool XMLCALL
XML_ParserReset(XML_Parser parser, const XML_Char *encodingName)
{
TAG *tStk;
OPEN_INTERNAL_ENTITY *openEntityList;
if (parser == NULL)
return XML_FALSE;
if (parser->m_parentParser)
return XML_FALSE;
/* move m_tagStack to m_freeTagList */
tStk = parser->m_tagStack;
while (tStk) {
TAG *tag = tStk;
tStk = tStk->parent;
tag->parent = parser->m_freeTagList;
moveToFreeBindingList(parser, tag->bindings);
tag->bindings = NULL;
parser->m_freeTagList = tag;
}
/* move m_openInternalEntities to m_freeInternalEntities */
openEntityList = parser->m_openInternalEntities;
while (openEntityList) {
OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
openEntityList = openEntity->next;
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
moveToFreeBindingList(parser, parser->m_inheritedBindings);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
poolClear(&parser->m_tempPool);
poolClear(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
parser->m_protocolEncodingName = NULL;
parserInit(parser, encodingName);
dtdReset(parser->m_dtd, &parser->m_mem);
return XML_TRUE;
}
enum XML_Status XMLCALL
XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName)
{
if (parser == NULL)
return XML_STATUS_ERROR;
/* Block after XML_Parse()/XML_ParseBuffer() has been called.
XXX There's no way for the caller to determine which of the
XXX possible error cases caused the XML_STATUS_ERROR return.
*/
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_STATUS_ERROR;
/* Get rid of any previous encoding name */
FREE(parser, (void *)parser->m_protocolEncodingName);
if (encodingName == NULL)
/* No new encoding name */
parser->m_protocolEncodingName = NULL;
else {
/* Copy the new encoding name into allocated memory */
parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
if (!parser->m_protocolEncodingName)
return XML_STATUS_ERROR;
}
return XML_STATUS_OK;
}
XML_Parser XMLCALL
XML_ExternalEntityParserCreate(XML_Parser oldParser,
const XML_Char *context,
const XML_Char *encodingName)
{
XML_Parser parser = oldParser;
DTD *newDtd = NULL;
DTD *oldDtd;
XML_StartElementHandler oldStartElementHandler;
XML_EndElementHandler oldEndElementHandler;
XML_CharacterDataHandler oldCharacterDataHandler;
XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
XML_CommentHandler oldCommentHandler;
XML_StartCdataSectionHandler oldStartCdataSectionHandler;
XML_EndCdataSectionHandler oldEndCdataSectionHandler;
XML_DefaultHandler oldDefaultHandler;
XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
XML_NotationDeclHandler oldNotationDeclHandler;
XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
XML_NotStandaloneHandler oldNotStandaloneHandler;
XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
XML_SkippedEntityHandler oldSkippedEntityHandler;
XML_UnknownEncodingHandler oldUnknownEncodingHandler;
XML_ElementDeclHandler oldElementDeclHandler;
XML_AttlistDeclHandler oldAttlistDeclHandler;
XML_EntityDeclHandler oldEntityDeclHandler;
XML_XmlDeclHandler oldXmlDeclHandler;
ELEMENT_TYPE * oldDeclElementType;
void *oldUserData;
void *oldHandlerArg;
XML_Bool oldDefaultExpandInternalEntities;
XML_Parser oldExternalEntityRefHandlerArg;
#ifdef XML_DTD
enum XML_ParamEntityParsing oldParamEntityParsing;
int oldInEntityValue;
#endif
XML_Bool oldns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
unsigned long oldhash_secret_salt;
/* Validate the oldParser parameter before we pull everything out of it */
if (oldParser == NULL)
return NULL;
/* Stash the original parser contents on the stack */
oldDtd = parser->m_dtd;
oldStartElementHandler = parser->m_startElementHandler;
oldEndElementHandler = parser->m_endElementHandler;
oldCharacterDataHandler = parser->m_characterDataHandler;
oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
oldCommentHandler = parser->m_commentHandler;
oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
oldDefaultHandler = parser->m_defaultHandler;
oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
oldNotationDeclHandler = parser->m_notationDeclHandler;
oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
oldNotStandaloneHandler = parser->m_notStandaloneHandler;
oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
oldSkippedEntityHandler = parser->m_skippedEntityHandler;
oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
oldElementDeclHandler = parser->m_elementDeclHandler;
oldAttlistDeclHandler = parser->m_attlistDeclHandler;
oldEntityDeclHandler = parser->m_entityDeclHandler;
oldXmlDeclHandler = parser->m_xmlDeclHandler;
oldDeclElementType = parser->m_declElementType;
oldUserData = parser->m_userData;
oldHandlerArg = parser->m_handlerArg;
oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
#ifdef XML_DTD
oldParamEntityParsing = parser->m_paramEntityParsing;
oldInEntityValue = parser->m_prologState.inEntityValue;
#endif
oldns_triplets = parser->m_ns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
oldhash_secret_salt = parser->m_hash_secret_salt;
#ifdef XML_DTD
if (!context)
newDtd = oldDtd;
#endif /* XML_DTD */
/* Note that the magical uses of the pre-processor to make field
access look more like C++ require that `parser' be overwritten
here. This makes this function more painful to follow than it
would be otherwise.
*/
if (parser->m_ns) {
XML_Char tmp[2];
*tmp = parser->m_namespaceSeparator;
parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
}
else {
parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
}
if (!parser)
return NULL;
parser->m_startElementHandler = oldStartElementHandler;
parser->m_endElementHandler = oldEndElementHandler;
parser->m_characterDataHandler = oldCharacterDataHandler;
parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
parser->m_commentHandler = oldCommentHandler;
parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
parser->m_defaultHandler = oldDefaultHandler;
parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
parser->m_notationDeclHandler = oldNotationDeclHandler;
parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
parser->m_notStandaloneHandler = oldNotStandaloneHandler;
parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
parser->m_skippedEntityHandler = oldSkippedEntityHandler;
parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
parser->m_elementDeclHandler = oldElementDeclHandler;
parser->m_attlistDeclHandler = oldAttlistDeclHandler;
parser->m_entityDeclHandler = oldEntityDeclHandler;
parser->m_xmlDeclHandler = oldXmlDeclHandler;
parser->m_declElementType = oldDeclElementType;
parser->m_userData = oldUserData;
if (oldUserData == oldHandlerArg)
parser->m_handlerArg = parser->m_userData;
else
parser->m_handlerArg = parser;
if (oldExternalEntityRefHandlerArg != oldParser)
parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
parser->m_ns_triplets = oldns_triplets;
parser->m_hash_secret_salt = oldhash_secret_salt;
parser->m_parentParser = oldParser;
#ifdef XML_DTD
parser->m_paramEntityParsing = oldParamEntityParsing;
parser->m_prologState.inEntityValue = oldInEntityValue;
if (context) {
#endif /* XML_DTD */
if (!dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
|| !setContext(parser, context)) {
XML_ParserFree(parser);
return NULL;
}
parser->m_processor = externalEntityInitProcessor;
#ifdef XML_DTD
}
else {
/* The DTD instance referenced by parser->m_dtd is shared between the document's
root parser and external PE parsers, therefore one does not need to
call setContext. In addition, one also *must* not call setContext,
because this would overwrite existing prefix->binding pointers in
parser->m_dtd with ones that get destroyed with the external PE parser.
This would leave those prefixes with dangling pointers.
*/
parser->m_isParamEntity = XML_TRUE;
XmlPrologStateInitExternalEntity(&parser->m_prologState);
parser->m_processor = externalParEntInitProcessor;
}
#endif /* XML_DTD */
return parser;
}
static void FASTCALL
destroyBindings(BINDING *bindings, XML_Parser parser)
{
for (;;) {
BINDING *b = bindings;
if (!b)
break;
bindings = b->nextTagBinding;
FREE(parser, b->uri);
FREE(parser, b);
}
}
void XMLCALL
XML_ParserFree(XML_Parser parser)
{
TAG *tagList;
OPEN_INTERNAL_ENTITY *entityList;
if (parser == NULL)
return;
/* free m_tagStack and m_freeTagList */
tagList = parser->m_tagStack;
for (;;) {
TAG *p;
if (tagList == NULL) {
if (parser->m_freeTagList == NULL)
break;
tagList = parser->m_freeTagList;
parser->m_freeTagList = NULL;
}
p = tagList;
tagList = tagList->parent;
FREE(parser, p->buf);
destroyBindings(p->bindings, parser);
FREE(parser, p);
}
/* free m_openInternalEntities and m_freeInternalEntities */
entityList = parser->m_openInternalEntities;
for (;;) {
OPEN_INTERNAL_ENTITY *openEntity;
if (entityList == NULL) {
if (parser->m_freeInternalEntities == NULL)
break;
entityList = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = NULL;
}
openEntity = entityList;
entityList = entityList->next;
FREE(parser, openEntity);
}
destroyBindings(parser->m_freeBindingList, parser);
destroyBindings(parser->m_inheritedBindings, parser);
poolDestroy(&parser->m_tempPool);
poolDestroy(&parser->m_temp2Pool);
FREE(parser, (void *)parser->m_protocolEncodingName);
#ifdef XML_DTD
/* external parameter entity parsers share the DTD structure
parser->m_dtd with the root parser, so we must not destroy it
*/
if (!parser->m_isParamEntity && parser->m_dtd)
#else
if (parser->m_dtd)
#endif /* XML_DTD */
dtdDestroy(parser->m_dtd, (XML_Bool)!parser->m_parentParser, &parser->m_mem);
FREE(parser, (void *)parser->m_atts);
#ifdef XML_ATTR_INFO
FREE(parser, (void *)parser->m_attInfo);
#endif
FREE(parser, parser->m_groupConnector);
FREE(parser, parser->m_buffer);
FREE(parser, parser->m_dataBuf);
FREE(parser, parser->m_nsAtts);
FREE(parser, parser->m_unknownEncodingMem);
if (parser->m_unknownEncodingRelease)
parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
FREE(parser, parser);
}
void XMLCALL
XML_UseParserAsHandlerArg(XML_Parser parser)
{
if (parser != NULL)
parser->m_handlerArg = parser;
}
enum XML_Error XMLCALL
XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD)
{
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
#ifdef XML_DTD
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
parser->m_useForeignDTD = useDTD;
return XML_ERROR_NONE;
#else
return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
#endif
}
void XMLCALL
XML_SetReturnNSTriplet(XML_Parser parser, int do_nst)
{
if (parser == NULL)
return;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return;
parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
}
void XMLCALL
XML_SetUserData(XML_Parser parser, void *p)
{
if (parser == NULL)
return;
if (parser->m_handlerArg == parser->m_userData)
parser->m_handlerArg = parser->m_userData = p;
else
parser->m_userData = p;
}
enum XML_Status XMLCALL
XML_SetBase(XML_Parser parser, const XML_Char *p)
{
if (parser == NULL)
return XML_STATUS_ERROR;
if (p) {
p = poolCopyString(&parser->m_dtd->pool, p);
if (!p)
return XML_STATUS_ERROR;
parser->m_curBase = p;
}
else
parser->m_curBase = NULL;
return XML_STATUS_OK;
}
const XML_Char * XMLCALL
XML_GetBase(XML_Parser parser)
{
if (parser == NULL)
return NULL;
return parser->m_curBase;
}
int XMLCALL
XML_GetSpecifiedAttributeCount(XML_Parser parser)
{
if (parser == NULL)
return -1;
return parser->m_nSpecifiedAtts;
}
int XMLCALL
XML_GetIdAttributeIndex(XML_Parser parser)
{
if (parser == NULL)
return -1;
return parser->m_idAttIndex;
}
#ifdef XML_ATTR_INFO
const XML_AttrInfo * XMLCALL
XML_GetAttributeInfo(XML_Parser parser)
{
if (parser == NULL)
return NULL;
return parser->m_attInfo;
}
#endif
void XMLCALL
XML_SetElementHandler(XML_Parser parser,
XML_StartElementHandler start,
XML_EndElementHandler end)
{
if (parser == NULL)
return;
parser->m_startElementHandler = start;
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetStartElementHandler(XML_Parser parser,
XML_StartElementHandler start) {
if (parser != NULL)
parser->m_startElementHandler = start;
}
void XMLCALL
XML_SetEndElementHandler(XML_Parser parser,
XML_EndElementHandler end) {
if (parser != NULL)
parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetCharacterDataHandler(XML_Parser parser,
XML_CharacterDataHandler handler)
{
if (parser != NULL)
parser->m_characterDataHandler = handler;
}
void XMLCALL
XML_SetProcessingInstructionHandler(XML_Parser parser,
XML_ProcessingInstructionHandler handler)
{
if (parser != NULL)
parser->m_processingInstructionHandler = handler;
}
void XMLCALL
XML_SetCommentHandler(XML_Parser parser,
XML_CommentHandler handler)
{
if (parser != NULL)
parser->m_commentHandler = handler;
}
void XMLCALL
XML_SetCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start,
XML_EndCdataSectionHandler end)
{
if (parser == NULL)
return;
parser->m_startCdataSectionHandler = start;
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetStartCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start) {
if (parser != NULL)
parser->m_startCdataSectionHandler = start;
}
void XMLCALL
XML_SetEndCdataSectionHandler(XML_Parser parser,
XML_EndCdataSectionHandler end) {
if (parser != NULL)
parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetDefaultHandler(XML_Parser parser,
XML_DefaultHandler handler)
{
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_FALSE;
}
void XMLCALL
XML_SetDefaultHandlerExpand(XML_Parser parser,
XML_DefaultHandler handler)
{
if (parser == NULL)
return;
parser->m_defaultHandler = handler;
parser->m_defaultExpandInternalEntities = XML_TRUE;
}
void XMLCALL
XML_SetDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start,
XML_EndDoctypeDeclHandler end)
{
if (parser == NULL)
return;
parser->m_startDoctypeDeclHandler = start;
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetStartDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start) {
if (parser != NULL)
parser->m_startDoctypeDeclHandler = start;
}
void XMLCALL
XML_SetEndDoctypeDeclHandler(XML_Parser parser,
XML_EndDoctypeDeclHandler end) {
if (parser != NULL)
parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
XML_UnparsedEntityDeclHandler handler)
{
if (parser != NULL)
parser->m_unparsedEntityDeclHandler = handler;
}
void XMLCALL
XML_SetNotationDeclHandler(XML_Parser parser,
XML_NotationDeclHandler handler)
{
if (parser != NULL)
parser->m_notationDeclHandler = handler;
}
void XMLCALL
XML_SetNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start,
XML_EndNamespaceDeclHandler end)
{
if (parser == NULL)
return;
parser->m_startNamespaceDeclHandler = start;
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetStartNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start) {
if (parser != NULL)
parser->m_startNamespaceDeclHandler = start;
}
void XMLCALL
XML_SetEndNamespaceDeclHandler(XML_Parser parser,
XML_EndNamespaceDeclHandler end) {
if (parser != NULL)
parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetNotStandaloneHandler(XML_Parser parser,
XML_NotStandaloneHandler handler)
{
if (parser != NULL)
parser->m_notStandaloneHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandler(XML_Parser parser,
XML_ExternalEntityRefHandler handler)
{
if (parser != NULL)
parser->m_externalEntityRefHandler = handler;
}
void XMLCALL
XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg)
{
if (parser == NULL)
return;
if (arg)
parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
else
parser->m_externalEntityRefHandlerArg = parser;
}
void XMLCALL
XML_SetSkippedEntityHandler(XML_Parser parser,
XML_SkippedEntityHandler handler)
{
if (parser != NULL)
parser->m_skippedEntityHandler = handler;
}
void XMLCALL
XML_SetUnknownEncodingHandler(XML_Parser parser,
XML_UnknownEncodingHandler handler,
void *data)
{
if (parser == NULL)
return;
parser->m_unknownEncodingHandler = handler;
parser->m_unknownEncodingHandlerData = data;
}
void XMLCALL
XML_SetElementDeclHandler(XML_Parser parser,
XML_ElementDeclHandler eldecl)
{
if (parser != NULL)
parser->m_elementDeclHandler = eldecl;
}
void XMLCALL
XML_SetAttlistDeclHandler(XML_Parser parser,
XML_AttlistDeclHandler attdecl)
{
if (parser != NULL)
parser->m_attlistDeclHandler = attdecl;
}
void XMLCALL
XML_SetEntityDeclHandler(XML_Parser parser,
XML_EntityDeclHandler handler)
{
if (parser != NULL)
parser->m_entityDeclHandler = handler;
}
void XMLCALL
XML_SetXmlDeclHandler(XML_Parser parser,
XML_XmlDeclHandler handler) {
if (parser != NULL)
parser->m_xmlDeclHandler = handler;
}
int XMLCALL
XML_SetParamEntityParsing(XML_Parser parser,
enum XML_ParamEntityParsing peParsing)
{
if (parser == NULL)
return 0;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
#ifdef XML_DTD
parser->m_paramEntityParsing = peParsing;
return 1;
#else
return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
#endif
}
int XMLCALL
XML_SetHashSalt(XML_Parser parser,
unsigned long hash_salt)
{
if (parser == NULL)
return 0;
if (parser->m_parentParser)
return XML_SetHashSalt(parser->m_parentParser, hash_salt);
/* block after XML_Parse()/XML_ParseBuffer() has been called */
if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
parser->m_hash_secret_salt = hash_salt;
return 1;
}
enum XML_Status XMLCALL
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
{
if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
if (parser != NULL)
parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
return XML_STATUS_ERROR;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && !startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
if (len == 0) {
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
if (!isFinal)
return XML_STATUS_OK;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
/* If data are left over from last buffer, and we now know that these
data are the final chunk of input, then we have to check them again
to detect errors based on that fact.
*/
parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode == XML_ERROR_NONE) {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
/* It is hard to be certain, but it seems that this case
* cannot occur. This code is cleaning up a previous parse
* with no new data (since len == 0). Changing the parsing
* state requires getting to execute a handler function, and
* there doesn't seem to be an opportunity for that while in
* this circumstance.
*
* Given the uncertainty, we retain the code but exclude it
* from coverage tests.
*
* LCOV_EXCL_START
*/
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return XML_STATUS_SUSPENDED;
/* LCOV_EXCL_STOP */
case XML_INITIALIZED:
case XML_PARSING:
parser->m_parsingStatus.parsing = XML_FINISHED;
/* fall through */
default:
return XML_STATUS_OK;
}
}
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
#ifndef XML_CONTEXT_BYTES
else if (parser->m_bufferPtr == parser->m_bufferEnd) {
const char *end;
int nLeftOver;
enum XML_Status result;
/* Detect overflow (a+b > MAX <==> b > MAX-a) */
if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_parseEndByteIndex += len;
parser->m_positionPtr = s;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return XML_STATUS_OK;
}
/* fall through */
default:
result = XML_STATUS_OK;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position);
nLeftOver = s + len - end;
if (nLeftOver) {
if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) {
/* avoid _signed_ integer overflow */
char *temp = NULL;
const int bytesToAllocate = (int)((unsigned)len * 2U);
if (bytesToAllocate > 0) {
temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate);
}
if (temp == NULL) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
parser->m_buffer = temp;
parser->m_bufferLim = parser->m_buffer + bytesToAllocate;
}
memcpy(parser->m_buffer, end, nLeftOver);
}
parser->m_bufferPtr = parser->m_buffer;
parser->m_bufferEnd = parser->m_buffer + nLeftOver;
parser->m_positionPtr = parser->m_bufferPtr;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_eventPtr = parser->m_bufferPtr;
parser->m_eventEndPtr = parser->m_bufferPtr;
return result;
}
#endif /* not defined XML_CONTEXT_BYTES */
else {
void *buff = XML_GetBuffer(parser, len);
if (buff == NULL)
return XML_STATUS_ERROR;
else {
memcpy(buff, s, len);
return XML_ParseBuffer(parser, len, isFinal);
}
}
}
enum XML_Status XMLCALL
XML_ParseBuffer(XML_Parser parser, int len, int isFinal)
{
const char *start;
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
if (parser->m_parentParser == NULL && !startParsing(parser)) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
/* fall through */
default:
parser->m_parsingStatus.parsing = XML_PARSING;
}
start = parser->m_bufferPtr;
parser->m_positionPtr = start;
parser->m_bufferEnd += len;
parser->m_parseEndPtr = parser->m_bufferEnd;
parser->m_parseEndByteIndex += len;
parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
parser->m_errorCode = parser->m_processor(parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default: ; /* should not happen */
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void * XMLCALL
XML_GetBuffer(XML_Parser parser, int len)
{
if (parser == NULL)
return NULL;
if (len < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
parser->m_errorCode = XML_ERROR_SUSPENDED;
return NULL;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return NULL;
default: ;
}
if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) {
#ifdef XML_CONTEXT_BYTES
int keep;
#endif /* defined XML_CONTEXT_BYTES */
/* Do not invoke signed arithmetic overflow: */
int neededSize = (int) ((unsigned)len +
(unsigned)EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd,
parser->m_bufferPtr));
if (neededSize < 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
#ifdef XML_CONTEXT_BYTES
keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
neededSize += keep;
#endif /* defined XML_CONTEXT_BYTES */
if (neededSize <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
#ifdef XML_CONTEXT_BYTES
if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
int offset = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer) - keep;
/* The buffer pointers cannot be NULL here; we have at least some bytes in the buffer */
memmove(parser->m_buffer, &parser->m_buffer[offset], parser->m_bufferEnd - parser->m_bufferPtr + keep);
parser->m_bufferEnd -= offset;
parser->m_bufferPtr -= offset;
}
#else
if (parser->m_buffer && parser->m_bufferPtr) {
memmove(parser->m_buffer, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
parser->m_bufferEnd = parser->m_buffer +
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
parser->m_bufferPtr = parser->m_buffer;
}
#endif /* not defined XML_CONTEXT_BYTES */
}
else {
char *newBuf;
int bufferSize = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
if (bufferSize == 0)
bufferSize = INIT_BUFFER_SIZE;
do {
/* Do not invoke signed arithmetic overflow: */
bufferSize = (int) (2U * (unsigned) bufferSize);
} while (bufferSize < neededSize && bufferSize > 0);
if (bufferSize <= 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
newBuf = (char *)MALLOC(parser, bufferSize);
if (newBuf == 0) {
parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
parser->m_bufferLim = newBuf + bufferSize;
#ifdef XML_CONTEXT_BYTES
if (parser->m_bufferPtr) {
int keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
memcpy(newBuf, &parser->m_bufferPtr[-keep],
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep);
FREE(parser, parser->m_buffer);
parser->m_buffer = newBuf;
parser->m_bufferEnd = parser->m_buffer +
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep;
parser->m_bufferPtr = parser->m_buffer + keep;
}
else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
parser->m_bufferPtr = parser->m_buffer = newBuf;
}
#else
if (parser->m_bufferPtr) {
memcpy(newBuf, parser->m_bufferPtr,
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
FREE(parser, parser->m_buffer);
parser->m_bufferEnd = newBuf +
EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
}
else {
/* This must be a brand new buffer with no data in it yet */
parser->m_bufferEnd = newBuf;
}
parser->m_bufferPtr = parser->m_buffer = newBuf;
#endif /* not defined XML_CONTEXT_BYTES */
}
parser->m_eventPtr = parser->m_eventEndPtr = NULL;
parser->m_positionPtr = NULL;
}
return parser->m_bufferEnd;
}
enum XML_Status XMLCALL
XML_StopParser(XML_Parser parser, XML_Bool resumable)
{
if (parser == NULL)
return XML_STATUS_ERROR;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
if (resumable) {
parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_FINISHED;
break;
case XML_FINISHED:
parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
default:
if (resumable) {
#ifdef XML_DTD
if (parser->m_isParamEntity) {
parser->m_errorCode = XML_ERROR_SUSPEND_PE;
return XML_STATUS_ERROR;
}
#endif
parser->m_parsingStatus.parsing = XML_SUSPENDED;
}
else
parser->m_parsingStatus.parsing = XML_FINISHED;
}
return XML_STATUS_OK;
}
enum XML_Status XMLCALL
XML_ResumeParser(XML_Parser parser)
{
enum XML_Status result = XML_STATUS_OK;
if (parser == NULL)
return XML_STATUS_ERROR;
if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
return XML_STATUS_ERROR;
}
parser->m_parsingStatus.parsing = XML_PARSING;
parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
if (parser->m_errorCode != XML_ERROR_NONE) {
parser->m_eventEndPtr = parser->m_eventPtr;
parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (parser->m_parsingStatus.finalBuffer) {
parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default: ;
}
}
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
void XMLCALL
XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status)
{
if (parser == NULL)
return;
assert(status != NULL);
*status = parser->m_parsingStatus;
}
enum XML_Error XMLCALL
XML_GetErrorCode(XML_Parser parser)
{
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
return parser->m_errorCode;
}
XML_Index XMLCALL
XML_GetCurrentByteIndex(XML_Parser parser)
{
if (parser == NULL)
return -1;
if (parser->m_eventPtr)
return (XML_Index)(parser->m_parseEndByteIndex - (parser->m_parseEndPtr - parser->m_eventPtr));
return -1;
}
int XMLCALL
XML_GetCurrentByteCount(XML_Parser parser)
{
if (parser == NULL)
return 0;
if (parser->m_eventEndPtr && parser->m_eventPtr)
return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
return 0;
}
const char * XMLCALL
XML_GetInputContext(XML_Parser parser, int *offset, int *size)
{
#ifdef XML_CONTEXT_BYTES
if (parser == NULL)
return NULL;
if (parser->m_eventPtr && parser->m_buffer) {
if (offset != NULL)
*offset = (int)(parser->m_eventPtr - parser->m_buffer);
if (size != NULL)
*size = (int)(parser->m_bufferEnd - parser->m_buffer);
return parser->m_buffer;
}
#else
(void)parser;
(void)offset;
(void)size;
#endif /* defined XML_CONTEXT_BYTES */
return (char *) 0;
}
XML_Size XMLCALL
XML_GetCurrentLineNumber(XML_Parser parser)
{
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.lineNumber + 1;
}
XML_Size XMLCALL
XML_GetCurrentColumnNumber(XML_Parser parser)
{
if (parser == NULL)
return 0;
if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
parser->m_positionPtr = parser->m_eventPtr;
}
return parser->m_position.columnNumber;
}
void XMLCALL
XML_FreeContentModel(XML_Parser parser, XML_Content *model)
{
if (parser != NULL)
FREE(parser, model);
}
void * XMLCALL
XML_MemMalloc(XML_Parser parser, size_t size)
{
if (parser == NULL)
return NULL;
return MALLOC(parser, size);
}
void * XMLCALL
XML_MemRealloc(XML_Parser parser, void *ptr, size_t size)
{
if (parser == NULL)
return NULL;
return REALLOC(parser, ptr, size);
}
void XMLCALL
XML_MemFree(XML_Parser parser, void *ptr)
{
if (parser != NULL)
FREE(parser, ptr);
}
void XMLCALL
XML_DefaultCurrent(XML_Parser parser)
{
if (parser == NULL)
return;
if (parser->m_defaultHandler) {
if (parser->m_openInternalEntities)
reportDefault(parser,
parser->m_internalEncoding,
parser->m_openInternalEntities->internalEventPtr,
parser->m_openInternalEntities->internalEventEndPtr);
else
reportDefault(parser, parser->m_encoding, parser->m_eventPtr, parser->m_eventEndPtr);
}
}
const XML_LChar * XMLCALL
XML_ErrorString(enum XML_Error code)
{
switch (code) {
case XML_ERROR_NONE:
return NULL;
case XML_ERROR_NO_MEMORY:
return XML_L("out of memory");
case XML_ERROR_SYNTAX:
return XML_L("syntax error");
case XML_ERROR_NO_ELEMENTS:
return XML_L("no element found");
case XML_ERROR_INVALID_TOKEN:
return XML_L("not well-formed (invalid token)");
case XML_ERROR_UNCLOSED_TOKEN:
return XML_L("unclosed token");
case XML_ERROR_PARTIAL_CHAR:
return XML_L("partial character");
case XML_ERROR_TAG_MISMATCH:
return XML_L("mismatched tag");
case XML_ERROR_DUPLICATE_ATTRIBUTE:
return XML_L("duplicate attribute");
case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
return XML_L("junk after document element");
case XML_ERROR_PARAM_ENTITY_REF:
return XML_L("illegal parameter entity reference");
case XML_ERROR_UNDEFINED_ENTITY:
return XML_L("undefined entity");
case XML_ERROR_RECURSIVE_ENTITY_REF:
return XML_L("recursive entity reference");
case XML_ERROR_ASYNC_ENTITY:
return XML_L("asynchronous entity");
case XML_ERROR_BAD_CHAR_REF:
return XML_L("reference to invalid character number");
case XML_ERROR_BINARY_ENTITY_REF:
return XML_L("reference to binary entity");
case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
return XML_L("reference to external entity in attribute");
case XML_ERROR_MISPLACED_XML_PI:
return XML_L("XML or text declaration not at start of entity");
case XML_ERROR_UNKNOWN_ENCODING:
return XML_L("unknown encoding");
case XML_ERROR_INCORRECT_ENCODING:
return XML_L("encoding specified in XML declaration is incorrect");
case XML_ERROR_UNCLOSED_CDATA_SECTION:
return XML_L("unclosed CDATA section");
case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
return XML_L("error in processing external entity reference");
case XML_ERROR_NOT_STANDALONE:
return XML_L("document is not standalone");
case XML_ERROR_UNEXPECTED_STATE:
return XML_L("unexpected parser state - please send a bug report");
case XML_ERROR_ENTITY_DECLARED_IN_PE:
return XML_L("entity declared in parameter entity");
case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
return XML_L("requested feature requires XML_DTD support in Expat");
case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
return XML_L("cannot change setting once parsing has begun");
/* Added in 1.95.7. */
case XML_ERROR_UNBOUND_PREFIX:
return XML_L("unbound prefix");
/* Added in 1.95.8. */
case XML_ERROR_UNDECLARING_PREFIX:
return XML_L("must not undeclare prefix");
case XML_ERROR_INCOMPLETE_PE:
return XML_L("incomplete markup in parameter entity");
case XML_ERROR_XML_DECL:
return XML_L("XML declaration not well-formed");
case XML_ERROR_TEXT_DECL:
return XML_L("text declaration not well-formed");
case XML_ERROR_PUBLICID:
return XML_L("illegal character(s) in public id");
case XML_ERROR_SUSPENDED:
return XML_L("parser suspended");
case XML_ERROR_NOT_SUSPENDED:
return XML_L("parser not suspended");
case XML_ERROR_ABORTED:
return XML_L("parsing aborted");
case XML_ERROR_FINISHED:
return XML_L("parsing finished");
case XML_ERROR_SUSPEND_PE:
return XML_L("cannot suspend in external parameter entity");
/* Added in 2.0.0. */
case XML_ERROR_RESERVED_PREFIX_XML:
return XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name");
case XML_ERROR_RESERVED_PREFIX_XMLNS:
return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
case XML_ERROR_RESERVED_NAMESPACE_URI:
return XML_L("prefix must not be bound to one of the reserved namespace names");
/* Added in 2.2.5. */
case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
return XML_L("invalid argument");
}
return NULL;
}
const XML_LChar * XMLCALL
XML_ExpatVersion(void) {
/* V1 is used to string-ize the version number. However, it would
string-ize the actual version macro *names* unless we get them
substituted before being passed to V1. CPP is defined to expand
a macro, then rescan for more expansions. Thus, we use V2 to expand
the version macros, then CPP will expand the resulting V1() macro
with the correct numerals. */
/* ### I'm assuming cpp is portable in this respect... */
#define V1(a,b,c) XML_L(#a)XML_L(".")XML_L(#b)XML_L(".")XML_L(#c)
#define V2(a,b,c) XML_L("expat_")V1(a,b,c)
return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
#undef V1
#undef V2
}
XML_Expat_Version XMLCALL
XML_ExpatVersionInfo(void)
{
XML_Expat_Version version;
version.major = XML_MAJOR_VERSION;
version.minor = XML_MINOR_VERSION;
version.micro = XML_MICRO_VERSION;
return version;
}
const XML_Feature * XMLCALL
XML_GetFeatureList(void)
{
static const XML_Feature features[] = {
{XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
sizeof(XML_Char)},
{XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
sizeof(XML_LChar)},
#ifdef XML_UNICODE
{XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
#endif
#ifdef XML_UNICODE_WCHAR_T
{XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
#endif
#ifdef XML_DTD
{XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
#endif
#ifdef XML_CONTEXT_BYTES
{XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
XML_CONTEXT_BYTES},
#endif
#ifdef XML_MIN_SIZE
{XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
#endif
#ifdef XML_NS
{XML_FEATURE_NS, XML_L("XML_NS"), 0},
#endif
#ifdef XML_LARGE_SIZE
{XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
#endif
#ifdef XML_ATTR_INFO
{XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
#endif
{XML_FEATURE_END, NULL, 0}
};
return features;
}
/* Initially tag->rawName always points into the parse buffer;
for those TAG instances opened while the current parse buffer was
processed, and not yet closed, we need to store tag->rawName in a more
permanent location, since the parse buffer is about to be discarded.
*/
static XML_Bool
storeRawNames(XML_Parser parser)
{
TAG *tag = parser->m_tagStack;
while (tag) {
int bufSize;
int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
char *rawNameBuf = tag->buf + nameLen;
/* Stop if already stored. Since m_tagStack is a stack, we can stop
at the first entry that has already been copied; everything
below it in the stack is already been accounted for in a
previous call to this function.
*/
if (tag->rawName == rawNameBuf)
break;
/* For re-use purposes we need to ensure that the
size of tag->buf is a multiple of sizeof(XML_Char).
*/
bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
if (bufSize > tag->bufEnd - tag->buf) {
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_FALSE;
/* if tag->name.str points to tag->buf (only when namespace
processing is off) then we have to update it
*/
if (tag->name.str == (XML_Char *)tag->buf)
tag->name.str = (XML_Char *)temp;
/* if tag->name.localPart is set (when namespace processing is on)
then update it as well, since it will always point into tag->buf
*/
if (tag->name.localPart)
tag->name.localPart = (XML_Char *)temp + (tag->name.localPart -
(XML_Char *)tag->buf);
tag->buf = temp;
tag->bufEnd = temp + bufSize;
rawNameBuf = temp + nameLen;
}
memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
tag->rawName = rawNameBuf;
tag = tag->parent;
}
return XML_TRUE;
}
static enum XML_Error PTRCALL
contentProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doContent(parser, 0, parser->m_encoding, start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (!storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error PTRCALL
externalEntityInitProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = externalEntityInitProcessor2;
return externalEntityInitProcessor2(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor2(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
const char *next = start; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(parser->m_encoding, start, end, &next);
switch (tok) {
case XML_TOK_BOM:
/* If we are at the end of the buffer, this would cause the next stage,
i.e. externalEntityInitProcessor3, to pass control directly to
doContent (by detecting XML_TOK_NONE) without processing any xml text
declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
*/
if (next == end && !parser->m_parsingStatus.finalBuffer) {
*endPtr = next;
return XML_ERROR_NONE;
}
start = next;
break;
case XML_TOK_PARTIAL:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
parser->m_eventPtr = start;
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityInitProcessor3;
return externalEntityInitProcessor3(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityInitProcessor3(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
int tok;
const char *next = start; /* XmlContentTok doesn't always set the last arg */
parser->m_eventPtr = start;
tok = XmlContentTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
case XML_TOK_XML_DECL:
{
enum XML_Error result;
result = processXmlDecl(parser, 1, start, next);
if (result != XML_ERROR_NONE)
return result;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*endPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
start = next;
}
}
break;
case XML_TOK_PARTIAL:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
}
parser->m_processor = externalEntityContentProcessor;
parser->m_tagLevel = 1;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
static enum XML_Error PTRCALL
externalEntityContentProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doContent(parser, 1, parser->m_encoding, start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (!storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
}
return result;
}
static enum XML_Error
doContent(XML_Parser parser,
int startTagLevel,
const ENCODING *enc,
const char *s,
const char *end,
const char **nextPtr,
XML_Bool haveMore)
{
/* save one level of indirection */
DTD * const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
}
else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
for (;;) {
const char *next = s; /* XmlContentTok doesn't always set the last arg */
int tok = XmlContentTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_TRAILING_CR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
*eventEndPP = end;
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0)
return XML_ERROR_NO_ELEMENTS;
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (startTagLevel > 0) {
if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_NO_ELEMENTS;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_ENTITY_REF:
{
const XML_Char *name;
ENTITY *entity;
XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (ch) {
if (parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
name = poolStoreString(&dtd->pool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&dtd->pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity or default handler.
*/
if (!dtd->hasParamEntityRefs || dtd->standalone) {
if (!entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (!entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
}
else if (!entity) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->notation)
return XML_ERROR_BINARY_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
if (!parser->m_defaultExpandInternalEntities) {
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name, 0);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
result = processInternalEntity(parser, entity, XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
}
else if (parser->m_externalEntityRefHandler) {
const XML_Char *context;
entity->open = XML_TRUE;
context = getContext(parser);
entity->open = XML_FALSE;
if (!context)
return XML_ERROR_NO_MEMORY;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
context,
entity->base,
entity->systemId,
entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
poolDiscard(&parser->m_tempPool);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
case XML_TOK_START_TAG_NO_ATTS:
/* fall through */
case XML_TOK_START_TAG_WITH_ATTS:
{
TAG *tag;
enum XML_Error result;
XML_Char *toPtr;
if (parser->m_freeTagList) {
tag = parser->m_freeTagList;
parser->m_freeTagList = parser->m_freeTagList->parent;
}
else {
tag = (TAG *)MALLOC(parser, sizeof(TAG));
if (!tag)
return XML_ERROR_NO_MEMORY;
tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
if (!tag->buf) {
FREE(parser, tag);
return XML_ERROR_NO_MEMORY;
}
tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
}
tag->bindings = NULL;
tag->parent = parser->m_tagStack;
parser->m_tagStack = tag;
tag->name.localPart = NULL;
tag->name.prefix = NULL;
tag->rawName = s + enc->minBytesPerChar;
tag->rawNameLength = XmlNameLength(enc, tag->rawName);
++parser->m_tagLevel;
{
const char *rawNameEnd = tag->rawName + tag->rawNameLength;
const char *fromPtr = tag->rawName;
toPtr = (XML_Char *)tag->buf;
for (;;) {
int bufSize;
int convLen;
const enum XML_Convert_Result convert_res = XmlConvert(enc,
&fromPtr, rawNameEnd,
(ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1);
convLen = (int)(toPtr - (XML_Char *)tag->buf);
if ((fromPtr >= rawNameEnd) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
tag->name.strLen = convLen;
break;
}
bufSize = (int)(tag->bufEnd - tag->buf) << 1;
{
char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
tag->buf = temp;
tag->bufEnd = temp + bufSize;
toPtr = (XML_Char *)temp + convLen;
}
}
}
tag->name.str = (XML_Char *)tag->buf;
*toPtr = XML_T('\0');
result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
if (result)
return result;
if (parser->m_startElementHandler)
parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
(const XML_Char **)parser->m_atts);
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
break;
}
case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
/* fall through */
case XML_TOK_EMPTY_ELEMENT_WITH_ATTS:
{
const char *rawName = s + enc->minBytesPerChar;
enum XML_Error result;
BINDING *bindings = NULL;
XML_Bool noElmHandlers = XML_TRUE;
TAG_NAME name;
name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
rawName + XmlNameLength(enc, rawName));
if (!name.str)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
result = storeAtts(parser, enc, s, &name, &bindings);
if (result != XML_ERROR_NONE) {
freeBindings(parser, bindings);
return result;
}
poolFinish(&parser->m_tempPool);
if (parser->m_startElementHandler) {
parser->m_startElementHandler(parser->m_handlerArg, name.str, (const XML_Char **)parser->m_atts);
noElmHandlers = XML_FALSE;
}
if (parser->m_endElementHandler) {
if (parser->m_startElementHandler)
*eventPP = *eventEndPP;
parser->m_endElementHandler(parser->m_handlerArg, name.str);
noElmHandlers = XML_FALSE;
}
if (noElmHandlers && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
poolClear(&parser->m_tempPool);
freeBindings(parser, bindings);
}
if ((parser->m_tagLevel == 0) && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
parser->m_processor = epilogProcessor;
else
return epilogProcessor(parser, next, end, nextPtr);
}
break;
case XML_TOK_END_TAG:
if (parser->m_tagLevel == startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
else {
int len;
const char *rawName;
TAG *tag = parser->m_tagStack;
parser->m_tagStack = tag->parent;
tag->parent = parser->m_freeTagList;
parser->m_freeTagList = tag;
rawName = s + enc->minBytesPerChar*2;
len = XmlNameLength(enc, rawName);
if (len != tag->rawNameLength
|| memcmp(tag->rawName, rawName, len) != 0) {
*eventPP = rawName;
return XML_ERROR_TAG_MISMATCH;
}
--parser->m_tagLevel;
if (parser->m_endElementHandler) {
const XML_Char *localPart;
const XML_Char *prefix;
XML_Char *uri;
localPart = tag->name.localPart;
if (parser->m_ns && localPart) {
/* localPart and prefix may have been overwritten in
tag->name.str, since this points to the binding->uri
buffer which gets re-used; so we have to add them again
*/
uri = (XML_Char *)tag->name.str + tag->name.uriLen;
/* don't need to check for space - already done in storeAtts() */
while (*localPart) *uri++ = *localPart++;
prefix = (XML_Char *)tag->name.prefix;
if (parser->m_ns_triplets && prefix) {
*uri++ = parser->m_namespaceSeparator;
while (*prefix) *uri++ = *prefix++;
}
*uri = XML_T('\0');
}
parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
while (tag->bindings) {
BINDING *b = tag->bindings;
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
tag->bindings = tag->bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
if (parser->m_tagLevel == 0)
return epilogProcessor(parser, next, end, nextPtr);
}
break;
case XML_TOK_CHAR_REF:
{
int n = XmlCharRefNumber(enc, s);
if (n < 0)
return XML_ERROR_BAD_CHAR_REF;
if (parser->m_characterDataHandler) {
XML_Char buf[XML_ENCODE_MAX];
parser->m_characterDataHandler(parser->m_handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_CDATA_SECT_OPEN:
{
enum XML_Error result;
if (parser->m_startCdataSectionHandler)
parser->m_startCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* Suppose you doing a transformation on a document that involves
changing only the character data. You set up a defaultHandler
and a characterDataHandler. The defaultHandler simply copies
characters through. The characterDataHandler does the
transformation and writes the characters out escaping them as
necessary. This case will fail to work if we leave out the
following two lines (because & and < inside CDATA sections will
be incorrectly escaped).
However, now we have a start/endCdataSectionHandler, so it seems
easier to let the user deal with this.
*/
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (!next) {
parser->m_processor = cdataSectionProcessor;
return result;
}
}
break;
case XML_TOK_TRAILING_RSQB:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
if (parser->m_characterDataHandler) {
if (MUST_CONVERT(enc, s)) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
}
else
parser->m_characterDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)end - (XML_Char *)s));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0) {
*eventPP = end;
return XML_ERROR_NO_ELEMENTS;
}
if (parser->m_tagLevel != startTagLevel) {
*eventPP = end;
return XML_ERROR_ASYNC_ENTITY;
}
*nextPtr = end;
return XML_ERROR_NONE;
case XML_TOK_DATA_CHARS:
{
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
}
else
charDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
case XML_TOK_PI:
if (!reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (!reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
break;
default:
/* All of the tokens produced by XmlContentTok() have their own
* explicit cases, so this default is not strictly necessary.
* However it is a useful safety net, so we retain the code and
* simply exclude it from the coverage tests.
*
* LCOV_EXCL_START
*/
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default: ;
}
}
/* not reached */
}
/* This function does not call free() on the allocated memory, merely
* moving it to the parser's m_freeBindingList where it can be freed or
* reused as appropriate.
*/
static void
freeBindings(XML_Parser parser, BINDING *bindings)
{
while (bindings) {
BINDING *b = bindings;
/* m_startNamespaceDeclHandler will have been called for this
* binding in addBindings(), so call the end handler now.
*/
if (parser->m_endNamespaceDeclHandler)
parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
bindings = bindings->nextTagBinding;
b->nextTagBinding = parser->m_freeBindingList;
parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
}
/* Precondition: all arguments must be non-NULL;
Purpose:
- normalize attributes
- check attributes for well-formedness
- generate namespace aware attribute names (URI, prefix)
- build list of attributes for startElementHandler
- default attributes
- process namespace declarations (check and report them)
- generate namespace aware element name (URI, prefix)
*/
static enum XML_Error
storeAtts(XML_Parser parser, const ENCODING *enc,
const char *attStr, TAG_NAME *tagNamePtr,
BINDING **bindingsPtr)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
ELEMENT_TYPE *elementType;
int nDefaultAtts;
const XML_Char **appAtts; /* the attribute list for the application */
int attIndex = 0;
int prefixLen;
int i;
int n;
XML_Char *uri;
int nPrefixes = 0;
BINDING *binding;
const XML_Char *localPart;
/* lookup the element type name */
elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str,0);
if (!elementType) {
const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
if (!name)
return XML_ERROR_NO_MEMORY;
elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
sizeof(ELEMENT_TYPE));
if (!elementType)
return XML_ERROR_NO_MEMORY;
if (parser->m_ns && !setElementTypePrefix(parser, elementType))
return XML_ERROR_NO_MEMORY;
}
nDefaultAtts = elementType->nDefaultAtts;
/* get the attributes from the tokenizer */
n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
if (n + nDefaultAtts > parser->m_attsSize) {
int oldAttsSize = parser->m_attsSize;
ATTRIBUTE *temp;
#ifdef XML_ATTR_INFO
XML_AttrInfo *temp2;
#endif
parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts, parser->m_attsSize * sizeof(ATTRIBUTE));
if (temp == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_atts = temp;
#ifdef XML_ATTR_INFO
temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo, parser->m_attsSize * sizeof(XML_AttrInfo));
if (temp2 == NULL) {
parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
}
parser->m_attInfo = temp2;
#endif
if (n > oldAttsSize)
XmlGetAttributes(enc, attStr, n, parser->m_atts);
}
appAtts = (const XML_Char **)parser->m_atts;
for (i = 0; i < n; i++) {
ATTRIBUTE *currAtt = &parser->m_atts[i];
#ifdef XML_ATTR_INFO
XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
#endif
/* add the name and value to the attribute list */
ATTRIBUTE_ID *attId = getAttributeId(parser, enc, currAtt->name,
currAtt->name
+ XmlNameLength(enc, currAtt->name));
if (!attId)
return XML_ERROR_NO_MEMORY;
#ifdef XML_ATTR_INFO
currAttInfo->nameStart = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
currAttInfo->nameEnd = currAttInfo->nameStart +
XmlNameLength(enc, currAtt->name);
currAttInfo->valueStart = parser->m_parseEndByteIndex -
(parser->m_parseEndPtr - currAtt->valuePtr);
currAttInfo->valueEnd = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->valueEnd);
#endif
/* Detect duplicate attributes by their QNames. This does not work when
namespace processing is turned on and different prefixes for the same
namespace are used. For this case we have a check further down.
*/
if ((attId->name)[-1]) {
if (enc == parser->m_encoding)
parser->m_eventPtr = parser->m_atts[i].name;
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
(attId->name)[-1] = 1;
appAtts[attIndex++] = attId->name;
if (!parser->m_atts[i].normalized) {
enum XML_Error result;
XML_Bool isCdata = XML_TRUE;
/* figure out whether declared as other than CDATA */
if (attId->maybeTokenized) {
int j;
for (j = 0; j < nDefaultAtts; j++) {
if (attId == elementType->defaultAtts[j].id) {
isCdata = elementType->defaultAtts[j].isCdata;
break;
}
}
}
/* normalize the attribute value */
result = storeAttributeValue(parser, enc, isCdata,
parser->m_atts[i].valuePtr, parser->m_atts[i].valueEnd,
&parser->m_tempPool);
if (result)
return result;
appAtts[attIndex] = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
}
else {
/* the value did not need normalizing */
appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc, parser->m_atts[i].valuePtr,
parser->m_atts[i].valueEnd);
if (appAtts[attIndex] == 0)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
}
/* handle prefixed attribute names */
if (attId->prefix) {
if (attId->xmlns) {
/* deal with namespace declarations here */
enum XML_Error result = addBinding(parser, attId->prefix, attId,
appAtts[attIndex], bindingsPtr);
if (result)
return result;
--attIndex;
}
else {
/* deal with other prefixed names later */
attIndex++;
nPrefixes++;
(attId->name)[-1] = 2;
}
}
else
attIndex++;
}
/* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
parser->m_nSpecifiedAtts = attIndex;
if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
for (i = 0; i < attIndex; i += 2)
if (appAtts[i] == elementType->idAtt->name) {
parser->m_idAttIndex = i;
break;
}
}
else
parser->m_idAttIndex = -1;
/* do attribute defaulting */
for (i = 0; i < nDefaultAtts; i++) {
const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
if (!(da->id->name)[-1] && da->value) {
if (da->id->prefix) {
if (da->id->xmlns) {
enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
da->value, bindingsPtr);
if (result)
return result;
}
else {
(da->id->name)[-1] = 2;
nPrefixes++;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
}
else {
(da->id->name)[-1] = 1;
appAtts[attIndex++] = da->id->name;
appAtts[attIndex++] = da->value;
}
}
}
appAtts[attIndex] = 0;
/* expand prefixed attribute names, check for duplicates,
and clear flags that say whether attributes were specified */
i = 0;
if (nPrefixes) {
int j; /* hash table index */
unsigned long version = parser->m_nsAttsVersion;
int nsAttsSize = (int)1 << parser->m_nsAttsPower;
unsigned char oldNsAttsPower = parser->m_nsAttsPower;
/* size of hash table must be at least 2 * (# of prefixed attributes) */
if ((nPrefixes << 1) >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
NS_ATT *temp;
/* hash table size must also be a power of 2 and >= 8 */
while (nPrefixes >> parser->m_nsAttsPower++);
if (parser->m_nsAttsPower < 3)
parser->m_nsAttsPower = 3;
nsAttsSize = (int)1 << parser->m_nsAttsPower;
temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));
if (!temp) {
/* Restore actual size of memory in m_nsAtts */
parser->m_nsAttsPower = oldNsAttsPower;
return XML_ERROR_NO_MEMORY;
}
parser->m_nsAtts = temp;
version = 0; /* force re-initialization of m_nsAtts hash table */
}
/* using a version flag saves us from initializing m_nsAtts every time */
if (!version) { /* initialize version flags when version wraps around */
version = INIT_ATTS_VERSION;
for (j = nsAttsSize; j != 0; )
parser->m_nsAtts[--j].version = version;
}
parser->m_nsAttsVersion = --version;
/* expand prefixed names and check for duplicates */
for (; i < attIndex; i += 2) {
const XML_Char *s = appAtts[i];
if (s[-1] == 2) { /* prefixed */
ATTRIBUTE_ID *id;
const BINDING *b;
unsigned long uriHash;
struct siphash sip_state;
struct sipkey sip_key;
copy_salt_to_sipkey(parser, &sip_key);
sip24_init(&sip_state, &sip_key);
((XML_Char *)s)[-1] = 0; /* clear flag */
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
if (!id || !id->prefix) {
/* This code is walking through the appAtts array, dealing
* with (in this case) a prefixed attribute name. To be in
* the array, the attribute must have already been bound, so
* has to have passed through the hash table lookup once
* already. That implies that an entry for it already
* exists, so the lookup above will return a pointer to
* already allocated memory. There is no opportunaity for
* the allocator to fail, so the condition above cannot be
* fulfilled.
*
* Since it is difficult to be certain that the above
* analysis is complete, we retain the test and merely
* remove the code from coverage tests.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
b = id->prefix->binding;
if (!b)
return XML_ERROR_UNBOUND_PREFIX;
for (j = 0; j < b->uriLen; j++) {
const XML_Char c = b->uri[j];
if (!poolAppendChar(&parser->m_tempPool, c))
return XML_ERROR_NO_MEMORY;
}
sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
while (*s++ != XML_T(ASCII_COLON))
;
sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
do { /* copies null terminator */
if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
uriHash = (unsigned long)sip24_final(&sip_state);
{ /* Check hash table for duplicate of expanded name (uriName).
Derived from code in lookup(parser, HASH_TABLE *table, ...).
*/
unsigned char step = 0;
unsigned long mask = nsAttsSize - 1;
j = uriHash & mask; /* index into hash table */
while (parser->m_nsAtts[j].version == version) {
/* for speed we compare stored hash values first */
if (uriHash == parser->m_nsAtts[j].hash) {
const XML_Char *s1 = poolStart(&parser->m_tempPool);
const XML_Char *s2 = parser->m_nsAtts[j].uriName;
/* s1 is null terminated, but not s2 */
for (; *s1 == *s2 && *s1 != 0; s1++, s2++);
if (*s1 == 0)
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
if (!step)
step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
j < step ? (j += nsAttsSize - step) : (j -= step);
}
}
if (parser->m_ns_triplets) { /* append namespace separator and prefix */
parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
s = b->prefix->name;
do {
if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
}
/* store expanded name in attribute list */
s = poolStart(&parser->m_tempPool);
poolFinish(&parser->m_tempPool);
appAtts[i] = s;
/* fill empty slot with new version, uriName and hash value */
parser->m_nsAtts[j].version = version;
parser->m_nsAtts[j].hash = uriHash;
parser->m_nsAtts[j].uriName = s;
if (!--nPrefixes) {
i += 2;
break;
}
}
else /* not prefixed */
((XML_Char *)s)[-1] = 0; /* clear flag */
}
}
/* clear flags for the remaining attributes */
for (; i < attIndex; i += 2)
((XML_Char *)(appAtts[i]))[-1] = 0;
for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
binding->attId->name[-1] = 0;
if (!parser->m_ns)
return XML_ERROR_NONE;
/* expand the element type name */
if (elementType->prefix) {
binding = elementType->prefix->binding;
if (!binding)
return XML_ERROR_UNBOUND_PREFIX;
localPart = tagNamePtr->str;
while (*localPart++ != XML_T(ASCII_COLON))
;
}
else if (dtd->defaultPrefix.binding) {
binding = dtd->defaultPrefix.binding;
localPart = tagNamePtr->str;
}
else
return XML_ERROR_NONE;
prefixLen = 0;
if (parser->m_ns_triplets && binding->prefix->name) {
for (; binding->prefix->name[prefixLen++];)
; /* prefixLen includes null terminator */
}
tagNamePtr->localPart = localPart;
tagNamePtr->uriLen = binding->uriLen;
tagNamePtr->prefix = binding->prefix->name;
tagNamePtr->prefixLen = prefixLen;
for (i = 0; localPart[i++];)
; /* i includes null terminator */
n = i + binding->uriLen + prefixLen;
if (n > binding->uriAlloc) {
TAG *p;
uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
if (!uri)
return XML_ERROR_NO_MEMORY;
binding->uriAlloc = n + EXPAND_SPARE;
memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
for (p = parser->m_tagStack; p; p = p->parent)
if (p->name.str == binding->uri)
p->name.str = uri;
FREE(parser, binding->uri);
binding->uri = uri;
}
/* if m_namespaceSeparator != '\0' then uri includes it already */
uri = binding->uri + binding->uriLen;
memcpy(uri, localPart, i * sizeof(XML_Char));
/* we always have a namespace separator between localPart and prefix */
if (prefixLen) {
uri += i - 1;
*uri = parser->m_namespaceSeparator; /* replace null terminator */
memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
}
tagNamePtr->str = binding->uri;
return XML_ERROR_NONE;
}
/* addBinding() overwrites the value of prefix->binding without checking.
Therefore one must keep track of the old value outside of addBinding().
*/
static enum XML_Error
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
const XML_Char *uri, BINDING **bindingsPtr)
{
static const XML_Char xmlNamespace[] = {
ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH,
ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD,
ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,
ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8, ASCII_SLASH,
ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
ASCII_e, '\0'
};
static const int xmlLen =
(int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1;
static const XML_Char xmlnsNamespace[] = {
ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH,
ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD,
ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0,
ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s,
ASCII_SLASH, '\0'
};
static const int xmlnsLen =
(int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1;
XML_Bool mustBeXML = XML_FALSE;
XML_Bool isXML = XML_TRUE;
XML_Bool isXMLNS = XML_TRUE;
BINDING *b;
int len;
/* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
if (*uri == XML_T('\0') && prefix->name)
return XML_ERROR_UNDECLARING_PREFIX;
if (prefix->name
&& prefix->name[0] == XML_T(ASCII_x)
&& prefix->name[1] == XML_T(ASCII_m)
&& prefix->name[2] == XML_T(ASCII_l)) {
/* Not allowed to bind xmlns */
if (prefix->name[3] == XML_T(ASCII_n)
&& prefix->name[4] == XML_T(ASCII_s)
&& prefix->name[5] == XML_T('\0'))
return XML_ERROR_RESERVED_PREFIX_XMLNS;
if (prefix->name[3] == XML_T('\0'))
mustBeXML = XML_TRUE;
}
for (len = 0; uri[len]; len++) {
if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
isXML = XML_FALSE;
if (!mustBeXML && isXMLNS
&& (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
isXMLNS = XML_FALSE;
}
isXML = isXML && len == xmlLen;
isXMLNS = isXMLNS && len == xmlnsLen;
if (mustBeXML != isXML)
return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
: XML_ERROR_RESERVED_NAMESPACE_URI;
if (isXMLNS)
return XML_ERROR_RESERVED_NAMESPACE_URI;
if (parser->m_namespaceSeparator)
len++;
if (parser->m_freeBindingList) {
b = parser->m_freeBindingList;
if (len > b->uriAlloc) {
XML_Char *temp = (XML_Char *)REALLOC(parser, b->uri,
sizeof(XML_Char) * (len + EXPAND_SPARE));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
b->uri = temp;
b->uriAlloc = len + EXPAND_SPARE;
}
parser->m_freeBindingList = b->nextTagBinding;
}
else {
b = (BINDING *)MALLOC(parser, sizeof(BINDING));
if (!b)
return XML_ERROR_NO_MEMORY;
b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
if (!b->uri) {
FREE(parser, b);
return XML_ERROR_NO_MEMORY;
}
b->uriAlloc = len + EXPAND_SPARE;
}
b->uriLen = len;
memcpy(b->uri, uri, len * sizeof(XML_Char));
if (parser->m_namespaceSeparator)
b->uri[len - 1] = parser->m_namespaceSeparator;
b->prefix = prefix;
b->attId = attId;
b->prevPrefixBinding = prefix->binding;
/* NULL binding when default namespace undeclared */
if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
prefix->binding = NULL;
else
prefix->binding = b;
b->nextTagBinding = *bindingsPtr;
*bindingsPtr = b;
/* if attId == NULL then we are not starting a namespace scope */
if (attId && parser->m_startNamespaceDeclHandler)
parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
prefix->binding ? uri : 0);
return XML_ERROR_NONE;
}
/* The idea here is to avoid using stack for each CDATA section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
cdataSectionProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doCdataSection(parser, parser->m_encoding, &start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
if (parser->m_parentParser) { /* we are parsing an external entity */
parser->m_processor = externalEntityContentProcessor;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
else {
parser->m_processor = contentProcessor;
return contentProcessor(parser, start, end, endPtr);
}
}
return result;
}
/* startPtr gets set to non-null if the section is closed, and to null if
the section is not yet closed.
*/
static enum XML_Error
doCdataSection(XML_Parser parser,
const ENCODING *enc,
const char **startPtr,
const char *end,
const char **nextPtr,
XML_Bool haveMore)
{
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
}
else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
*startPtr = NULL;
for (;;) {
const char *next;
int tok = XmlCdataSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_CDATA_SECT_CLOSE:
if (parser->m_endCdataSectionHandler)
parser->m_endCdataSectionHandler(parser->m_handlerArg);
/* BEGIN disabled code */
/* see comment under XML_TOK_CDATA_SECT_OPEN */
else if (0 && parser->m_characterDataHandler)
parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
/* END disabled code */
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_DATA_NEWLINE:
if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_DATA_CHARS:
{
XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = next;
charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
(int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
}
else
charDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
}
else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_CDATA_SECTION;
default:
/* Every token returned by XmlCdataSectionTok() has its own
* explicit case, so this default case will never be executed.
* We retain it as a safety net and exclude it from the coverage
* statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
*eventPP = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default: ;
}
}
/* not reached */
}
#ifdef XML_DTD
/* The idea here is to avoid using stack for each IGNORE section when
the whole file is parsed with one call.
*/
static enum XML_Error PTRCALL
ignoreSectionProcessor(XML_Parser parser,
const char *start,
const char *end,
const char **endPtr)
{
enum XML_Error result = doIgnoreSection(parser, parser->m_encoding, &start, end,
endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
parser->m_processor = prologProcessor;
return prologProcessor(parser, start, end, endPtr);
}
return result;
}
/* startPtr gets set to non-null is the section is closed, and to null
if the section is not yet closed.
*/
static enum XML_Error
doIgnoreSection(XML_Parser parser,
const ENCODING *enc,
const char **startPtr,
const char *end,
const char **nextPtr,
XML_Bool haveMore)
{
const char *next;
int tok;
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
*eventPP = s;
eventEndPP = &parser->m_eventEndPtr;
}
else {
/* It's not entirely clear, but it seems the following two lines
* of code cannot be executed. The only occasions on which 'enc'
* is not 'encoding' are when this function is called
* from the internal entity processing, and IGNORE sections are an
* error in internal entities.
*
* Since it really isn't clear that this is true, we keep the code
* and just remove it from our coverage tests.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
*eventPP = s;
*startPtr = NULL;
tok = XmlIgnoreSectionTok(enc, s, end, &next);
*eventEndPP = next;
switch (tok) {
case XML_TOK_IGNORE_SECT:
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_PARTIAL:
case XML_TOK_NONE:
if (haveMore) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
default:
/* All of the tokens that XmlIgnoreSectionTok() returns have
* explicit cases to handle them, so this default case is never
* executed. We keep it as a safety net anyway, and remove it
* from our test coverage statistics.
*
* LCOV_EXCL_START
*/
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
/* not reached */
}
#endif /* XML_DTD */
static enum XML_Error
initializeEncoding(XML_Parser parser)
{
const char *s;
#ifdef XML_UNICODE
char encodingBuf[128];
/* See comments abount `protoclEncodingName` in parserInit() */
if (!parser->m_protocolEncodingName)
s = NULL;
else {
int i;
for (i = 0; parser->m_protocolEncodingName[i]; i++) {
if (i == sizeof(encodingBuf) - 1
|| (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
encodingBuf[0] = '\0';
break;
}
encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
}
encodingBuf[i] = '\0';
s = encodingBuf;
}
#else
s = parser->m_protocolEncodingName;
#endif
if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(&parser->m_initEncoding, &parser->m_encoding, s))
return XML_ERROR_NONE;
return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
}
static enum XML_Error
processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
const char *s, const char *next)
{
const char *encodingName = NULL;
const XML_Char *storedEncName = NULL;
const ENCODING *newEncoding = NULL;
const char *version = NULL;
const char *versionend;
const XML_Char *storedversion = NULL;
int standalone = -1;
if (!(parser->m_ns
? XmlParseXmlDeclNS
: XmlParseXmlDecl)(isGeneralTextEntity,
parser->m_encoding,
s,
next,
&parser->m_eventPtr,
&version,
&versionend,
&encodingName,
&newEncoding,
&standalone)) {
if (isGeneralTextEntity)
return XML_ERROR_TEXT_DECL;
else
return XML_ERROR_XML_DECL;
}
if (!isGeneralTextEntity && standalone == 1) {
parser->m_dtd->standalone = XML_TRUE;
#ifdef XML_DTD
if (parser->m_paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif /* XML_DTD */
}
if (parser->m_xmlDeclHandler) {
if (encodingName != NULL) {
storedEncName = poolStoreString(&parser->m_temp2Pool,
parser->m_encoding,
encodingName,
encodingName
+ XmlNameLength(parser->m_encoding, encodingName));
if (!storedEncName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_temp2Pool);
}
if (version) {
storedversion = poolStoreString(&parser->m_temp2Pool,
parser->m_encoding,
version,
versionend - parser->m_encoding->minBytesPerChar);
if (!storedversion)
return XML_ERROR_NO_MEMORY;
}
parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName, standalone);
}
else if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_protocolEncodingName == NULL) {
if (newEncoding) {
/* Check that the specified encoding does not conflict with what
* the parser has already deduced. Do we have the same number
* of bytes in the smallest representation of a character? If
* this is UTF-16, is it the same endianness?
*/
if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
|| (newEncoding->minBytesPerChar == 2 &&
newEncoding != parser->m_encoding)) {
parser->m_eventPtr = encodingName;
return XML_ERROR_INCORRECT_ENCODING;
}
parser->m_encoding = newEncoding;
}
else if (encodingName) {
enum XML_Error result;
if (!storedEncName) {
storedEncName = poolStoreString(
&parser->m_temp2Pool, parser->m_encoding, encodingName,
encodingName + XmlNameLength(parser->m_encoding, encodingName));
if (!storedEncName)
return XML_ERROR_NO_MEMORY;
}
result = handleUnknownEncoding(parser, storedEncName);
poolClear(&parser->m_temp2Pool);
if (result == XML_ERROR_UNKNOWN_ENCODING)
parser->m_eventPtr = encodingName;
return result;
}
}
if (storedEncName || storedversion)
poolClear(&parser->m_temp2Pool);
return XML_ERROR_NONE;
}
static enum XML_Error
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
{
if (parser->m_unknownEncodingHandler) {
XML_Encoding info;
int i;
for (i = 0; i < 256; i++)
info.map[i] = -1;
info.convert = NULL;
info.data = NULL;
info.release = NULL;
if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName,
&info)) {
ENCODING *enc;
parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
if (!parser->m_unknownEncodingMem) {
if (info.release)
info.release(info.data);
return XML_ERROR_NO_MEMORY;
}
enc = (parser->m_ns
? XmlInitUnknownEncodingNS
: XmlInitUnknownEncoding)(parser->m_unknownEncodingMem,
info.map,
info.convert,
info.data);
if (enc) {
parser->m_unknownEncodingData = info.data;
parser->m_unknownEncodingRelease = info.release;
parser->m_encoding = enc;
return XML_ERROR_NONE;
}
}
if (info.release != NULL)
info.release(info.data);
}
return XML_ERROR_UNKNOWN_ENCODING;
}
static enum XML_Error PTRCALL
prologInitProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
parser->m_processor = prologProcessor;
return prologProcessor(parser, s, end, nextPtr);
}
#ifdef XML_DTD
static enum XML_Error PTRCALL
externalParEntInitProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
/* we know now that XML_Parse(Buffer) has been called,
so we consider the external parameter entity read */
parser->m_dtd->paramEntityRead = XML_TRUE;
if (parser->m_prologState.inEntityValue) {
parser->m_processor = entityValueInitProcessor;
return entityValueInitProcessor(parser, s, end, nextPtr);
}
else {
parser->m_processor = externalParEntProcessor;
return externalParEntProcessor(parser, s, end, nextPtr);
}
}
static enum XML_Error PTRCALL
entityValueInitProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
int tok;
const char *start = s;
const char *next = start;
parser->m_eventPtr = start;
for (;;) {
tok = XmlPrologTok(parser->m_encoding, start, end, &next);
parser->m_eventEndPtr = next;
if (tok <= 0) {
if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, parser->m_encoding, s, end);
}
else if (tok == XML_TOK_XML_DECL) {
enum XML_Error result;
result = processXmlDecl(parser, 0, start, next);
if (result != XML_ERROR_NONE)
return result;
/* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For that
* to happen, a parameter entity parsing handler must have
* attempted to suspend the parser, which fails and raises an
* error. The parser can be aborted, but can't be suspended.
*/
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
*nextPtr = next;
/* stop scanning for text declaration - we found one */
parser->m_processor = entityValueProcessor;
return entityValueProcessor(parser, next, end, nextPtr);
}
/* If we are at the end of the buffer, this would cause XmlPrologTok to
return XML_TOK_NONE on the next call, which would then cause the
function to exit with *nextPtr set to s - that is what we want for other
tokens, but not for the BOM - we would rather like to skip it;
then, when this routine is entered the next time, XmlPrologTok will
return XML_TOK_INVALID, since the BOM is still in the buffer
*/
else if (tok == XML_TOK_BOM && next == end && !parser->m_parsingStatus.finalBuffer) {
*nextPtr = next;
return XML_ERROR_NONE;
}
/* If we get this token, we have the start of what might be a
normal tag, but not a declaration (i.e. it doesn't begin with
"<!"). In a DTD context, that isn't legal.
*/
else if (tok == XML_TOK_INSTANCE_START) {
*nextPtr = next;
return XML_ERROR_SYNTAX;
}
start = next;
parser->m_eventPtr = start;
}
}
static enum XML_Error PTRCALL
externalParEntProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next,
nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error PTRCALL
entityValueProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
const char *start = s;
const char *next = s;
const ENCODING *enc = parser->m_encoding;
int tok;
for (;;) {
tok = XmlPrologTok(enc, start, end, &next);
if (tok <= 0) {
if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
/* found end of entity value - can store it now */
return storeEntityValue(parser, enc, s, end);
}
start = next;
}
}
#endif /* XML_DTD */
static enum XML_Error PTRCALL
prologProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
const char *next = s;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next,
nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error
doProlog(XML_Parser parser,
const ENCODING *enc,
const char *s,
const char *end,
int tok,
const char *next,
const char **nextPtr,
XML_Bool haveMore)
{
#ifdef XML_DTD
static const XML_Char externalSubsetName[] = { ASCII_HASH , '\0' };
#endif /* XML_DTD */
static const XML_Char atypeCDATA[] =
{ ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' };
static const XML_Char atypeID[] = { ASCII_I, ASCII_D, '\0' };
static const XML_Char atypeIDREF[] =
{ ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' };
static const XML_Char atypeIDREFS[] =
{ ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' };
static const XML_Char atypeENTITY[] =
{ ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' };
static const XML_Char atypeENTITIES[] = { ASCII_E, ASCII_N,
ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\0' };
static const XML_Char atypeNMTOKEN[] = {
ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' };
static const XML_Char atypeNMTOKENS[] = { ASCII_N, ASCII_M, ASCII_T,
ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\0' };
static const XML_Char notationPrefix[] = { ASCII_N, ASCII_O, ASCII_T,
ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0' };
static const XML_Char enumValueSep[] = { ASCII_PIPE, '\0' };
static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' };
/* save one level of indirection */
DTD * const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
enum XML_Content_Quant quant;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
}
else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
for (;;) {
int role;
XML_Bool handleDefault = XML_TRUE;
*eventPP = s;
*eventEndPP = next;
if (tok <= 0) {
if (haveMore && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case -XML_TOK_PROLOG_S:
tok = -tok;
break;
case XML_TOK_NONE:
#ifdef XML_DTD
/* for internal PE NOT referenced between declarations */
if (enc != parser->m_encoding && !parser->m_openInternalEntities->betweenDecl) {
*nextPtr = s;
return XML_ERROR_NONE;
}
/* WFC: PE Between Declarations - must check that PE contains
complete markup, not only for external PEs, but also for
internal PEs if the reference occurs between declarations.
*/
if (parser->m_isParamEntity || enc != parser->m_encoding) {
if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
== XML_ROLE_ERROR)
return XML_ERROR_INCOMPLETE_PE;
*nextPtr = s;
return XML_ERROR_NONE;
}
#endif /* XML_DTD */
return XML_ERROR_NO_ELEMENTS;
default:
tok = -tok;
next = end;
break;
}
}
role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
switch (role) {
case XML_ROLE_XML_DECL:
{
enum XML_Error result = processXmlDecl(parser, 0, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_NAME:
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next);
if (!parser->m_doctypeName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = NULL;
handleDefault = XML_FALSE;
}
parser->m_doctypeSysid = NULL; /* always initialize to NULL */
break;
case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
if (parser->m_startDoctypeDeclHandler) {
parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 1);
parser->m_doctypeName = NULL;
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
#ifdef XML_DTD
case XML_ROLE_TEXT_DECL:
{
enum XML_Error result = processXmlDecl(parser, 1, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
}
break;
#endif /* XML_DTD */
case XML_ROLE_DOCTYPE_PUBLIC_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
parser->m_declEntity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
XML_Char *pubId;
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
pubId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!pubId)
return XML_ERROR_NO_MEMORY;
normalizePublicId(pubId);
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = pubId;
handleDefault = XML_FALSE;
goto alreadyChecked;
}
/* fall through */
case XML_ROLE_ENTITY_PUBLIC_ID:
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
alreadyChecked:
if (dtd->keepProcessing && parser->m_declEntity) {
XML_Char *tem = poolStoreString(&dtd->pool,
enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declEntity->publicId = tem;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_PUBLIC_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_CLOSE:
if (parser->m_doctypeName) {
parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName,
parser->m_doctypeSysid, parser->m_doctypePubid, 0);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
/* parser->m_doctypeSysid will be non-NULL in the case of a previous
XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
was not set, indicating an external subset
*/
#ifdef XML_DTD
if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!entity) {
/* The external subset name "#" will have already been
* inserted into the hash table at the start of the
* external entity parsing, so no allocation will happen
* and lookup() cannot fail.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
if (parser->m_useForeignDTD)
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (!dtd->standalone &&
parser->m_notStandaloneHandler &&
!parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else if (!parser->m_doctypeSysid)
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
parser->m_useForeignDTD = XML_FALSE;
}
#endif /* XML_DTD */
if (parser->m_endDoctypeDeclHandler) {
parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_INSTANCE_START:
#ifdef XML_DTD
/* if there is no DOCTYPE declaration then now is the
last chance to read the foreign DTD
*/
if (parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!entity)
return XML_ERROR_NO_MEMORY;
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (!dtd->standalone &&
parser->m_notStandaloneHandler &&
!parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
}
#endif /* XML_DTD */
parser->m_processor = contentProcessor;
return contentProcessor(parser, s, end, nextPtr);
case XML_ROLE_ATTLIST_ELEMENT_NAME:
parser->m_declElementType = getElementType(parser, enc, s, next);
if (!parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_NAME:
parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
if (!parser->m_declAttributeId)
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeType = NULL;
parser->m_declAttributeIsId = XML_FALSE;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
parser->m_declAttributeIsCdata = XML_TRUE;
parser->m_declAttributeType = atypeCDATA;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ID:
parser->m_declAttributeIsId = XML_TRUE;
parser->m_declAttributeType = atypeID;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
parser->m_declAttributeType = atypeIDREF;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
parser->m_declAttributeType = atypeIDREFS;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
parser->m_declAttributeType = atypeENTITY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
parser->m_declAttributeType = atypeENTITIES;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
parser->m_declAttributeType = atypeNMTOKEN;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
parser->m_declAttributeType = atypeNMTOKENS;
checkAttListDeclHandler:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
const XML_Char *prefix;
if (parser->m_declAttributeType) {
prefix = enumValueSep;
}
else {
prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE
? notationPrefix
: enumValueStart);
}
if (!poolAppendString(&parser->m_tempPool, prefix))
return XML_ERROR_NO_MEMORY;
if (!poolAppend(&parser->m_tempPool, enc, s, next))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
parser->m_declAttributeIsCdata, parser->m_declAttributeIsId,
0, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType,
0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
const XML_Char *attVal;
enum XML_Error result =
storeAttributeValue(parser, enc, parser->m_declAttributeIsCdata,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar,
&dtd->pool);
if (result)
return result;
attVal = poolStart(&dtd->pool);
poolFinish(&dtd->pool);
/* ID attributes aren't allowed to have a default */
if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType,
attVal,
role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_ENTITY_VALUE:
if (dtd->keepProcessing) {
enum XML_Error result = storeEntityValue(parser, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (parser->m_declEntity) {
parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
poolFinish(&dtd->entityValuePool);
if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
parser->m_declEntity->is_param,
parser->m_declEntity->textPtr,
parser->m_declEntity->textLen,
parser->m_curBase, 0, 0, 0);
handleDefault = XML_FALSE;
}
}
else
poolDiscard(&dtd->entityValuePool);
if (result != XML_ERROR_NONE)
return result;
}
break;
case XML_ROLE_DOCTYPE_SYSTEM_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (parser->m_doctypeSysid == NULL)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
#ifdef XML_DTD
else
/* use externalSubsetName to make parser->m_doctypeSysid non-NULL
for the case where no parser->m_startDoctypeDeclHandler is set */
parser->m_doctypeSysid = externalSubsetName;
#endif /* XML_DTD */
if (!dtd->standalone
#ifdef XML_DTD
&& !parser->m_paramEntityParsing
#endif /* XML_DTD */
&& parser->m_notStandaloneHandler
&& !parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
#ifndef XML_DTD
break;
#else /* XML_DTD */
if (!parser->m_declEntity) {
parser->m_declEntity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->publicId = NULL;
}
#endif /* XML_DTD */
/* fall through */
case XML_ROLE_ENTITY_SYSTEM_ID:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!parser->m_declEntity->systemId)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->base = parser->m_curBase;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_SYSTEM_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_COMPLETE:
if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
parser->m_declEntity->is_param,
0,0,
parser->m_declEntity->base,
parser->m_declEntity->systemId,
parser->m_declEntity->publicId,
0);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_NOTATION_NAME:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
if (!parser->m_declEntity->notation)
return XML_ERROR_NO_MEMORY;
poolFinish(&dtd->pool);
if (parser->m_unparsedEntityDeclHandler) {
*eventEndPP = s;
parser->m_unparsedEntityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
parser->m_declEntity->base,
parser->m_declEntity->systemId,
parser->m_declEntity->publicId,
parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
else if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(parser->m_handlerArg,
parser->m_declEntity->name,
0,0,0,
parser->m_declEntity->base,
parser->m_declEntity->systemId,
parser->m_declEntity->publicId,
parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_GENERAL_ENTITY_NAME:
{
if (XmlPredefinedEntityName(enc, s, next)) {
parser->m_declEntity = NULL;
break;
}
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (!name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name,
sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_FALSE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
}
else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
}
break;
case XML_ROLE_PARAM_ENTITY_NAME:
#ifdef XML_DTD
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (!name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
name, sizeof(ENTITY));
if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_TRUE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
}
else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
#else /* not XML_DTD */
parser->m_declEntity = NULL;
#endif /* XML_DTD */
break;
case XML_ROLE_NOTATION_NAME:
parser->m_declNotationPublicId = NULL;
parser->m_declNotationName = NULL;
if (parser->m_notationDeclHandler) {
parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next);
if (!parser->m_declNotationName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_PUBLIC_ID:
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
if (parser->m_declNotationName) { /* means m_notationDeclHandler != NULL */
XML_Char *tem = poolStoreString(&parser->m_tempPool,
enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declNotationPublicId = tem;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_SYSTEM_ID:
if (parser->m_declNotationName && parser->m_notationDeclHandler) {
const XML_Char *systemId
= poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!systemId)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_notationDeclHandler(parser->m_handlerArg,
parser->m_declNotationName,
parser->m_curBase,
systemId,
parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_NOTATION_NO_SYSTEM_ID:
if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
*eventEndPP = s;
parser->m_notationDeclHandler(parser->m_handlerArg,
parser->m_declNotationName,
parser->m_curBase,
0,
parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_ERROR:
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
/* PE references in internal subset are
not allowed within declarations. */
return XML_ERROR_PARAM_ENTITY_REF;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
default:
return XML_ERROR_SYNTAX;
}
#ifdef XML_DTD
case XML_ROLE_IGNORE_SECT:
{
enum XML_Error result;
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
handleDefault = XML_FALSE;
result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (!next) {
parser->m_processor = ignoreSectionProcessor;
return result;
}
}
break;
#endif /* XML_DTD */
case XML_ROLE_GROUP_OPEN:
if (parser->m_prologState.level >= parser->m_groupSize) {
if (parser->m_groupSize) {
char *temp = (char *)REALLOC(parser, parser->m_groupConnector, parser->m_groupSize *= 2);
if (temp == NULL) {
parser->m_groupSize /= 2;
return XML_ERROR_NO_MEMORY;
}
parser->m_groupConnector = temp;
if (dtd->scaffIndex) {
int *temp = (int *)REALLOC(parser, dtd->scaffIndex,
parser->m_groupSize * sizeof(int));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex = temp;
}
}
else {
parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32);
if (!parser->m_groupConnector) {
parser->m_groupSize = 0;
return XML_ERROR_NO_MEMORY;
}
}
}
parser->m_groupConnector[parser->m_prologState.level] = 0;
if (dtd->in_eldecl) {
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex[dtd->scaffLevel] = myindex;
dtd->scaffLevel++;
dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_SEQUENCE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
return XML_ERROR_SYNTAX;
parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
if (dtd->in_eldecl && parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_GROUP_CHOICE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
return XML_ERROR_SYNTAX;
if (dtd->in_eldecl
&& !parser->m_groupConnector[parser->m_prologState.level]
&& (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
!= XML_CTYPE_MIXED)
) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_CHOICE;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
break;
case XML_ROLE_PARAM_ENTITY_REF:
#ifdef XML_DTD
case XML_ROLE_INNER_PARAM_ENTITY_REF:
dtd->hasParamEntityRefs = XML_TRUE;
if (!parser->m_paramEntityParsing)
dtd->keepProcessing = dtd->standalone;
else {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&dtd->pool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&dtd->pool);
/* first, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity handler
*/
if (parser->m_prologState.documentEntity &&
(dtd->standalone
? !parser->m_openInternalEntities
: !dtd->hasParamEntityRefs)) {
if (!entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (!entity->is_internal) {
/* It's hard to exhaustively search the code to be sure,
* but there doesn't seem to be a way of executing the
* following line. There are two cases:
*
* If 'standalone' is false, the DTD must have no
* parameter entities or we wouldn't have passed the outer
* 'if' statement. That measn the only entity in the hash
* table is the external subset name "#" which cannot be
* given as a parameter entity name in XML syntax, so the
* lookup must have returned NULL and we don't even reach
* the test for an internal entity.
*
* If 'standalone' is true, it does not seem to be
* possible to create entities taking this code path that
* are not internal entities, so fail the test above.
*
* Because this analysis is very uncertain, the code is
* being left in place and merely removed from the
* coverage test statistics.
*/
return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
}
}
else if (!entity) {
dtd->keepProcessing = dtd->standalone;
/* cannot report skipped entities in declarations */
if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) {
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
handleDefault = XML_FALSE;
}
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
XML_Bool betweenDecl =
(role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
result = processInternalEntity(parser, entity, betweenDecl);
if (result != XML_ERROR_NONE)
return result;
handleDefault = XML_FALSE;
break;
}
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId)) {
entity->open = XML_FALSE;
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
entity->open = XML_FALSE;
handleDefault = XML_FALSE;
if (!dtd->paramEntityRead) {
dtd->keepProcessing = dtd->standalone;
break;
}
}
else {
dtd->keepProcessing = dtd->standalone;
break;
}
}
#endif /* XML_DTD */
if (!dtd->standalone &&
parser->m_notStandaloneHandler &&
!parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
break;
/* Element declaration stuff */
case XML_ROLE_ELEMENT_NAME:
if (parser->m_elementDeclHandler) {
parser->m_declElementType = getElementType(parser, enc, s, next);
if (!parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
dtd->scaffLevel = 0;
dtd->scaffCount = 0;
dtd->in_eldecl = XML_TRUE;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ANY:
case XML_ROLE_CONTENT_EMPTY:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler) {
XML_Content * content = (XML_Content *) MALLOC(parser, sizeof(XML_Content));
if (!content)
return XML_ERROR_NO_MEMORY;
content->quant = XML_CQUANT_NONE;
content->name = NULL;
content->numchildren = 0;
content->children = NULL;
content->type = ((role == XML_ROLE_CONTENT_ANY) ?
XML_CTYPE_ANY :
XML_CTYPE_EMPTY);
*eventEndPP = s;
parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, content);
handleDefault = XML_FALSE;
}
dtd->in_eldecl = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_PCDATA:
if (dtd->in_eldecl) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_MIXED;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ELEMENT:
quant = XML_CQUANT_NONE;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_OPT:
quant = XML_CQUANT_OPT;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_REP:
quant = XML_CQUANT_REP;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_PLUS:
quant = XML_CQUANT_PLUS;
elementContent:
if (dtd->in_eldecl) {
ELEMENT_TYPE *el;
const XML_Char *name;
int nameLen;
const char *nxt = (quant == XML_CQUANT_NONE
? next
: next - enc->minBytesPerChar);
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
dtd->scaffold[myindex].type = XML_CTYPE_NAME;
dtd->scaffold[myindex].quant = quant;
el = getElementType(parser, enc, s, nxt);
if (!el)
return XML_ERROR_NO_MEMORY;
name = el->name;
dtd->scaffold[myindex].name = name;
nameLen = 0;
for (; name[nameLen++]; );
dtd->contentStringLen += nameLen;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_CLOSE:
quant = XML_CQUANT_NONE;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_OPT:
quant = XML_CQUANT_OPT;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_REP:
quant = XML_CQUANT_REP;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_PLUS:
quant = XML_CQUANT_PLUS;
closeGroup:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
dtd->scaffLevel--;
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
if (dtd->scaffLevel == 0) {
if (!handleDefault) {
XML_Content *model = build_model(parser);
if (!model)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, model);
}
dtd->in_eldecl = XML_FALSE;
dtd->contentStringLen = 0;
}
}
break;
/* End element declaration stuff */
case XML_ROLE_PI:
if (!reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_COMMENT:
if (!reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_NONE:
switch (tok) {
case XML_TOK_BOM:
handleDefault = XML_FALSE;
break;
}
break;
case XML_ROLE_DOCTYPE_NONE:
if (parser->m_startDoctypeDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ENTITY_NONE:
if (dtd->keepProcessing && parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_NOTATION_NONE:
if (parser->m_notationDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTLIST_NONE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ELEMENT_NONE:
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
} /* end of big switch */
if (handleDefault && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
s = next;
tok = XmlPrologTok(enc, s, end, &next);
}
}
/* not reached */
}
static enum XML_Error PTRCALL
epilogProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
parser->m_processor = epilogProcessor;
parser->m_eventPtr = s;
for (;;) {
const char *next = NULL;
int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
parser->m_eventEndPtr = next;
switch (tok) {
/* report partial linebreak - it might be the last token */
case -XML_TOK_PROLOG_S:
if (parser->m_defaultHandler) {
reportDefault(parser, parser->m_encoding, s, next);
if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
}
*nextPtr = next;
return XML_ERROR_NONE;
case XML_TOK_NONE:
*nextPtr = s;
return XML_ERROR_NONE;
case XML_TOK_PROLOG_S:
if (parser->m_defaultHandler)
reportDefault(parser, parser->m_encoding, s, next);
break;
case XML_TOK_PI:
if (!reportProcessingInstruction(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
if (!reportComment(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_INVALID:
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (!parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
if (!parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
default:
return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
}
parser->m_eventPtr = s = next;
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default: ;
}
}
}
static enum XML_Error
processInternalEntity(XML_Parser parser, ENTITY *entity,
XML_Bool betweenDecl)
{
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
}
else {
openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (!openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
next, &next, XML_FALSE);
}
else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart,
textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
}
else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
static enum XML_Error PTRCALL
internalEntityProcessor(XML_Parser parser,
const char *s,
const char *end,
const char **nextPtr)
{
ENTITY *entity;
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
if (!openEntity)
return XML_ERROR_UNEXPECTED_STATE;
entity = openEntity->entity;
textStart = ((char *)entity->textPtr) + entity->processed;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
next, &next, XML_FALSE);
}
else
#endif /* XML_DTD */
result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - (char *)entity->textPtr);
return result;
}
else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
#ifdef XML_DTD
if (entity->is_param) {
int tok;
parser->m_processor = prologProcessor;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
else
#endif /* XML_DTD */
{
parser->m_processor = contentProcessor;
/* see externalEntityContentProcessor vs contentProcessor */
return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end,
nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
}
static enum XML_Error PTRCALL
errorProcessor(XML_Parser parser,
const char *UNUSED_P(s),
const char *UNUSED_P(end),
const char **UNUSED_P(nextPtr))
{
return parser->m_errorCode;
}
static enum XML_Error
storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end,
STRING_POOL *pool)
{
enum XML_Error result = appendAttributeValue(parser, enc, isCdata, ptr,
end, pool);
if (result)
return result;
if (!isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
poolChop(pool);
if (!poolAppendChar(pool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
return XML_ERROR_NONE;
}
static enum XML_Error
appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end,
STRING_POOL *pool)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
for (;;) {
const char *next;
int tok = XmlAttributeValueTok(enc, ptr, end, &next);
switch (tok) {
case XML_TOK_NONE:
return XML_ERROR_NONE;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_CHAR_REF:
{
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, ptr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BAD_CHAR_REF;
}
if (!isCdata
&& n == 0x20 /* space */
&& (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (!poolAppendChar(pool, buf[i]))
return XML_ERROR_NO_MEMORY;
}
}
break;
case XML_TOK_DATA_CHARS:
if (!poolAppend(pool, enc, ptr, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_TRAILING_CR:
next = ptr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_ATTRIBUTE_VALUE_S:
case XML_TOK_DATA_NEWLINE:
if (!isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
if (!poolAppendChar(pool, 0x20))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_ENTITY_REF:
{
const XML_Char *name;
ENTITY *entity;
char checkEntityDecl;
XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
ptr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (ch) {
if (!poolAppendChar(pool, ch))
return XML_ERROR_NO_MEMORY;
break;
}
name = poolStoreString(&parser->m_temp2Pool, enc,
ptr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
poolDiscard(&parser->m_temp2Pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal.
*/
if (pool == &dtd->pool) /* are we called from prolog? */
checkEntityDecl =
#ifdef XML_DTD
parser->m_prologState.documentEntity &&
#endif /* XML_DTD */
(dtd->standalone
? !parser->m_openInternalEntities
: !dtd->hasParamEntityRefs);
else /* if (pool == &parser->m_tempPool): we are called from content */
checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone;
if (checkEntityDecl) {
if (!entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (!entity->is_internal)
return XML_ERROR_ENTITY_DECLARED_IN_PE;
}
else if (!entity) {
/* Cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler.
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
/* Cannot call the default handler because this would be
out of sync with the call to the startElementHandler.
if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
reportDefault(parser, enc, ptr, next);
*/
break;
}
if (entity->open) {
if (enc == parser->m_encoding) {
/* It does not appear that this line can be executed.
*
* The "if (entity->open)" check catches recursive entity
* definitions. In order to be called with an open
* entity, it must have gone through this code before and
* been through the recursive call to
* appendAttributeValue() some lines below. That call
* sets the local encoding ("enc") to the parser's
* internal encoding (internal_utf8 or internal_utf16),
* which can never be the same as the principle encoding.
* It doesn't appear there is another code path that gets
* here with entity->open being TRUE.
*
* Since it is not certain that this logic is watertight,
* we keep the line and merely exclude it from coverage
* tests.
*/
parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
}
return XML_ERROR_RECURSIVE_ENTITY_REF;
}
if (entity->notation) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_BINARY_ENTITY_REF;
}
if (!entity->textPtr) {
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
}
else {
enum XML_Error result;
const XML_Char *textEnd = entity->textPtr + entity->textLen;
entity->open = XML_TRUE;
result = appendAttributeValue(parser, parser->m_internalEncoding, isCdata,
(char *)entity->textPtr,
(char *)textEnd, pool);
entity->open = XML_FALSE;
if (result)
return result;
}
}
break;
default:
/* The only token returned by XmlAttributeValueTok() that does
* not have an explicit case here is XML_TOK_PARTIAL_CHAR.
* Getting that would require an entity name to contain an
* incomplete XML character (e.g. \xE2\x82); however previous
* tokenisers will have already recognised and rejected such
* names before XmlAttributeValueTok() gets a look-in. This
* default case should be retained as a safety net, but the code
* excluded from coverage tests.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = ptr;
return XML_ERROR_UNEXPECTED_STATE;
/* LCOV_EXCL_STOP */
}
ptr = next;
}
/* not reached */
}
static enum XML_Error
storeEntityValue(XML_Parser parser,
const ENCODING *enc,
const char *entityTextPtr,
const char *entityTextEnd)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
STRING_POOL *pool = &(dtd->entityValuePool);
enum XML_Error result = XML_ERROR_NONE;
#ifdef XML_DTD
int oldInEntityValue = parser->m_prologState.inEntityValue;
parser->m_prologState.inEntityValue = 1;
#endif /* XML_DTD */
/* never return Null for the value argument in EntityDeclHandler,
since this would indicate an external entity; therefore we
have to make sure that entityValuePool.start is not null */
if (!pool->blocks) {
if (!poolGrow(pool))
return XML_ERROR_NO_MEMORY;
}
for (;;) {
const char *next;
int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
#ifdef XML_DTD
if (parser->m_isParamEntity || enc != parser->m_encoding) {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&parser->m_tempPool, enc,
entityTextPtr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&parser->m_tempPool);
if (!entity) {
/* not a well-formedness error - see XML 1.0: WFC Entity Declared */
/* cannot report skipped entity here - see comments on
parser->m_skippedEntityHandler
if (parser->m_skippedEntityHandler)
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
dtd->keepProcessing = dtd->standalone;
goto endEntityValue;
}
if (entity->open) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_RECURSIVE_ENTITY_REF;
goto endEntityValue;
}
if (entity->systemId) {
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
entity->publicId)) {
entity->open = XML_FALSE;
result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
goto endEntityValue;
}
entity->open = XML_FALSE;
if (!dtd->paramEntityRead)
dtd->keepProcessing = dtd->standalone;
}
else
dtd->keepProcessing = dtd->standalone;
}
else {
entity->open = XML_TRUE;
result = storeEntityValue(parser,
parser->m_internalEncoding,
(char *)entity->textPtr,
(char *)(entity->textPtr
+ entity->textLen));
entity->open = XML_FALSE;
if (result)
goto endEntityValue;
}
break;
}
#endif /* XML_DTD */
/* In the internal subset, PE references are not legal
within markup declarations, e.g entity values in this case. */
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_PARAM_ENTITY_REF;
goto endEntityValue;
case XML_TOK_NONE:
result = XML_ERROR_NONE;
goto endEntityValue;
case XML_TOK_ENTITY_REF:
case XML_TOK_DATA_CHARS:
if (!poolAppend(pool, enc, entityTextPtr, next)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
break;
case XML_TOK_TRAILING_CR:
next = entityTextPtr + enc->minBytesPerChar;
/* fall through */
case XML_TOK_DATA_NEWLINE:
if (pool->end == pool->ptr && !poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = 0xA;
break;
case XML_TOK_CHAR_REF:
{
XML_Char buf[XML_ENCODE_MAX];
int i;
int n = XmlCharRefNumber(enc, entityTextPtr);
if (n < 0) {
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_BAD_CHAR_REF;
goto endEntityValue;
}
n = XmlEncode(n, (ICHAR *)buf);
/* The XmlEncode() functions can never return 0 here. That
* error return happens if the code point passed in is either
* negative or greater than or equal to 0x110000. The
* XmlCharRefNumber() functions will all return a number
* strictly less than 0x110000 or a negative value if an error
* occurred. The negative value is intercepted above, so
* XmlEncode() is never passed a value it might return an
* error for.
*/
for (i = 0; i < n; i++) {
if (pool->end == pool->ptr && !poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
goto endEntityValue;
}
*(pool->ptr)++ = buf[i];
}
}
break;
case XML_TOK_PARTIAL:
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
case XML_TOK_INVALID:
if (enc == parser->m_encoding)
parser->m_eventPtr = next;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
default:
/* This default case should be unnecessary -- all the tokens
* that XmlEntityValueTok() can return have their own explicit
* cases -- but should be retained for safety. We do however
* exclude it from the coverage statistics.
*
* LCOV_EXCL_START
*/
if (enc == parser->m_encoding)
parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_UNEXPECTED_STATE;
goto endEntityValue;
/* LCOV_EXCL_STOP */
}
entityTextPtr = next;
}
endEntityValue:
#ifdef XML_DTD
parser->m_prologState.inEntityValue = oldInEntityValue;
#endif /* XML_DTD */
return result;
}
static void FASTCALL
normalizeLines(XML_Char *s)
{
XML_Char *p;
for (;; s++) {
if (*s == XML_T('\0'))
return;
if (*s == 0xD)
break;
}
p = s;
do {
if (*s == 0xD) {
*p++ = 0xA;
if (*++s == 0xA)
s++;
}
else
*p++ = *s++;
} while (*s);
*p = XML_T('\0');
}
static int
reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
const XML_Char *target;
XML_Char *data;
const char *tem;
if (!parser->m_processingInstructionHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
start += enc->minBytesPerChar * 2;
tem = start + XmlNameLength(enc, start);
target = poolStoreString(&parser->m_tempPool, enc, start, tem);
if (!target)
return 0;
poolFinish(&parser->m_tempPool);
data = poolStoreString(&parser->m_tempPool, enc,
XmlSkipS(enc, tem),
end - enc->minBytesPerChar*2);
if (!data)
return 0;
normalizeLines(data);
parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
poolClear(&parser->m_tempPool);
return 1;
}
static int
reportComment(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
XML_Char *data;
if (!parser->m_commentHandler) {
if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
data = poolStoreString(&parser->m_tempPool,
enc,
start + enc->minBytesPerChar * 4,
end - enc->minBytesPerChar * 3);
if (!data)
return 0;
normalizeLines(data);
parser->m_commentHandler(parser->m_handlerArg, data);
poolClear(&parser->m_tempPool);
return 1;
}
static void
reportDefault(XML_Parser parser, const ENCODING *enc,
const char *s, const char *end)
{
if (MUST_CONVERT(enc, s)) {
enum XML_Convert_Result convert_res;
const char **eventPP;
const char **eventEndPP;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
}
else {
/* To get here, two things must be true; the parser must be
* using a character encoding that is not the same as the
* encoding passed in, and the encoding passed in must need
* conversion to the internal format (UTF-8 unless XML_UNICODE
* is defined). The only occasions on which the encoding passed
* in is not the same as the parser's encoding are when it is
* the internal encoding (e.g. a previously defined parameter
* entity, already converted to internal format). This by
* definition doesn't need conversion, so the whole branch never
* gets executed.
*
* For safety's sake we don't delete these lines and merely
* exclude them from coverage statistics.
*
* LCOV_EXCL_START
*/
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
/* LCOV_EXCL_STOP */
}
do {
ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf, (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
*eventPP = s;
} while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
}
else
parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
}
static int
defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
XML_Bool isId, const XML_Char *value, XML_Parser parser)
{
DEFAULT_ATTRIBUTE *att;
if (value || isId) {
/* The handling of default attributes gets messed up if we have
a default which duplicates a non-default. */
int i;
for (i = 0; i < type->nDefaultAtts; i++)
if (attId == type->defaultAtts[i].id)
return 1;
if (isId && !type->idAtt && !attId->xmlns)
type->idAtt = attId;
}
if (type->nDefaultAtts == type->allocDefaultAtts) {
if (type->allocDefaultAtts == 0) {
type->allocDefaultAtts = 8;
type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(parser, type->allocDefaultAtts
* sizeof(DEFAULT_ATTRIBUTE));
if (!type->defaultAtts) {
type->allocDefaultAtts = 0;
return 0;
}
}
else {
DEFAULT_ATTRIBUTE *temp;
int count = type->allocDefaultAtts * 2;
temp = (DEFAULT_ATTRIBUTE *)
REALLOC(parser, type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
if (temp == NULL)
return 0;
type->allocDefaultAtts = count;
type->defaultAtts = temp;
}
}
att = type->defaultAtts + type->nDefaultAtts;
att->id = attId;
att->value = value;
att->isCdata = isCdata;
if (!isCdata)
attId->maybeTokenized = XML_TRUE;
type->nDefaultAtts += 1;
return 1;
}
static int
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
PREFIX *prefix;
const XML_Char *s;
for (s = elementType->name; s != name; s++) {
if (!poolAppendChar(&dtd->pool, *s))
return 0;
}
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return 0;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (!prefix)
return 0;
if (prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
}
}
return 1;
}
static ATTRIBUTE_ID *
getAttributeId(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
ATTRIBUTE_ID *id;
const XML_Char *name;
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
name = poolStoreString(&dtd->pool, enc, start, end);
if (!name)
return NULL;
/* skip quotation mark - its storage will be re-used (like in name[-1]) */
++name;
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name, sizeof(ATTRIBUTE_ID));
if (!id)
return NULL;
if (id->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (!parser->m_ns)
;
else if (name[0] == XML_T(ASCII_x)
&& name[1] == XML_T(ASCII_m)
&& name[2] == XML_T(ASCII_l)
&& name[3] == XML_T(ASCII_n)
&& name[4] == XML_T(ASCII_s)
&& (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
if (name[5] == XML_T('\0'))
id->prefix = &dtd->defaultPrefix;
else
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6, sizeof(PREFIX));
id->xmlns = XML_TRUE;
}
else {
int i;
for (i = 0; name[i]; i++) {
/* attributes without prefix are *not* in the default namespace */
if (name[i] == XML_T(ASCII_COLON)) {
int j;
for (j = 0; j < i; j++) {
if (!poolAppendChar(&dtd->pool, name[j]))
return NULL;
}
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
return NULL;
id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
sizeof(PREFIX));
if (!id->prefix)
return NULL;
if (id->prefix->name == poolStart(&dtd->pool))
poolFinish(&dtd->pool);
else
poolDiscard(&dtd->pool);
break;
}
}
}
}
return id;
}
#define CONTEXT_SEP XML_T(ASCII_FF)
static const XML_Char *
getContext(XML_Parser parser)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
HASH_TABLE_ITER iter;
XML_Bool needSep = XML_FALSE;
if (dtd->defaultPrefix.binding) {
int i;
int len;
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = dtd->defaultPrefix.binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++) {
if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) {
/* Because of memory caching, I don't believe this line can be
* executed.
*
* This is part of a loop copying the default prefix binding
* URI into the parser's temporary string pool. Previously,
* that URI was copied into the same string pool, with a
* terminating NUL character, as part of setContext(). When
* the pool was cleared, that leaves a block definitely big
* enough to hold the URI on the free block list of the pool.
* The URI copy in getContext() therefore cannot run out of
* memory.
*
* If the pool is used between the setContext() and
* getContext() calls, the worst it can do is leave a bigger
* block on the front of the free list. Given that this is
* all somewhat inobvious and program logic can be changed, we
* don't delete the line but we do exclude it from the test
* coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
}
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->prefixes));
for (;;) {
int i;
int len;
const XML_Char *s;
PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
if (!prefix)
break;
if (!prefix->binding) {
/* This test appears to be (justifiable) paranoia. There does
* not seem to be a way of injecting a prefix without a binding
* that doesn't get errored long before this function is called.
* The test should remain for safety's sake, so we instead
* exclude the following line from the coverage statistics.
*/
continue; /* LCOV_EXCL_LINE */
}
if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = prefix->name; *s; s++)
if (!poolAppendChar(&parser->m_tempPool, *s))
return NULL;
if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = prefix->binding->uriLen;
if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++)
if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
return NULL;
needSep = XML_TRUE;
}
hashTableIterInit(&iter, &(dtd->generalEntities));
for (;;) {
const XML_Char *s;
ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
if (!e)
break;
if (!e->open)
continue;
if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = e->name; *s; s++)
if (!poolAppendChar(&parser->m_tempPool, *s))
return 0;
needSep = XML_TRUE;
}
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return NULL;
return parser->m_tempPool.start;
}
static XML_Bool
setContext(XML_Parser parser, const XML_Char *context)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *s = context;
while (*context != XML_T('\0')) {
if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
ENTITY *e;
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&parser->m_tempPool), 0);
if (e)
e->open = XML_TRUE;
if (*s != XML_T('\0'))
s++;
context = s;
poolDiscard(&parser->m_tempPool);
}
else if (*s == XML_T(ASCII_EQUALS)) {
PREFIX *prefix;
if (poolLength(&parser->m_tempPool) == 0)
prefix = &dtd->defaultPrefix;
else {
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&parser->m_tempPool),
sizeof(PREFIX));
if (!prefix)
return XML_FALSE;
if (prefix->name == poolStart(&parser->m_tempPool)) {
prefix->name = poolCopyString(&dtd->pool, prefix->name);
if (!prefix->name)
return XML_FALSE;
}
poolDiscard(&parser->m_tempPool);
}
for (context = s + 1;
*context != CONTEXT_SEP && *context != XML_T('\0');
context++)
if (!poolAppendChar(&parser->m_tempPool, *context))
return XML_FALSE;
if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
&parser->m_inheritedBindings) != XML_ERROR_NONE)
return XML_FALSE;
poolDiscard(&parser->m_tempPool);
if (*context != XML_T('\0'))
++context;
s = context;
}
else {
if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_FALSE;
s++;
}
}
return XML_TRUE;
}
static void FASTCALL
normalizePublicId(XML_Char *publicId)
{
XML_Char *p = publicId;
XML_Char *s;
for (s = publicId; *s; s++) {
switch (*s) {
case 0x20:
case 0xD:
case 0xA:
if (p != publicId && p[-1] != 0x20)
*p++ = 0x20;
break;
default:
*p++ = *s;
}
}
if (p != publicId && p[-1] == 0x20)
--p;
*p = XML_T('\0');
}
static DTD *
dtdCreate(const XML_Memory_Handling_Suite *ms)
{
DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD));
if (p == NULL)
return p;
poolInit(&(p->pool), ms);
poolInit(&(p->entityValuePool), ms);
hashTableInit(&(p->generalEntities), ms);
hashTableInit(&(p->elementTypes), ms);
hashTableInit(&(p->attributeIds), ms);
hashTableInit(&(p->prefixes), ms);
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableInit(&(p->paramEntities), ms);
#endif /* XML_DTD */
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
p->scaffIndex = NULL;
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
return p;
}
static void
dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms)
{
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (!e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableClear(&(p->generalEntities));
#ifdef XML_DTD
p->paramEntityRead = XML_FALSE;
hashTableClear(&(p->paramEntities));
#endif /* XML_DTD */
hashTableClear(&(p->elementTypes));
hashTableClear(&(p->attributeIds));
hashTableClear(&(p->prefixes));
poolClear(&(p->pool));
poolClear(&(p->entityValuePool));
p->defaultPrefix.name = NULL;
p->defaultPrefix.binding = NULL;
p->in_eldecl = XML_FALSE;
ms->free_fcn(p->scaffIndex);
p->scaffIndex = NULL;
ms->free_fcn(p->scaffold);
p->scaffold = NULL;
p->scaffLevel = 0;
p->scaffSize = 0;
p->scaffCount = 0;
p->contentStringLen = 0;
p->keepProcessing = XML_TRUE;
p->hasParamEntityRefs = XML_FALSE;
p->standalone = XML_FALSE;
}
static void
dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms)
{
HASH_TABLE_ITER iter;
hashTableIterInit(&iter, &(p->elementTypes));
for (;;) {
ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (!e)
break;
if (e->allocDefaultAtts != 0)
ms->free_fcn(e->defaultAtts);
}
hashTableDestroy(&(p->generalEntities));
#ifdef XML_DTD
hashTableDestroy(&(p->paramEntities));
#endif /* XML_DTD */
hashTableDestroy(&(p->elementTypes));
hashTableDestroy(&(p->attributeIds));
hashTableDestroy(&(p->prefixes));
poolDestroy(&(p->pool));
poolDestroy(&(p->entityValuePool));
if (isDocEntity) {
ms->free_fcn(p->scaffIndex);
ms->free_fcn(p->scaffold);
}
ms->free_fcn(p);
}
/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
The new DTD has already been initialized.
*/
static int
dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms)
{
HASH_TABLE_ITER iter;
/* Copy the prefix table. */
hashTableIterInit(&iter, &(oldDtd->prefixes));
for (;;) {
const XML_Char *name;
const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
if (!oldP)
break;
name = poolCopyString(&(newDtd->pool), oldP->name);
if (!name)
return 0;
if (!lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
return 0;
}
hashTableIterInit(&iter, &(oldDtd->attributeIds));
/* Copy the attribute id table. */
for (;;) {
ATTRIBUTE_ID *newA;
const XML_Char *name;
const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
if (!oldA)
break;
/* Remember to allocate the scratch byte before the name. */
if (!poolAppendChar(&(newDtd->pool), XML_T('\0')))
return 0;
name = poolCopyString(&(newDtd->pool), oldA->name);
if (!name)
return 0;
++name;
newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
sizeof(ATTRIBUTE_ID));
if (!newA)
return 0;
newA->maybeTokenized = oldA->maybeTokenized;
if (oldA->prefix) {
newA->xmlns = oldA->xmlns;
if (oldA->prefix == &oldDtd->defaultPrefix)
newA->prefix = &newDtd->defaultPrefix;
else
newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldA->prefix->name, 0);
}
}
/* Copy the element type table. */
hashTableIterInit(&iter, &(oldDtd->elementTypes));
for (;;) {
int i;
ELEMENT_TYPE *newE;
const XML_Char *name;
const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
if (!oldE)
break;
name = poolCopyString(&(newDtd->pool), oldE->name);
if (!name)
return 0;
newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
sizeof(ELEMENT_TYPE));
if (!newE)
return 0;
if (oldE->nDefaultAtts) {
newE->defaultAtts = (DEFAULT_ATTRIBUTE *)
ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
if (!newE->defaultAtts) {
return 0;
}
}
if (oldE->idAtt)
newE->idAtt = (ATTRIBUTE_ID *)
lookup(oldParser, &(newDtd->attributeIds), oldE->idAtt->name, 0);
newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
if (oldE->prefix)
newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
oldE->prefix->name, 0);
for (i = 0; i < newE->nDefaultAtts; i++) {
newE->defaultAtts[i].id = (ATTRIBUTE_ID *)
lookup(oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
if (oldE->defaultAtts[i].value) {
newE->defaultAtts[i].value
= poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
if (!newE->defaultAtts[i].value)
return 0;
}
else
newE->defaultAtts[i].value = NULL;
}
}
/* Copy the entity tables. */
if (!copyEntityTable(oldParser,
&(newDtd->generalEntities),
&(newDtd->pool),
&(oldDtd->generalEntities)))
return 0;
#ifdef XML_DTD
if (!copyEntityTable(oldParser,
&(newDtd->paramEntities),
&(newDtd->pool),
&(oldDtd->paramEntities)))
return 0;
newDtd->paramEntityRead = oldDtd->paramEntityRead;
#endif /* XML_DTD */
newDtd->keepProcessing = oldDtd->keepProcessing;
newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
newDtd->standalone = oldDtd->standalone;
/* Don't want deep copying for scaffolding */
newDtd->in_eldecl = oldDtd->in_eldecl;
newDtd->scaffold = oldDtd->scaffold;
newDtd->contentStringLen = oldDtd->contentStringLen;
newDtd->scaffSize = oldDtd->scaffSize;
newDtd->scaffLevel = oldDtd->scaffLevel;
newDtd->scaffIndex = oldDtd->scaffIndex;
return 1;
} /* End dtdCopy */
static int
copyEntityTable(XML_Parser oldParser,
HASH_TABLE *newTable,
STRING_POOL *newPool,
const HASH_TABLE *oldTable)
{
HASH_TABLE_ITER iter;
const XML_Char *cachedOldBase = NULL;
const XML_Char *cachedNewBase = NULL;
hashTableIterInit(&iter, oldTable);
for (;;) {
ENTITY *newE;
const XML_Char *name;
const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
if (!oldE)
break;
name = poolCopyString(newPool, oldE->name);
if (!name)
return 0;
newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
if (!newE)
return 0;
if (oldE->systemId) {
const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
if (!tem)
return 0;
newE->systemId = tem;
if (oldE->base) {
if (oldE->base == cachedOldBase)
newE->base = cachedNewBase;
else {
cachedOldBase = oldE->base;
tem = poolCopyString(newPool, cachedOldBase);
if (!tem)
return 0;
cachedNewBase = newE->base = tem;
}
}
if (oldE->publicId) {
tem = poolCopyString(newPool, oldE->publicId);
if (!tem)
return 0;
newE->publicId = tem;
}
}
else {
const XML_Char *tem = poolCopyStringN(newPool, oldE->textPtr,
oldE->textLen);
if (!tem)
return 0;
newE->textPtr = tem;
newE->textLen = oldE->textLen;
}
if (oldE->notation) {
const XML_Char *tem = poolCopyString(newPool, oldE->notation);
if (!tem)
return 0;
newE->notation = tem;
}
newE->is_param = oldE->is_param;
newE->is_internal = oldE->is_internal;
}
return 1;
}
#define INIT_POWER 6
static XML_Bool FASTCALL
keyeq(KEY s1, KEY s2)
{
for (; *s1 == *s2; s1++, s2++)
if (*s1 == 0)
return XML_TRUE;
return XML_FALSE;
}
static size_t
keylen(KEY s)
{
size_t len = 0;
for (; *s; s++, len++);
return len;
}
static void
copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key)
{
key->k[0] = 0;
key->k[1] = get_hash_secret_salt(parser);
}
static unsigned long FASTCALL
hash(XML_Parser parser, KEY s)
{
struct siphash state;
struct sipkey key;
(void)sip24_valid;
copy_salt_to_sipkey(parser, &key);
sip24_init(&state, &key);
sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
return (unsigned long)sip24_final(&state);
}
static NAMED *
lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize)
{
size_t i;
if (table->size == 0) {
size_t tsize;
if (!createSize)
return NULL;
table->power = INIT_POWER;
/* table->size is a power of 2 */
table->size = (size_t)1 << INIT_POWER;
tsize = table->size * sizeof(NAMED *);
table->v = (NAMED **)table->mem->malloc_fcn(tsize);
if (!table->v) {
table->size = 0;
return NULL;
}
memset(table->v, 0, tsize);
i = hash(parser, name) & ((unsigned long)table->size - 1);
}
else {
unsigned long h = hash(parser, name);
unsigned long mask = (unsigned long)table->size - 1;
unsigned char step = 0;
i = h & mask;
while (table->v[i]) {
if (keyeq(name, table->v[i]->name))
return table->v[i];
if (!step)
step = PROBE_STEP(h, mask, table->power);
i < step ? (i += table->size - step) : (i -= step);
}
if (!createSize)
return NULL;
/* check for overflow (table is half full) */
if (table->used >> (table->power - 1)) {
unsigned char newPower = table->power + 1;
size_t newSize = (size_t)1 << newPower;
unsigned long newMask = (unsigned long)newSize - 1;
size_t tsize = newSize * sizeof(NAMED *);
NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize);
if (!newV)
return NULL;
memset(newV, 0, tsize);
for (i = 0; i < table->size; i++)
if (table->v[i]) {
unsigned long newHash = hash(parser, table->v[i]->name);
size_t j = newHash & newMask;
step = 0;
while (newV[j]) {
if (!step)
step = PROBE_STEP(newHash, newMask, newPower);
j < step ? (j += newSize - step) : (j -= step);
}
newV[j] = table->v[i];
}
table->mem->free_fcn(table->v);
table->v = newV;
table->power = newPower;
table->size = newSize;
i = h & newMask;
step = 0;
while (table->v[i]) {
if (!step)
step = PROBE_STEP(h, newMask, newPower);
i < step ? (i += newSize - step) : (i -= step);
}
}
}
table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize);
if (!table->v[i])
return NULL;
memset(table->v[i], 0, createSize);
table->v[i]->name = name;
(table->used)++;
return table->v[i];
}
static void FASTCALL
hashTableClear(HASH_TABLE *table)
{
size_t i;
for (i = 0; i < table->size; i++) {
table->mem->free_fcn(table->v[i]);
table->v[i] = NULL;
}
table->used = 0;
}
static void FASTCALL
hashTableDestroy(HASH_TABLE *table)
{
size_t i;
for (i = 0; i < table->size; i++)
table->mem->free_fcn(table->v[i]);
table->mem->free_fcn(table->v);
}
static void FASTCALL
hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms)
{
p->power = 0;
p->size = 0;
p->used = 0;
p->v = NULL;
p->mem = ms;
}
static void FASTCALL
hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table)
{
iter->p = table->v;
iter->end = iter->p + table->size;
}
static NAMED * FASTCALL
hashTableIterNext(HASH_TABLE_ITER *iter)
{
while (iter->p != iter->end) {
NAMED *tem = *(iter->p)++;
if (tem)
return tem;
}
return NULL;
}
static void FASTCALL
poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms)
{
pool->blocks = NULL;
pool->freeBlocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
pool->mem = ms;
}
static void FASTCALL
poolClear(STRING_POOL *pool)
{
if (!pool->freeBlocks)
pool->freeBlocks = pool->blocks;
else {
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
p->next = pool->freeBlocks;
pool->freeBlocks = p;
p = tem;
}
}
pool->blocks = NULL;
pool->start = NULL;
pool->ptr = NULL;
pool->end = NULL;
}
static void FASTCALL
poolDestroy(STRING_POOL *pool)
{
BLOCK *p = pool->blocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
p = pool->freeBlocks;
while (p) {
BLOCK *tem = p->next;
pool->mem->free_fcn(p);
p = tem;
}
}
static XML_Char *
poolAppend(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end)
{
if (!pool->ptr && !poolGrow(pool))
return NULL;
for (;;) {
const enum XML_Convert_Result convert_res = XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
if (!poolGrow(pool))
return NULL;
}
return pool->start;
}
static const XML_Char * FASTCALL
poolCopyString(STRING_POOL *pool, const XML_Char *s)
{
do {
if (!poolAppendChar(pool, *s))
return NULL;
} while (*s++);
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char *
poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n)
{
if (!pool->ptr && !poolGrow(pool)) {
/* The following line is unreachable given the current usage of
* poolCopyStringN(). Currently it is called from exactly one
* place to copy the text of a simple general entity. By that
* point, the name of the entity is already stored in the pool, so
* pool->ptr cannot be NULL.
*
* If poolCopyStringN() is used elsewhere as it well might be,
* this line may well become executable again. Regardless, this
* sort of check shouldn't be removed lightly, so we just exclude
* it from the coverage statistics.
*/
return NULL; /* LCOV_EXCL_LINE */
}
for (; n > 0; --n, s++) {
if (!poolAppendChar(pool, *s))
return NULL;
}
s = pool->start;
poolFinish(pool);
return s;
}
static const XML_Char * FASTCALL
poolAppendString(STRING_POOL *pool, const XML_Char *s)
{
while (*s) {
if (!poolAppendChar(pool, *s))
return NULL;
s++;
}
return pool->start;
}
static XML_Char *
poolStoreString(STRING_POOL *pool, const ENCODING *enc,
const char *ptr, const char *end)
{
if (!poolAppend(pool, enc, ptr, end))
return NULL;
if (pool->ptr == pool->end && !poolGrow(pool))
return NULL;
*(pool->ptr)++ = 0;
return pool->start;
}
static size_t
poolBytesToAllocateFor(int blockSize)
{
/* Unprotected math would be:
** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
**
** Detect overflow, avoiding _signed_ overflow undefined behavior
** For a + b * c we check b * c in isolation first, so that addition of a
** on top has no chance of making us accept a small non-negative number
*/
const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
if (blockSize <= 0)
return 0;
if (blockSize > (int)(INT_MAX / stretch))
return 0;
{
const int stretchedBlockSize = blockSize * (int)stretch;
const int bytesToAllocate = (int)(
offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
if (bytesToAllocate < 0)
return 0;
return (size_t)bytesToAllocate;
}
}
static XML_Bool FASTCALL
poolGrow(STRING_POOL *pool)
{
if (pool->freeBlocks) {
if (pool->start == 0) {
pool->blocks = pool->freeBlocks;
pool->freeBlocks = pool->freeBlocks->next;
pool->blocks->next = NULL;
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
pool->ptr = pool->start;
return XML_TRUE;
}
if (pool->end - pool->start < pool->freeBlocks->size) {
BLOCK *tem = pool->freeBlocks->next;
pool->freeBlocks->next = pool->blocks;
pool->blocks = pool->freeBlocks;
pool->freeBlocks = tem;
memcpy(pool->blocks->s, pool->start,
(pool->end - pool->start) * sizeof(XML_Char));
pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
pool->start = pool->blocks->s;
pool->end = pool->start + pool->blocks->size;
return XML_TRUE;
}
}
if (pool->blocks && pool->start == pool->blocks->s) {
BLOCK *temp;
int blockSize = (int)((unsigned)(pool->end - pool->start)*2U);
size_t bytesToAllocate;
/* NOTE: Needs to be calculated prior to calling `realloc`
to avoid dangling pointers: */
const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX/2 bytes have already been allocated. This isn't
* readily testable, since it is unlikely that an average
* machine will have that much memory, so we exclude it from the
* coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
temp = (BLOCK *)
pool->mem->realloc_fcn(pool->blocks, (unsigned)bytesToAllocate);
if (temp == NULL)
return XML_FALSE;
pool->blocks = temp;
pool->blocks->size = blockSize;
pool->ptr = pool->blocks->s + offsetInsideBlock;
pool->start = pool->blocks->s;
pool->end = pool->start + blockSize;
}
else {
BLOCK *tem;
int blockSize = (int)(pool->end - pool->start);
size_t bytesToAllocate;
if (blockSize < 0) {
/* This condition traps a situation where either more than
* INT_MAX bytes have already been allocated (which is prevented
* by various pieces of program logic, not least this one, never
* mind the unlikelihood of actually having that much memory) or
* the pool control fields have been corrupted (which could
* conceivably happen in an extremely buggy user handler
* function). Either way it isn't readily testable, so we
* exclude it from the coverage statistics.
*/
return XML_FALSE; /* LCOV_EXCL_LINE */
}
if (blockSize < INIT_BLOCK_SIZE)
blockSize = INIT_BLOCK_SIZE;
else {
/* Detect overflow, avoiding _signed_ overflow undefined behavior */
if ((int)((unsigned)blockSize * 2U) < 0) {
return XML_FALSE;
}
blockSize *= 2;
}
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
return XML_FALSE;
tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate);
if (!tem)
return XML_FALSE;
tem->size = blockSize;
tem->next = pool->blocks;
pool->blocks = tem;
if (pool->ptr != pool->start)
memcpy(tem->s, pool->start,
(pool->ptr - pool->start) * sizeof(XML_Char));
pool->ptr = tem->s + (pool->ptr - pool->start);
pool->start = tem->s;
pool->end = tem->s + blockSize;
}
return XML_TRUE;
}
static int FASTCALL
nextScaffoldPart(XML_Parser parser)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
CONTENT_SCAFFOLD * me;
int next;
if (!dtd->scaffIndex) {
dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
if (!dtd->scaffIndex)
return -1;
dtd->scaffIndex[0] = 0;
}
if (dtd->scaffCount >= dtd->scaffSize) {
CONTENT_SCAFFOLD *temp;
if (dtd->scaffold) {
temp = (CONTENT_SCAFFOLD *)
REALLOC(parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize *= 2;
}
else {
temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
* sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
}
dtd->scaffold = temp;
}
next = dtd->scaffCount++;
me = &dtd->scaffold[next];
if (dtd->scaffLevel) {
CONTENT_SCAFFOLD *parent = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel-1]];
if (parent->lastchild) {
dtd->scaffold[parent->lastchild].nextsib = next;
}
if (!parent->childcnt)
parent->firstchild = next;
parent->lastchild = next;
parent->childcnt++;
}
me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
return next;
}
static void
build_node(XML_Parser parser,
int src_node,
XML_Content *dest,
XML_Content **contpos,
XML_Char **strpos)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
dest->type = dtd->scaffold[src_node].type;
dest->quant = dtd->scaffold[src_node].quant;
if (dest->type == XML_CTYPE_NAME) {
const XML_Char *src;
dest->name = *strpos;
src = dtd->scaffold[src_node].name;
for (;;) {
*(*strpos)++ = *src;
if (!*src)
break;
src++;
}
dest->numchildren = 0;
dest->children = NULL;
}
else {
unsigned int i;
int cn;
dest->numchildren = dtd->scaffold[src_node].childcnt;
dest->children = *contpos;
*contpos += dest->numchildren;
for (i = 0, cn = dtd->scaffold[src_node].firstchild;
i < dest->numchildren;
i++, cn = dtd->scaffold[cn].nextsib) {
build_node(parser, cn, &(dest->children[i]), contpos, strpos);
}
dest->name = NULL;
}
}
static XML_Content *
build_model (XML_Parser parser)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
XML_Content *ret;
XML_Content *cpos;
XML_Char * str;
int allocsize = (dtd->scaffCount * sizeof(XML_Content)
+ (dtd->contentStringLen * sizeof(XML_Char)));
ret = (XML_Content *)MALLOC(parser, allocsize);
if (!ret)
return NULL;
str = (XML_Char *) (&ret[dtd->scaffCount]);
cpos = &ret[1];
build_node(parser, 0, ret, &cpos, &str);
return ret;
}
static ELEMENT_TYPE *
getElementType(XML_Parser parser,
const ENCODING *enc,
const char *ptr,
const char *end)
{
DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
ELEMENT_TYPE *ret;
if (!name)
return NULL;
ret = (ELEMENT_TYPE *) lookup(parser, &dtd->elementTypes, name, sizeof(ELEMENT_TYPE));
if (!ret)
return NULL;
if (ret->name != name)
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
if (!setElementTypePrefix(parser, ret))
return NULL;
}
return ret;
}
static XML_Char *
copyString(const XML_Char *s,
const XML_Memory_Handling_Suite *memsuite)
{
int charsRequired = 0;
XML_Char *result;
/* First determine how long the string is */
while (s[charsRequired] != 0) {
charsRequired++;
}
/* Include the terminator */
charsRequired++;
/* Now allocate space for the copy */
result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
if (result == NULL)
return NULL;
/* Copy the original into place */
memcpy(result, s, charsRequired * sizeof(XML_Char));
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/bad_537_0 |
crossvul-cpp_data_bad_4362_2 | #include <xml_relax_ng.h>
static void dealloc(xmlRelaxNGPtr schema)
{
NOKOGIRI_DEBUG_START(schema);
xmlRelaxNGFree(schema);
NOKOGIRI_DEBUG_END(schema);
}
/*
* call-seq:
* validate_document(document)
*
* Validate a Nokogiri::XML::Document against this RelaxNG schema.
*/
static VALUE validate_document(VALUE self, VALUE document)
{
xmlDocPtr doc;
xmlRelaxNGPtr schema;
VALUE errors;
xmlRelaxNGValidCtxtPtr valid_ctxt;
Data_Get_Struct(self, xmlRelaxNG, schema);
Data_Get_Struct(document, xmlDoc, doc);
errors = rb_ary_new();
valid_ctxt = xmlRelaxNGNewValidCtxt(schema);
if(NULL == valid_ctxt) {
/* we have a problem */
rb_raise(rb_eRuntimeError, "Could not create a validation context");
}
#ifdef HAVE_XMLRELAXNGSETVALIDSTRUCTUREDERRORS
xmlRelaxNGSetValidStructuredErrors(
valid_ctxt,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
xmlRelaxNGValidateDoc(valid_ctxt, doc);
xmlRelaxNGFreeValidCtxt(valid_ctxt);
return errors;
}
/*
* call-seq:
* read_memory(string)
*
* Create a new RelaxNG from the contents of +string+
*/
static VALUE read_memory(VALUE klass, VALUE content)
{
xmlRelaxNGParserCtxtPtr ctx = xmlRelaxNGNewMemParserCtxt(
(const char *)StringValuePtr(content),
(int)RSTRING_LEN(content)
);
xmlRelaxNGPtr schema;
VALUE errors = rb_ary_new();
VALUE rb_schema;
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS
xmlRelaxNGSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlRelaxNGParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlRelaxNGFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
return rb_schema;
}
/*
* call-seq:
* from_document(doc)
*
* Create a new RelaxNG schema from the Nokogiri::XML::Document +doc+
*/
static VALUE from_document(VALUE klass, VALUE document)
{
xmlDocPtr doc;
xmlRelaxNGParserCtxtPtr ctx;
xmlRelaxNGPtr schema;
VALUE errors;
VALUE rb_schema;
Data_Get_Struct(document, xmlDoc, doc);
/* In case someone passes us a node. ugh. */
doc = doc->doc;
ctx = xmlRelaxNGNewDocParserCtxt(doc);
errors = rb_ary_new();
xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS
xmlRelaxNGSetParserStructuredErrors(
ctx,
Nokogiri_error_array_pusher,
(void *)errors
);
#endif
schema = xmlRelaxNGParse(ctx);
xmlSetStructuredErrorFunc(NULL, NULL);
xmlRelaxNGFreeParserCtxt(ctx);
if(NULL == schema) {
xmlErrorPtr error = xmlGetLastError();
if(error)
Nokogiri_error_raise(NULL, error);
else
rb_raise(rb_eRuntimeError, "Could not parse document");
return Qnil;
}
rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
rb_iv_set(rb_schema, "@errors", errors);
return rb_schema;
}
VALUE cNokogiriXmlRelaxNG;
void init_xml_relax_ng()
{
VALUE nokogiri = rb_define_module("Nokogiri");
VALUE xml = rb_define_module_under(nokogiri, "XML");
VALUE klass = rb_define_class_under(xml, "RelaxNG", cNokogiriXmlSchema);
cNokogiriXmlRelaxNG = klass;
rb_define_singleton_method(klass, "read_memory", read_memory, 1);
rb_define_singleton_method(klass, "from_document", from_document, 1);
rb_define_private_method(klass, "validate_document", validate_document, 1);
}
| ./CrossVul/dataset_final_sorted/CWE-611/c/bad_4362_2 |
crossvul-cpp_data_good_599_0 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/HTTP2Constants.h>
#include <proxygen/lib/http/codec/CodecUtil.h>
#include <proxygen/lib/utils/Logging.h>
#include <proxygen/lib/utils/Base64.h>
#include <folly/Conv.h>
#include <folly/Random.h>
#include <folly/ThreadLocal.h>
#include <folly/io/Cursor.h>
#include <folly/tracing/ScopedTraceSection.h>
#include <type_traits>
using namespace proxygen::compress;
using namespace folly::io;
using namespace folly;
using std::string;
namespace {
std::string base64url_encode(ByteRange range) {
return proxygen::Base64::urlEncode(range);
}
std::string base64url_decode(const std::string& str) {
return proxygen::Base64::urlDecode(str);
}
}
namespace proxygen {
HTTP2Codec::HTTP2Codec(TransportDirection direction)
: HTTPParallelCodec(direction),
headerCodec_(direction),
frameState_(direction == TransportDirection::DOWNSTREAM
? FrameState::UPSTREAM_CONNECTION_PREFACE
: FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
const auto maxHeaderListSize = egressSettings_.getSetting(
SettingsId::MAX_HEADER_LIST_SIZE);
if (maxHeaderListSize) {
headerCodec_.setMaxUncompressed(maxHeaderListSize->value);
}
VLOG(4) << "creating " << getTransportDirectionString(direction)
<< " HTTP/2 codec";
}
HTTP2Codec::~HTTP2Codec() {}
// HTTPCodec API
size_t HTTP2Codec::onIngress(const folly::IOBuf& buf) {
// TODO: ensure only 1 parse at a time on stack.
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - onIngress");
Cursor cursor(&buf);
size_t parsed = 0;
ErrorCode connError = ErrorCode::NO_ERROR;
for (auto bufLen = cursor.totalLength();
connError == ErrorCode::NO_ERROR;
bufLen = cursor.totalLength()) {
if (frameState_ == FrameState::UPSTREAM_CONNECTION_PREFACE) {
if (bufLen >= http2::kConnectionPreface.length()) {
auto test = cursor.readFixedString(http2::kConnectionPreface.length());
parsed += http2::kConnectionPreface.length();
if (test != http2::kConnectionPreface) {
goawayErrorMessage_ = "missing connection preface";
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
} else if (frameState_ == FrameState::FRAME_HEADER ||
frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
// Waiting to parse the common frame header
if (bufLen >= http2::kFrameHeaderSize) {
connError = parseFrameHeader(cursor, curHeader_);
parsed += http2::kFrameHeaderSize;
if (frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE &&
curHeader_.type != http2::FrameType::SETTINGS) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: got invalid connection preface frame type=",
getFrameTypeString(curHeader_.type), "(", curHeader_.type, ")",
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
if (curHeader_.length > maxRecvFrameSize()) {
VLOG(4) << "Excessively large frame len=" << curHeader_.length;
connError = ErrorCode::FRAME_SIZE_ERROR;
}
if (callback_) {
callback_->onFrameHeader(
curHeader_.stream,
curHeader_.flags,
curHeader_.length,
static_cast<uint8_t>(curHeader_.type));
}
frameState_ = (curHeader_.type == http2::FrameType::DATA) ?
FrameState::DATA_FRAME_DATA : FrameState::FRAME_DATA;
pendingDataFrameBytes_ = curHeader_.length;
pendingDataFramePaddingBytes_ = 0;
#ifndef NDEBUG
receivedFrameCount_++;
#endif
} else {
break;
}
} else if (frameState_ == FrameState::DATA_FRAME_DATA && bufLen > 0 &&
(bufLen < curHeader_.length ||
pendingDataFrameBytes_ < curHeader_.length)) {
// FrameState::DATA_FRAME_DATA with partial data only
size_t dataParsed = 0;
connError = parseDataFrameData(cursor, bufLen, dataParsed);
if (dataParsed == 0 && pendingDataFrameBytes_ > 0) {
// We received only the padding byte, we will wait for more
break;
} else {
parsed += dataParsed;
if (pendingDataFrameBytes_ == 0) {
frameState_ = FrameState::FRAME_HEADER;
}
}
} else { // FrameState::FRAME_DATA
// or FrameState::DATA_FRAME_DATA with all data available
// Already parsed the common frame header
const auto frameLen = curHeader_.length;
if (bufLen >= frameLen) {
connError = parseFrame(cursor);
parsed += curHeader_.length;
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
}
}
checkConnectionError(connError, &buf);
return parsed;
}
ErrorCode HTTP2Codec::parseFrame(folly::io::Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseFrame");
if (expectedContinuationStream_ != 0 &&
(curHeader_.type != http2::FrameType::CONTINUATION ||
expectedContinuationStream_ != curHeader_.stream)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: while expected CONTINUATION with stream=",
expectedContinuationStream_, ", received streamID=", curHeader_.stream,
" of type=", getFrameTypeString(curHeader_.type));
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (expectedContinuationStream_ == 0 &&
curHeader_.type == http2::FrameType::CONTINUATION) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: unexpected CONTINUATION received with streamID=",
curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (frameAffectsCompression(curHeader_.type) &&
curHeaderBlock_.chainLength() + curHeader_.length >
egressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE, 0)) {
// this may be off by up to the padding length (max 255), but
// these numbers are already so generous, and we're comparing the
// max-uncompressed to the actual compressed size. Let's fail
// before buffering.
// TODO(t6513634): it would be nicer to stream-process this header
// block to keep the connection state consistent without consuming
// memory, and fail just the request per the HTTP/2 spec (section
// 10.3)
goawayErrorMessage_ = folly::to<string>(
"Failing connection due to excessively large headers");
LOG(ERROR) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
expectedContinuationStream_ =
(frameAffectsCompression(curHeader_.type) &&
!(curHeader_.flags & http2::END_HEADERS)) ? curHeader_.stream : 0;
switch (curHeader_.type) {
case http2::FrameType::DATA:
return parseAllData(cursor);
case http2::FrameType::HEADERS:
return parseHeaders(cursor);
case http2::FrameType::PRIORITY:
return parsePriority(cursor);
case http2::FrameType::RST_STREAM:
return parseRstStream(cursor);
case http2::FrameType::SETTINGS:
return parseSettings(cursor);
case http2::FrameType::PUSH_PROMISE:
return parsePushPromise(cursor);
case http2::FrameType::EX_HEADERS:
if (ingressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) {
return parseExHeaders(cursor);
} else {
VLOG(2) << "EX_HEADERS not enabled, ignoring the frame";
break;
}
case http2::FrameType::PING:
return parsePing(cursor);
case http2::FrameType::GOAWAY:
return parseGoaway(cursor);
case http2::FrameType::WINDOW_UPDATE:
return parseWindowUpdate(cursor);
case http2::FrameType::CONTINUATION:
return parseContinuation(cursor);
case http2::FrameType::ALTSVC:
// fall through, unimplemented
break;
case http2::FrameType::CERTIFICATE_REQUEST:
return parseCertificateRequest(cursor);
case http2::FrameType::CERTIFICATE:
return parseCertificate(cursor);
default:
// Implementations MUST ignore and discard any frame that has a
// type that is unknown
break;
}
// Landing here means unknown, unimplemented or ignored frame.
VLOG(2) << "Skipping frame (type=" << (uint8_t)curHeader_.type << ")";
cursor.skip(curHeader_.length);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::handleEndStream() {
if (curHeader_.type != http2::FrameType::HEADERS &&
curHeader_.type != http2::FrameType::EX_HEADERS &&
curHeader_.type != http2::FrameType::CONTINUATION &&
curHeader_.type != http2::FrameType::DATA) {
return ErrorCode::NO_ERROR;
}
// do we need to handle case where this stream has already aborted via
// another callback (onHeadersComplete/onBody)?
pendingEndStreamHandling_ |= (curHeader_.flags & http2::END_STREAM);
// with a websocket upgrade, we need to send message complete cb to
// mirror h1x codec's behavior. when the stream closes, we need to
// send another callback to clean up the stream's resources.
if (ingressWebsocketUpgrade_) {
ingressWebsocketUpgrade_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, true);
}
if (pendingEndStreamHandling_ && expectedContinuationStream_ == 0) {
pendingEndStreamHandling_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, false);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseAllData(Cursor& cursor) {
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing all frame DATA bytes for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto ret = http2::parseData(cursor, curHeader_, outData, padding);
RETURN_IF_ERROR(ret);
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return handleEndStream();
}
ErrorCode HTTP2Codec::parseDataFrameData(Cursor& cursor,
size_t bufLen,
size_t& parsed) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseDataFrameData");
if (bufLen == 0) {
VLOG(10) << "No data to parse";
return ErrorCode::NO_ERROR;
}
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing DATA frame data for stream=" << curHeader_.stream <<
" frame data length=" << curHeader_.length << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
// Parse the padding information only the first time
if (pendingDataFrameBytes_ == curHeader_.length &&
pendingDataFramePaddingBytes_ == 0) {
if (frameHasPadding(curHeader_) && bufLen == 1) {
// We need to wait for more bytes otherwise we won't be able to pass
// the correct padding to the first onBody call
return ErrorCode::NO_ERROR;
}
const auto ret = http2::parseDataBegin(cursor, curHeader_, parsed, padding);
RETURN_IF_ERROR(ret);
if (padding > 0) {
pendingDataFramePaddingBytes_ = padding - 1;
pendingDataFrameBytes_--;
bufLen--;
parsed++;
}
VLOG(10) << "out padding=" << padding << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
if (bufLen > 0) {
// Check if we have application data to parse
if (pendingDataFrameBytes_ > pendingDataFramePaddingBytes_) {
const size_t pendingAppData =
pendingDataFrameBytes_ - pendingDataFramePaddingBytes_;
const size_t toClone = std::min(pendingAppData, bufLen);
cursor.clone(outData, toClone);
bufLen -= toClone;
pendingDataFrameBytes_ -= toClone;
parsed += toClone;
VLOG(10) << "parsed some app data, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
// Check if we have padding bytes to parse
if (bufLen > 0 && pendingDataFramePaddingBytes_ > 0) {
size_t toSkip = 0;
auto ret = http2::parseDataEnd(cursor, bufLen,
pendingDataFramePaddingBytes_, toSkip);
RETURN_IF_ERROR(ret);
pendingDataFrameBytes_ -= toSkip;
pendingDataFramePaddingBytes_ -= toSkip;
parsed += toSkip;
VLOG(10) << "parsed some padding, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
}
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return (pendingDataFrameBytes_ > 0) ? ErrorCode::NO_ERROR : handleEndStream();
}
ErrorCode HTTP2Codec::parseHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseHeaders");
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing HEADERS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseHeaders(cursor, curHeader_, priority, headerBuf);
RETURN_IF_ERROR(err);
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, true /* trailersAllowed */));
}
err = parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
folly::none);
return err;
}
ErrorCode HTTP2Codec::parseExHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseExHeaders");
HTTPCodec::ExAttributes exAttributes;
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing ExHEADERS frame for stream=" << curHeader_.stream
<< " length=" << curHeader_.length;
auto err = http2::parseExHeaders(
cursor, curHeader_, exAttributes, priority, headerBuf);
RETURN_IF_ERROR(err);
if (isRequest(curHeader_.stream)) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, false /* trailersAllowed */));
}
return parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
exAttributes);
}
ErrorCode HTTP2Codec::parseContinuation(Cursor& cursor) {
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing CONTINUATION frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseContinuation(cursor, curHeader_, headerBuf);
RETURN_IF_ERROR(err);
err = parseHeadersImpl(cursor, std::move(headerBuf),
folly::none, folly::none, folly::none);
return err;
}
ErrorCode HTTP2Codec::parseHeadersImpl(
Cursor& /*cursor*/,
std::unique_ptr<IOBuf> headerBuf,
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes) {
curHeaderBlock_.append(std::move(headerBuf));
std::unique_ptr<HTTPMessage> msg;
if (curHeader_.flags & http2::END_HEADERS) {
auto errorCode =
parseHeadersDecodeFrames(priority, promisedStream, exAttributes, msg);
if (errorCode.hasValue()) {
return errorCode.value();
}
}
// if we're not parsing CONTINUATION, then it's start of new header block
if (curHeader_.type != http2::FrameType::CONTINUATION) {
headerBlockFrameType_ = curHeader_.type;
}
// Report back what we've parsed
if (callback_) {
auto concurError = parseHeadersCheckConcurrentStreams(priority);
if (concurError.hasValue()) {
return concurError.value();
}
uint32_t headersCompleteStream = curHeader_.stream;
bool trailers = parsingTrailers();
bool allHeaderFramesReceived =
(curHeader_.flags & http2::END_HEADERS) &&
(headerBlockFrameType_ == http2::FrameType::HEADERS);
if (allHeaderFramesReceived && !trailers) {
// Only deliver onMessageBegin once per stream.
// For responses with CONTINUATION, this will be delayed until
// the frame with the END_HEADERS flag set.
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageBegin,
"onMessageBegin",
curHeader_.stream,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::EX_HEADERS) {
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onExMessageBegin,
"onExMessageBegin",
curHeader_.stream,
exAttributes->controlStream,
exAttributes->unidirectional,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::PUSH_PROMISE) {
DCHECK(promisedStream);
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onPushMessageBegin,
"onPushMessageBegin", *promisedStream,
curHeader_.stream, msg.get())) {
return handleEndStream();
}
headersCompleteStream = *promisedStream;
}
if (curHeader_.flags & http2::END_HEADERS && msg) {
if (!(curHeader_.flags & http2::END_STREAM)) {
// If it there are DATA frames coming, consider it chunked
msg->setIsChunked(true);
}
if (trailers) {
VLOG(4) << "Trailers complete for streamId=" << headersCompleteStream
<< " direction=" << transportDirection_;
auto trailerHeaders =
std::make_unique<HTTPHeaders>(msg->extractHeaders());
msg.reset();
callback_->onTrailersComplete(headersCompleteStream,
std::move(trailerHeaders));
} else {
callback_->onHeadersComplete(headersCompleteStream, std::move(msg));
}
}
return handleEndStream();
}
return ErrorCode::NO_ERROR;
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersDecodeFrames(
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes,
std::unique_ptr<HTTPMessage>& msg) {
// decompress headers
Cursor headerCursor(curHeaderBlock_.front());
bool isReq = false;
if (promisedStream) {
isReq = true;
} else if (exAttributes) {
isReq = isRequest(curHeader_.stream);
} else {
isReq = transportDirection_ == TransportDirection::DOWNSTREAM;
}
// Validate circular dependencies.
if (priority && (curHeader_.stream == priority->streamDependency)) {
streamError(
folly::to<string>("Circular dependency for txn=", curHeader_.stream),
ErrorCode::PROTOCOL_ERROR,
curHeader_.type == http2::FrameType::HEADERS);
return ErrorCode::NO_ERROR;
}
decodeInfo_.init(isReq, parsingDownstreamTrailers_);
if (priority) {
decodeInfo_.msg->setHTTP2Priority(
std::make_tuple(priority->streamDependency,
priority->exclusive,
priority->weight));
}
headerCodec_.decodeStreaming(
headerCursor, curHeaderBlock_.chainLength(), this);
msg = std::move(decodeInfo_.msg);
// Saving this in case we need to log it on error
auto g = folly::makeGuard([this] { curHeaderBlock_.move(); });
// Check decoding error
if (decodeInfo_.decodeError != HPACK::DecodeError::NONE) {
static const std::string decodeErrorMessage =
"Failed decoding header block for stream=";
// Avoid logging header blocks that have failed decoding due to being
// excessively large.
if (decodeInfo_.decodeError != HPACK::DecodeError::HEADERS_TOO_LARGE) {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream
<< " header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
} else {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream;
}
if (msg) {
// print the partial message
msg->dumpMessage(3);
}
return ErrorCode::COMPRESSION_ERROR;
}
// Check parsing error
if (decodeInfo_.parsingError != "") {
LOG(ERROR) << "Failed parsing header list for stream=" << curHeader_.stream
<< ", error=" << decodeInfo_.parsingError << ", header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
HTTPException err(HTTPException::Direction::INGRESS,
folly::to<std::string>("HTTP2Codec stream error: ",
"stream=",
curHeader_.stream,
" status=",
400,
" error: ",
decodeInfo_.parsingError));
err.setHttpStatusCode(400);
callback_->onError(curHeader_.stream, err, true);
return ErrorCode::NO_ERROR;
}
return folly::Optional<ErrorCode>();
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersCheckConcurrentStreams(
const folly::Optional<http2::PriorityUpdate>& priority) {
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::EX_HEADERS) {
if (curHeader_.flags & http2::PRIORITY) {
DCHECK(priority);
// callback_->onPriority(priority.get());
}
// callback checks total number of streams is smaller than settings max
if (callback_->numIncomingStreams() >=
egressSettings_.getSetting(SettingsId::MAX_CONCURRENT_STREAMS,
std::numeric_limits<int32_t>::max())) {
streamError(folly::to<string>("Exceeded max_concurrent_streams"),
ErrorCode::REFUSED_STREAM, true);
return ErrorCode::NO_ERROR;
}
}
return folly::Optional<ErrorCode>();
}
void HTTP2Codec::onHeader(const folly::fbstring& name,
const folly::fbstring& value) {
if (decodeInfo_.onHeader(name, value)) {
if (name == "user-agent" && userAgent_.empty()) {
userAgent_ = value.toStdString();
}
} else {
VLOG(4) << "dir=" << uint32_t(transportDirection_) <<
decodeInfo_.parsingError << " codec=" << headerCodec_;
}
}
void HTTP2Codec::onHeadersComplete(HTTPHeaderSize decodedSize,
bool /*acknowledge*/) {
decodeInfo_.onHeadersComplete(decodedSize);
decodeInfo_.msg->setAdvancedProtocolString(http2::kProtocolString);
HTTPMessage* msg = decodeInfo_.msg.get();
HTTPRequestVerifier& verifier = decodeInfo_.verifier;
if ((transportDirection_ == TransportDirection::DOWNSTREAM) &&
verifier.hasUpgradeProtocol() &&
(*msg->getUpgradeProtocol() == headers::kWebsocketString) &&
msg->getMethod() == HTTPMethod::CONNECT) {
msg->setIngressWebsocketUpgrade();
ingressWebsocketUpgrade_ = true;
} else {
auto it = upgradedStreams_.find(curHeader_.stream);
if (it != upgradedStreams_.end()) {
upgradedStreams_.erase(curHeader_.stream);
// a websocket upgrade was sent on this stream.
if (msg->getStatusCode() != 200) {
decodeInfo_.parsingError =
folly::to<string>("Invalid response code to a websocket upgrade: ",
msg->getStatusCode());
return;
}
msg->setIngressWebsocketUpgrade();
}
}
}
void HTTP2Codec::onDecodeError(HPACK::DecodeError decodeError) {
decodeInfo_.decodeError = decodeError;
}
ErrorCode HTTP2Codec::parsePriority(Cursor& cursor) {
VLOG(4) << "parsing PRIORITY frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
http2::PriorityUpdate pri;
auto err = http2::parsePriority(cursor, curHeader_, pri);
RETURN_IF_ERROR(err);
if (curHeader_.stream == pri.streamDependency) {
streamError(folly::to<string>("Circular dependency for txn=",
curHeader_.stream),
ErrorCode::PROTOCOL_ERROR, false);
return ErrorCode::NO_ERROR;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onPriority, "onPriority",
curHeader_.stream,
std::make_tuple(pri.streamDependency,
pri.exclusive,
pri.weight));
return ErrorCode::NO_ERROR;
}
size_t HTTP2Codec::addPriorityNodes(
PriorityQueue& queue,
folly::IOBufQueue& writeBuf,
uint8_t maxLevel) {
HTTPCodec::StreamID parent = 0;
size_t bytes = 0;
while (maxLevel--) {
auto id = createStream();
virtualPriorityNodes_.push_back(id);
queue.addPriorityNode(id, parent);
bytes += generatePriority(writeBuf, id, std::make_tuple(parent, false, 0));
parent = id;
}
return bytes;
}
ErrorCode HTTP2Codec::parseRstStream(Cursor& cursor) {
// rst for stream in idle state - protocol error
VLOG(4) << "parsing RST_STREAM frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
upgradedStreams_.erase(curHeader_.stream);
ErrorCode statusCode = ErrorCode::NO_ERROR;
auto err = http2::parseRstStream(cursor, curHeader_, statusCode);
RETURN_IF_ERROR(err);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: RST_STREAM with code=", getErrorCodeString(statusCode),
" for streamID=", curHeader_.stream, " user-agent=", userAgent_);
VLOG(2) << goawayErrorMessage_;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onAbort, "onAbort",
curHeader_.stream, statusCode);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseSettings(Cursor& cursor) {
VLOG(4) << "parsing SETTINGS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
std::deque<SettingPair> settings;
auto err = http2::parseSettings(cursor, curHeader_, settings);
RETURN_IF_ERROR(err);
if (curHeader_.flags & http2::ACK) {
handleSettingsAck();
return ErrorCode::NO_ERROR;
}
return handleSettings(settings);
}
void HTTP2Codec::handleSettingsAck() {
if (pendingTableMaxSize_) {
headerCodec_.setDecoderHeaderTableMaxSize(*pendingTableMaxSize_);
pendingTableMaxSize_ = folly::none;
}
if (callback_) {
callback_->onSettingsAck();
}
}
ErrorCode HTTP2Codec::handleSettings(const std::deque<SettingPair>& settings) {
SettingsList settingsList;
for (auto& setting: settings) {
switch (setting.first) {
case SettingsId::HEADER_TABLE_SIZE:
{
uint32_t tableSize = setting.second;
if (setting.second > http2::kMaxHeaderTableSize) {
VLOG(2) << "Limiting table size from " << tableSize << " to " <<
http2::kMaxHeaderTableSize;
tableSize = http2::kMaxHeaderTableSize;
}
headerCodec_.setEncoderHeaderTableSize(tableSize);
}
break;
case SettingsId::ENABLE_PUSH:
if ((setting.second != 0 && setting.second != 1) ||
(setting.second == 1 &&
transportDirection_ == TransportDirection::UPSTREAM)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_PUSH invalid setting=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
break;
case SettingsId::INITIAL_WINDOW_SIZE:
if (setting.second > http2::kMaxWindowUpdateSize) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: INITIAL_WINDOW_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_FRAME_SIZE:
if (setting.second < http2::kMaxFramePayloadLengthMin ||
setting.second > http2::kMaxFramePayloadLength) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: MAX_FRAME_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
ingressSettings_.setSetting(SettingsId::MAX_FRAME_SIZE, setting.second);
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
break;
case SettingsId::ENABLE_EX_HEADERS:
{
auto ptr = egressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS);
if (ptr && ptr->value > 0) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " got ENABLE_EX_HEADERS=" << setting.second;
if (setting.second != 0 && setting.second != 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid ENABLE_EX_HEADERS=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
} else {
// egress ENABLE_EX_HEADERS is disabled, consider the ingress
// ENABLE_EX_HEADERS as unknown setting, and ignore it.
continue;
}
}
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.second > 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_CONNECT_PROTOCOL invalid number=",
setting.second, " for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
case SettingsId::SETTINGS_HTTP_CERT_AUTH:
break;
default:
continue; // ignore unknown setting
}
ingressSettings_.setSetting(setting.first, setting.second);
settingsList.push_back(*ingressSettings_.getSetting(setting.first));
}
if (callback_) {
callback_->onSettings(settingsList);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parsePushPromise(Cursor& cursor) {
// stream id must be idle - protocol error
// assoc-stream-id=closed/unknown - protocol error, unless rst_stream sent
/*
* What does "must handle" mean in the following context? I have to
* accept this as a valid pushed resource?
However, an endpoint that has sent RST_STREAM on the associated
stream MUST handle PUSH_PROMISE frames that might have been
created before the RST_STREAM frame is received and processed.
*/
if (transportDirection_ != TransportDirection::UPSTREAM) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on DOWNSTREAM codec");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (egressSettings_.getSetting(SettingsId::ENABLE_PUSH, -1) != 1) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on codec with push disabled");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
VLOG(4) << "parsing PUSH_PROMISE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t promisedStream;
std::unique_ptr<IOBuf> headerBlockFragment;
auto err = http2::parsePushPromise(cursor, curHeader_, promisedStream,
headerBlockFragment);
RETURN_IF_ERROR(err);
RETURN_IF_ERROR(checkNewStream(promisedStream, false /* trailersAllowed */));
err = parseHeadersImpl(cursor, std::move(headerBlockFragment), folly::none,
promisedStream, folly::none);
return err;
}
ErrorCode HTTP2Codec::parsePing(Cursor& cursor) {
VLOG(4) << "parsing PING frame length=" << curHeader_.length;
uint64_t opaqueData = 0;
auto err = http2::parsePing(cursor, curHeader_, opaqueData);
RETURN_IF_ERROR(err);
if (callback_) {
if (curHeader_.flags & http2::ACK) {
callback_->onPingReply(opaqueData);
} else {
callback_->onPingRequest(opaqueData);
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseGoaway(Cursor& cursor) {
VLOG(4) << "parsing GOAWAY frame length=" << curHeader_.length;
uint32_t lastGoodStream = 0;
ErrorCode statusCode = ErrorCode::NO_ERROR;
std::unique_ptr<IOBuf> debugData;
auto err = http2::parseGoaway(cursor, curHeader_, lastGoodStream, statusCode,
debugData);
if (statusCode != ErrorCode::NO_ERROR) {
VLOG(2) << "Goaway error statusCode=" << getErrorCodeString(statusCode)
<< " lastStream=" << lastGoodStream
<< " user-agent=" << userAgent_ << " debugData=" <<
((debugData) ? string((char*)debugData->data(), debugData->length()):
empty_string);
}
RETURN_IF_ERROR(err);
if (lastGoodStream < ingressGoawayAck_) {
ingressGoawayAck_ = lastGoodStream;
// Drain all streams <= lastGoodStream
// and abort streams > lastGoodStream
if (callback_) {
callback_->onGoaway(lastGoodStream, statusCode, std::move(debugData));
}
} else {
LOG(WARNING) << "Received multiple GOAWAY with increasing ack";
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseWindowUpdate(Cursor& cursor) {
VLOG(4) << "parsing WINDOW_UPDATE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t delta = 0;
auto err = http2::parseWindowUpdate(cursor, curHeader_, delta);
RETURN_IF_ERROR(err);
if (delta == 0) {
VLOG(4) << "Invalid 0 length delta for stream=" << curHeader_.stream;
if (curHeader_.stream == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid/0 length delta for streamID=",
curHeader_.stream);
return ErrorCode::PROTOCOL_ERROR;
} else {
// Parsing a zero delta window update should cause a protocol error
// and send a rst stream
goawayErrorMessage_ = folly::to<string>(
"parseWindowUpdate Invalid 0 length");
VLOG(4) << goawayErrorMessage_;
streamError(folly::to<std::string>("streamID=", curHeader_.stream,
" with HTTP2Codec stream error: ",
"window update delta=", delta),
ErrorCode::PROTOCOL_ERROR);
return ErrorCode::PROTOCOL_ERROR;
}
}
// if window exceeds 2^31-1, connection/stream error flow control error
// must be checked in session/txn
deliverCallbackIfAllowed(&HTTPCodec::Callback::onWindowUpdate,
"onWindowUpdate", curHeader_.stream, delta);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificateRequest(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE_REQUEST frame length=" << curHeader_.length;
uint16_t requestId = 0;
std::unique_ptr<IOBuf> authRequest;
auto err = http2::parseCertificateRequest(
cursor, curHeader_, requestId, authRequest);
RETURN_IF_ERROR(err);
if (callback_) {
callback_->onCertificateRequest(requestId, std::move(authRequest));
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificate(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE frame length=" << curHeader_.length;
uint16_t certId = 0;
std::unique_ptr<IOBuf> authData;
auto err = http2::parseCertificate(cursor, curHeader_, certId, authData);
RETURN_IF_ERROR(err);
if (curAuthenticatorBlock_.empty()) {
curCertId_ = certId;
} else if (certId != curCertId_) {
// Received CERTIFICATE frame with different Cert-ID.
return ErrorCode::PROTOCOL_ERROR;
}
curAuthenticatorBlock_.append(std::move(authData));
if (curAuthenticatorBlock_.chainLength() > http2::kMaxAuthenticatorBufSize) {
// Received excessively long authenticator.
return ErrorCode::PROTOCOL_ERROR;
}
if (!(curHeader_.flags & http2::TO_BE_CONTINUED)) {
auto authenticator = curAuthenticatorBlock_.move();
if (callback_) {
callback_->onCertificate(certId, std::move(authenticator));
} else {
curAuthenticatorBlock_.clear();
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) {
if (streamId == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: received streamID=", streamId,
" as invalid new stream for lastStreamID_=", lastStreamID_);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_);
if (parsingDownstreamTrailers_) {
VLOG(4) << "Parsing downstream trailers streamId=" << streamId;
}
if (sessionClosing_ != ClosingState::CLOSED) {
lastStreamID_ = streamId;
}
if (isInitiatedStream(streamId)) {
// this stream should be initiated by us, not by peer
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid new stream received with streamID=", streamId);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
} else {
return ErrorCode::NO_ERROR;
}
}
size_t HTTP2Codec::generateConnectionPreface(folly::IOBufQueue& writeBuf) {
if (transportDirection_ == TransportDirection::UPSTREAM) {
VLOG(4) << "generating connection preface";
writeBuf.append(http2::kConnectionPreface);
return http2::kConnectionPreface.length();
}
return 0;
}
bool HTTP2Codec::onIngressUpgradeMessage(const HTTPMessage& msg) {
if (!HTTPParallelCodec::onIngressUpgradeMessage(msg)) {
return false;
}
if (msg.getHeaders().getNumberOfValues(http2::kProtocolSettingsHeader) != 1) {
VLOG(4) << __func__ << " with no HTTP2-Settings";
return false;
}
const auto& settingsHeader = msg.getHeaders().getSingleOrEmpty(
http2::kProtocolSettingsHeader);
if (settingsHeader.empty()) {
return true;
}
auto decoded = base64url_decode(settingsHeader);
// Must be well formed Base64Url and not too large
if (decoded.empty() || decoded.length() > http2::kMaxFramePayloadLength) {
VLOG(4) << __func__ << " failed to decode HTTP2-Settings";
return false;
}
std::unique_ptr<IOBuf> decodedBuf = IOBuf::wrapBuffer(decoded.data(),
decoded.length());
IOBufQueue settingsQueue{IOBufQueue::cacheChainLength()};
settingsQueue.append(std::move(decodedBuf));
Cursor c(settingsQueue.front());
std::deque<SettingPair> settings;
// downcast is ok because of above length check
http2::FrameHeader frameHeader{
(uint32_t)settingsQueue.chainLength(), 0, http2::FrameType::SETTINGS, 0, 0};
auto err = http2::parseSettings(c, frameHeader, settings);
if (err != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " bad settings frame";
return false;
}
if (handleSettings(settings) != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " handleSettings failed";
return false;
}
return true;
}
void HTTP2Codec::generateHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generatePushPromise(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
StreamID assocStream,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
assocStream,
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generateExHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const HTTPCodec::ExAttributes& exAttributes,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
exAttributes,
eom,
size);
}
void HTTP2Codec::generateHeaderImpl(
folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const folly::Optional<StreamID>& assocStream,
const folly::Optional<HTTPCodec::ExAttributes>& exAttributes,
bool eom,
HTTPHeaderSize* size) {
if (assocStream) {
CHECK(!exAttributes);
VLOG(4) << "generating PUSH_PROMISE for stream=" << stream;
} else if (exAttributes) {
CHECK(!assocStream);
VLOG(4) << "generating ExHEADERS for stream=" << stream
<< " with control stream=" << exAttributes->controlStream
<< " unidirectional=" << exAttributes->unidirectional;
} else {
VLOG(4) << "generating HEADERS for stream=" << stream;
}
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing HEADERS/PROMISE for stream=" << stream <<
" ingressGoawayAck_=" << ingressGoawayAck_;
if (size) {
size->uncompressed = 0;
size->compressed = 0;
}
return;
}
if (msg.isRequest()) {
DCHECK(transportDirection_ == TransportDirection::UPSTREAM ||
assocStream || exAttributes);
if (msg.isEgressWebsocketUpgrade()) {
upgradedStreams_.insert(stream);
}
} else {
DCHECK(transportDirection_ == TransportDirection::DOWNSTREAM ||
exAttributes);
}
std::vector<std::string> temps;
auto allHeaders = CodecUtil::prepareMessageForCompression(msg, temps);
auto out = encodeHeaders(msg.getHeaders(), allHeaders, size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto res = msg.getHTTP2Priority();
auto remainingFrameSize = maxFrameSize;
if (res) {
pri = http2::PriorityUpdate{std::get<0>(*res), std::get<1>(*res),
std::get<2>(*res)};
DCHECK_GE(remainingFrameSize, http2::kFramePrioritySize)
<< "no enough space for priority? frameHeadroom=" << remainingFrameSize;
remainingFrameSize -= http2::kFramePrioritySize;
}
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
if (assocStream) {
DCHECK_EQ(transportDirection_, TransportDirection::DOWNSTREAM);
DCHECK(!eom);
generateHeaderCallbackWrapper(stream, http2::FrameType::PUSH_PROMISE,
http2::writePushPromise(writeBuf,
*assocStream,
stream,
std::move(chunk),
http2::kNoPadding,
endHeaders));
} else if (exAttributes) {
generateHeaderCallbackWrapper(
stream,
http2::FrameType::EX_HEADERS,
http2::writeExHeaders(writeBuf,
std::move(chunk),
stream,
*exAttributes,
pri,
http2::kNoPadding,
eom,
endHeaders));
} else {
generateHeaderCallbackWrapper(stream, http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
eom,
endHeaders));
}
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
}
void HTTP2Codec::generateContinuation(folly::IOBufQueue& writeBuf,
folly::IOBufQueue& queue,
StreamID stream,
size_t maxFrameSize) {
bool endHeaders = false;
while (!endHeaders) {
auto chunk = queue.split(std::min(maxFrameSize, queue.chainLength()));
endHeaders = (queue.chainLength() == 0);
VLOG(4) << "generating CONTINUATION for stream=" << stream;
generateHeaderCallbackWrapper(
stream,
http2::FrameType::CONTINUATION,
http2::writeContinuation(
writeBuf, stream, endHeaders, std::move(chunk)));
}
}
std::unique_ptr<folly::IOBuf> HTTP2Codec::encodeHeaders(
const HTTPHeaders& headers,
std::vector<compress::Header>& allHeaders,
HTTPHeaderSize* size) {
headerCodec_.setEncodeHeadroom(http2::kFrameHeaderSize +
http2::kFrameHeadersBaseMaxSize);
auto out = headerCodec_.encode(allHeaders);
if (size) {
*size = headerCodec_.getEncodedSize();
}
if (headerCodec_.getEncodedSize().uncompressed >
ingressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE,
std::numeric_limits<uint32_t>::max())) {
// The remote side told us they don't want headers this large...
// but this function has no mechanism to fail
string serializedHeaders;
headers.forEach(
[&serializedHeaders] (const string& name, const string& value) {
serializedHeaders = folly::to<string>(serializedHeaders, "\\n", name,
":", value);
});
LOG(ERROR) << "generating HEADERS frame larger than peer maximum nHeaders="
<< headers.size() << " all headers="
<< serializedHeaders;
}
return out;
}
size_t HTTP2Codec::generateHeaderCallbackWrapper(StreamID stream,
http2::FrameType type,
size_t length) {
if (callback_) {
callback_->onGenerateFrameHeader(stream,
static_cast<uint8_t>(type),
length);
}
return length;
}
size_t HTTP2Codec::generateBody(folly::IOBufQueue& writeBuf,
StreamID stream,
std::unique_ptr<folly::IOBuf> chain,
folly::Optional<uint8_t> padding,
bool eom) {
// todo: generate random padding for everything?
size_t written = 0;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing DATA for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(chain));
size_t maxFrameSize = maxSendFrameSize();
while (queue.chainLength() > maxFrameSize) {
auto chunk = queue.split(maxFrameSize);
written += generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
std::move(chunk),
stream,
padding,
false,
reuseIOBufHeadroomForData_));
}
return written + generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
queue.move(),
stream,
padding,
eom,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateChunkHeader(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/,
size_t /*length*/) {
// HTTP/2 has no chunk headers
return 0;
}
size_t HTTP2Codec::generateChunkTerminator(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/) {
// HTTP/2 has no chunk terminators
return 0;
}
size_t HTTP2Codec::generateTrailers(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPHeaders& trailers) {
std::vector<compress::Header> allHeaders;
CodecUtil::appendHeaders(trailers, allHeaders, HTTP_HEADER_NONE);
HTTPHeaderSize size;
auto out = encodeHeaders(trailers, allHeaders, &size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto remainingFrameSize = maxFrameSize;
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
generateHeaderCallbackWrapper(stream,
http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
true /*eom*/,
endHeaders));
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
return size.compressed;
}
size_t HTTP2Codec::generateEOM(folly::IOBufQueue& writeBuf,
StreamID stream) {
VLOG(4) << "sending EOM for stream=" << stream;
upgradedStreams_.erase(stream);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed EOM for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
nullptr,
stream,
http2::kNoPadding,
true,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateRstStream(folly::IOBufQueue& writeBuf,
StreamID stream,
ErrorCode statusCode) {
VLOG(4) << "sending RST_STREAM for stream=" << stream
<< " with code=" << getErrorCodeString(statusCode);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed RST_STREAM for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
// Suppress any EOM callback for the current frame.
if (stream == curHeader_.stream) {
curHeader_.flags &= ~http2::END_STREAM;
pendingEndStreamHandling_ = false;
ingressWebsocketUpgrade_ = false;
}
upgradedStreams_.erase(stream);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending RST_STREAM with code=" << getErrorCodeString(statusCode)
<< " for stream=" << stream << " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToReset(statusCode);
return generateHeaderCallbackWrapper(stream, http2::FrameType::RST_STREAM,
http2::writeRstStream(writeBuf, stream, code));
}
size_t HTTP2Codec::generateGoaway(folly::IOBufQueue& writeBuf,
StreamID lastStream,
ErrorCode statusCode,
std::unique_ptr<folly::IOBuf> debugData) {
DCHECK_LE(lastStream, egressGoawayAck_) << "Cannot increase last good stream";
egressGoawayAck_ = lastStream;
if (sessionClosing_ == ClosingState::CLOSED) {
VLOG(4) << "Not sending GOAWAY for closed session";
return 0;
}
switch (sessionClosing_) {
case ClosingState::OPEN:
case ClosingState::OPEN_WITH_GRACEFUL_DRAIN_ENABLED:
if (lastStream == std::numeric_limits<int32_t>::max() &&
statusCode == ErrorCode::NO_ERROR) {
sessionClosing_ = ClosingState::FIRST_GOAWAY_SENT;
} else {
// The user of this codec decided not to do the double goaway
// drain, or this is not a graceful shutdown
sessionClosing_ = ClosingState::CLOSED;
}
break;
case ClosingState::FIRST_GOAWAY_SENT:
sessionClosing_ = ClosingState::CLOSED;
break;
case ClosingState::CLOSING:
case ClosingState::CLOSED:
LOG(FATAL) << "unreachable";
}
VLOG(4) << "Sending GOAWAY with last acknowledged stream="
<< lastStream << " with code=" << getErrorCodeString(statusCode);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending GOAWAY with last acknowledged stream=" << lastStream
<< " with code=" << getErrorCodeString(statusCode)
<< " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToGoaway(statusCode);
return generateHeaderCallbackWrapper(
0,
http2::FrameType::GOAWAY,
http2::writeGoaway(writeBuf,
lastStream,
code,
std::move(debugData)));
}
size_t HTTP2Codec::generatePingRequest(folly::IOBufQueue& writeBuf) {
// should probably let the caller specify when integrating with session
// we know HTTPSession sets up events to track ping latency
uint64_t opaqueData = folly::Random::rand64();
VLOG(4) << "Generating ping request with opaqueData=" << opaqueData;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, opaqueData, false /* no ack */));
}
size_t HTTP2Codec::generatePingReply(folly::IOBufQueue& writeBuf,
uint64_t uniqueID) {
VLOG(4) << "Generating ping reply with opaqueData=" << uniqueID;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, uniqueID, true /* ack */));
}
size_t HTTP2Codec::generateSettings(folly::IOBufQueue& writeBuf) {
std::deque<SettingPair> settings;
for (auto& setting: egressSettings_.getAllSettings()) {
switch (setting.id) {
case SettingsId::HEADER_TABLE_SIZE:
if (pendingTableMaxSize_) {
LOG(ERROR) << "Can't have more than one settings in flight, skipping";
continue;
} else {
pendingTableMaxSize_ = setting.value;
}
break;
case SettingsId::ENABLE_PUSH:
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
// HTTP/2 spec says downstream must not send this flag
// HTTP2Codec uses it to determine if push features are enabled
continue;
} else {
CHECK(setting.value == 0 || setting.value == 1);
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
case SettingsId::INITIAL_WINDOW_SIZE:
case SettingsId::MAX_FRAME_SIZE:
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
headerCodec_.setMaxUncompressed(setting.value);
break;
case SettingsId::ENABLE_EX_HEADERS:
CHECK(setting.value == 0 || setting.value == 1);
if (setting.value == 0) {
continue; // just skip the experimental setting if disabled
} else {
VLOG(4) << "generating ENABLE_EX_HEADERS=" << setting.value;
}
break;
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.value == 0) {
continue;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
default:
LOG(ERROR) << "ignore unknown settingsId="
<< std::underlying_type<SettingsId>::type(setting.id)
<< " value=" << setting.value;
continue;
}
settings.push_back(SettingPair(setting.id, setting.value));
}
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating " << (unsigned)settings.size() << " settings";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettings(writeBuf, settings));
}
void HTTP2Codec::requestUpgrade(HTTPMessage& request) {
static folly::ThreadLocalPtr<HTTP2Codec> defaultCodec;
if (!defaultCodec.get()) {
defaultCodec.reset(new HTTP2Codec(TransportDirection::UPSTREAM));
}
auto& headers = request.getHeaders();
headers.set(HTTP_HEADER_UPGRADE, http2::kProtocolCleartextString);
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION, "Upgrade", false)) {
headers.add(HTTP_HEADER_CONNECTION, "Upgrade");
}
IOBufQueue writeBuf{IOBufQueue::cacheChainLength()};
defaultCodec->generateSettings(writeBuf);
// fake an ack since defaultCodec gets reused
defaultCodec->handleSettingsAck();
writeBuf.trimStart(http2::kFrameHeaderSize);
auto buf = writeBuf.move();
buf->coalesce();
headers.set(http2::kProtocolSettingsHeader,
base64url_encode(folly::ByteRange(buf->data(), buf->length())));
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(),
false)) {
headers.add(HTTP_HEADER_CONNECTION, http2::kProtocolSettingsHeader);
}
}
size_t HTTP2Codec::generateSettingsAck(folly::IOBufQueue& writeBuf) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating settings ack";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettingsAck(writeBuf));
}
size_t HTTP2Codec::generateWindowUpdate(folly::IOBufQueue& writeBuf,
StreamID stream,
uint32_t delta) {
VLOG(4) << "generating window update for stream=" << stream
<< ": Processed " << delta << " bytes";
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed WINDOW_UPDATE for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(stream, http2::FrameType::WINDOW_UPDATE,
http2::writeWindowUpdate(writeBuf, stream, delta));
}
size_t HTTP2Codec::generatePriority(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage::HTTPPriority& pri) {
VLOG(4) << "generating priority for stream=" << stream;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed PRIORITY for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::PRIORITY,
http2::writePriority(writeBuf, stream,
{std::get<0>(pri),
std::get<1>(pri),
std::get<2>(pri)}));
}
size_t HTTP2Codec::generateCertificateRequest(
folly::IOBufQueue& writeBuf,
uint16_t requestId,
std::unique_ptr<folly::IOBuf> certificateRequestData) {
VLOG(4) << "generating CERTIFICATE_REQUEST with Request-ID=" << requestId;
return http2::writeCertificateRequest(
writeBuf, requestId, std::move(certificateRequestData));
}
size_t HTTP2Codec::generateCertificate(folly::IOBufQueue& writeBuf,
uint16_t certId,
std::unique_ptr<folly::IOBuf> certData) {
size_t written = 0;
VLOG(4) << "sending CERTIFICATE with Cert-ID=" << certId << "for stream=0";
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(certData));
// The maximum size of an autenticator fragment, combined with the Cert-ID can
// not exceed the maximal allowable size of a sent frame.
size_t maxChunkSize = maxSendFrameSize() - sizeof(certId);
while (queue.chainLength() > maxChunkSize) {
auto chunk = queue.splitAtMost(maxChunkSize);
written +=
http2::writeCertificate(writeBuf, certId, std::move(chunk), true);
}
return written +
http2::writeCertificate(writeBuf, certId, queue.move(), false);
}
bool HTTP2Codec::checkConnectionError(ErrorCode err, const folly::IOBuf* buf) {
if (err != ErrorCode::NO_ERROR) {
LOG(ERROR) << "Connection error " << getErrorCodeString(err)
<< " with ingress=";
VLOG(3) << IOBufPrinter::printHexFolly(buf, true);
if (callback_) {
std::string errorDescription = goawayErrorMessage_.empty() ?
"Connection error" : goawayErrorMessage_;
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
errorDescription);
ex.setCodecStatusCode(err);
callback_->onError(0, ex, false);
}
return true;
}
return false;
}
void HTTP2Codec::streamError(const std::string& msg, ErrorCode code,
bool newTxn) {
HTTPException error(HTTPException::Direction::INGRESS_AND_EGRESS,
msg);
error.setCodecStatusCode(code);
if (callback_) {
callback_->onError(curHeader_.stream, error, newTxn);
}
}
HTTPCodec::StreamID
HTTP2Codec::mapPriorityToDependency(uint8_t priority) const {
// If the priority is out of the maximum index of virtual nodes array, we
// return the lowest level virtual node as a punishment of not setting
// priority correctly.
return virtualPriorityNodes_.empty()
? 0
: virtualPriorityNodes_[
std::min(priority, uint8_t(virtualPriorityNodes_.size() - 1))];
}
bool HTTP2Codec::parsingTrailers() const {
// HEADERS frame is used for request/response headers and trailers.
// Per spec, specific role of HEADERS frame is determined by it's postion
// within the stream. We don't keep full stream state in this codec,
// thus using heuristics to distinguish between headers/trailers.
// For DOWNSTREAM case, request headers HEADERS frame would be creating
// new stream, thus HEADERS on existing stream ID are considered trailers
// (see checkNewStream).
// For UPSTREAM case, response headers are required to have status code,
// thus if no status code we consider that trailers.
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::CONTINUATION) {
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
return parsingDownstreamTrailers_;
} else {
return !decodeInfo_.hasStatus();
}
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-388/cpp/good_599_0 |
crossvul-cpp_data_bad_599_0 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/HTTP2Constants.h>
#include <proxygen/lib/http/codec/CodecUtil.h>
#include <proxygen/lib/utils/Logging.h>
#include <proxygen/lib/utils/Base64.h>
#include <folly/Conv.h>
#include <folly/Random.h>
#include <folly/ThreadLocal.h>
#include <folly/io/Cursor.h>
#include <folly/tracing/ScopedTraceSection.h>
#include <type_traits>
using namespace proxygen::compress;
using namespace folly::io;
using namespace folly;
using std::string;
namespace {
std::string base64url_encode(ByteRange range) {
return proxygen::Base64::urlEncode(range);
}
std::string base64url_decode(const std::string& str) {
return proxygen::Base64::urlDecode(str);
}
}
namespace proxygen {
HTTP2Codec::HTTP2Codec(TransportDirection direction)
: HTTPParallelCodec(direction),
headerCodec_(direction),
frameState_(direction == TransportDirection::DOWNSTREAM
? FrameState::UPSTREAM_CONNECTION_PREFACE
: FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
const auto maxHeaderListSize = egressSettings_.getSetting(
SettingsId::MAX_HEADER_LIST_SIZE);
if (maxHeaderListSize) {
headerCodec_.setMaxUncompressed(maxHeaderListSize->value);
}
VLOG(4) << "creating " << getTransportDirectionString(direction)
<< " HTTP/2 codec";
}
HTTP2Codec::~HTTP2Codec() {}
// HTTPCodec API
size_t HTTP2Codec::onIngress(const folly::IOBuf& buf) {
// TODO: ensure only 1 parse at a time on stack.
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - onIngress");
Cursor cursor(&buf);
size_t parsed = 0;
ErrorCode connError = ErrorCode::NO_ERROR;
for (auto bufLen = cursor.totalLength();
connError == ErrorCode::NO_ERROR;
bufLen = cursor.totalLength()) {
if (frameState_ == FrameState::UPSTREAM_CONNECTION_PREFACE) {
if (bufLen >= http2::kConnectionPreface.length()) {
auto test = cursor.readFixedString(http2::kConnectionPreface.length());
parsed += http2::kConnectionPreface.length();
if (test != http2::kConnectionPreface) {
goawayErrorMessage_ = "missing connection preface";
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
} else if (frameState_ == FrameState::FRAME_HEADER ||
frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE) {
// Waiting to parse the common frame header
if (bufLen >= http2::kFrameHeaderSize) {
connError = parseFrameHeader(cursor, curHeader_);
parsed += http2::kFrameHeaderSize;
if (frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE &&
curHeader_.type != http2::FrameType::SETTINGS) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: got invalid connection preface frame type=",
getFrameTypeString(curHeader_.type), "(", curHeader_.type, ")",
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
connError = ErrorCode::PROTOCOL_ERROR;
}
if (curHeader_.length > maxRecvFrameSize()) {
VLOG(4) << "Excessively large frame len=" << curHeader_.length;
connError = ErrorCode::FRAME_SIZE_ERROR;
}
if (callback_) {
callback_->onFrameHeader(
curHeader_.stream,
curHeader_.flags,
curHeader_.length,
static_cast<uint8_t>(curHeader_.type));
}
frameState_ = (curHeader_.type == http2::FrameType::DATA) ?
FrameState::DATA_FRAME_DATA : FrameState::FRAME_DATA;
pendingDataFrameBytes_ = curHeader_.length;
pendingDataFramePaddingBytes_ = 0;
#ifndef NDEBUG
receivedFrameCount_++;
#endif
} else {
break;
}
} else if (frameState_ == FrameState::DATA_FRAME_DATA && bufLen > 0 &&
(bufLen < curHeader_.length ||
pendingDataFrameBytes_ < curHeader_.length)) {
// FrameState::DATA_FRAME_DATA with partial data only
size_t dataParsed = 0;
connError = parseDataFrameData(cursor, bufLen, dataParsed);
if (dataParsed == 0 && pendingDataFrameBytes_ > 0) {
// We received only the padding byte, we will wait for more
break;
} else {
parsed += dataParsed;
if (pendingDataFrameBytes_ == 0) {
frameState_ = FrameState::FRAME_HEADER;
}
}
} else { // FrameState::FRAME_DATA
// or FrameState::DATA_FRAME_DATA with all data available
// Already parsed the common frame header
const auto frameLen = curHeader_.length;
if (bufLen >= frameLen) {
connError = parseFrame(cursor);
parsed += curHeader_.length;
frameState_ = FrameState::FRAME_HEADER;
} else {
break;
}
}
}
checkConnectionError(connError, &buf);
return parsed;
}
ErrorCode HTTP2Codec::parseFrame(folly::io::Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseFrame");
if (expectedContinuationStream_ != 0 &&
(curHeader_.type != http2::FrameType::CONTINUATION ||
expectedContinuationStream_ != curHeader_.stream)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: while expected CONTINUATION with stream=",
expectedContinuationStream_, ", received streamID=", curHeader_.stream,
" of type=", getFrameTypeString(curHeader_.type));
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (expectedContinuationStream_ == 0 &&
curHeader_.type == http2::FrameType::CONTINUATION) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: unexpected CONTINUATION received with streamID=",
curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (frameAffectsCompression(curHeader_.type) &&
curHeaderBlock_.chainLength() + curHeader_.length >
egressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE, 0)) {
// this may be off by up to the padding length (max 255), but
// these numbers are already so generous, and we're comparing the
// max-uncompressed to the actual compressed size. Let's fail
// before buffering.
// TODO(t6513634): it would be nicer to stream-process this header
// block to keep the connection state consistent without consuming
// memory, and fail just the request per the HTTP/2 spec (section
// 10.3)
goawayErrorMessage_ = folly::to<string>(
"Failing connection due to excessively large headers");
LOG(ERROR) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
expectedContinuationStream_ =
(frameAffectsCompression(curHeader_.type) &&
!(curHeader_.flags & http2::END_HEADERS)) ? curHeader_.stream : 0;
switch (curHeader_.type) {
case http2::FrameType::DATA:
return parseAllData(cursor);
case http2::FrameType::HEADERS:
return parseHeaders(cursor);
case http2::FrameType::PRIORITY:
return parsePriority(cursor);
case http2::FrameType::RST_STREAM:
return parseRstStream(cursor);
case http2::FrameType::SETTINGS:
return parseSettings(cursor);
case http2::FrameType::PUSH_PROMISE:
return parsePushPromise(cursor);
case http2::FrameType::EX_HEADERS:
if (ingressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) {
return parseExHeaders(cursor);
} else {
VLOG(2) << "EX_HEADERS not enabled, ignoring the frame";
break;
}
case http2::FrameType::PING:
return parsePing(cursor);
case http2::FrameType::GOAWAY:
return parseGoaway(cursor);
case http2::FrameType::WINDOW_UPDATE:
return parseWindowUpdate(cursor);
case http2::FrameType::CONTINUATION:
return parseContinuation(cursor);
case http2::FrameType::ALTSVC:
// fall through, unimplemented
break;
case http2::FrameType::CERTIFICATE_REQUEST:
return parseCertificateRequest(cursor);
case http2::FrameType::CERTIFICATE:
return parseCertificate(cursor);
default:
// Implementations MUST ignore and discard any frame that has a
// type that is unknown
break;
}
// Landing here means unknown, unimplemented or ignored frame.
VLOG(2) << "Skipping frame (type=" << (uint8_t)curHeader_.type << ")";
cursor.skip(curHeader_.length);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::handleEndStream() {
if (curHeader_.type != http2::FrameType::HEADERS &&
curHeader_.type != http2::FrameType::EX_HEADERS &&
curHeader_.type != http2::FrameType::CONTINUATION &&
curHeader_.type != http2::FrameType::DATA) {
return ErrorCode::NO_ERROR;
}
// do we need to handle case where this stream has already aborted via
// another callback (onHeadersComplete/onBody)?
pendingEndStreamHandling_ |= (curHeader_.flags & http2::END_STREAM);
// with a websocket upgrade, we need to send message complete cb to
// mirror h1x codec's behavior. when the stream closes, we need to
// send another callback to clean up the stream's resources.
if (ingressWebsocketUpgrade_) {
ingressWebsocketUpgrade_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, true);
}
if (pendingEndStreamHandling_ && expectedContinuationStream_ == 0) {
pendingEndStreamHandling_ = false;
deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete,
"onMessageComplete", curHeader_.stream, false);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseAllData(Cursor& cursor) {
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing all frame DATA bytes for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto ret = http2::parseData(cursor, curHeader_, outData, padding);
RETURN_IF_ERROR(ret);
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return handleEndStream();
}
ErrorCode HTTP2Codec::parseDataFrameData(Cursor& cursor,
size_t bufLen,
size_t& parsed) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseDataFrameData");
if (bufLen == 0) {
VLOG(10) << "No data to parse";
return ErrorCode::NO_ERROR;
}
std::unique_ptr<IOBuf> outData;
uint16_t padding = 0;
VLOG(10) << "parsing DATA frame data for stream=" << curHeader_.stream <<
" frame data length=" << curHeader_.length << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
// Parse the padding information only the first time
if (pendingDataFrameBytes_ == curHeader_.length &&
pendingDataFramePaddingBytes_ == 0) {
if (frameHasPadding(curHeader_) && bufLen == 1) {
// We need to wait for more bytes otherwise we won't be able to pass
// the correct padding to the first onBody call
return ErrorCode::NO_ERROR;
}
const auto ret = http2::parseDataBegin(cursor, curHeader_, parsed, padding);
RETURN_IF_ERROR(ret);
if (padding > 0) {
pendingDataFramePaddingBytes_ = padding - 1;
pendingDataFrameBytes_--;
bufLen--;
parsed++;
}
VLOG(10) << "out padding=" << padding << " pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
if (bufLen > 0) {
// Check if we have application data to parse
if (pendingDataFrameBytes_ > pendingDataFramePaddingBytes_) {
const size_t pendingAppData =
pendingDataFrameBytes_ - pendingDataFramePaddingBytes_;
const size_t toClone = std::min(pendingAppData, bufLen);
cursor.clone(outData, toClone);
bufLen -= toClone;
pendingDataFrameBytes_ -= toClone;
parsed += toClone;
VLOG(10) << "parsed some app data, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
// Check if we have padding bytes to parse
if (bufLen > 0 && pendingDataFramePaddingBytes_ > 0) {
size_t toSkip = 0;
auto ret = http2::parseDataEnd(cursor, bufLen,
pendingDataFramePaddingBytes_, toSkip);
RETURN_IF_ERROR(ret);
pendingDataFrameBytes_ -= toSkip;
pendingDataFramePaddingBytes_ -= toSkip;
parsed += toSkip;
VLOG(10) << "parsed some padding, pendingDataFrameBytes_=" <<
pendingDataFrameBytes_ << " pendingDataFramePaddingBytes_=" <<
pendingDataFramePaddingBytes_ << " bufLen=" << bufLen <<
" parsed=" << parsed;
}
}
if (callback_ && (padding > 0 || (outData && !outData->empty()))) {
if (!outData) {
outData = std::make_unique<IOBuf>();
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, "onBody",
curHeader_.stream, std::move(outData), padding);
}
return (pendingDataFrameBytes_ > 0) ? ErrorCode::NO_ERROR : handleEndStream();
}
ErrorCode HTTP2Codec::parseHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseHeaders");
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing HEADERS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseHeaders(cursor, curHeader_, priority, headerBuf);
RETURN_IF_ERROR(err);
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, true /* trailersAllowed */));
}
err = parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
folly::none);
return err;
}
ErrorCode HTTP2Codec::parseExHeaders(Cursor& cursor) {
FOLLY_SCOPED_TRACE_SECTION("HTTP2Codec - parseExHeaders");
HTTPCodec::ExAttributes exAttributes;
folly::Optional<http2::PriorityUpdate> priority;
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing ExHEADERS frame for stream=" << curHeader_.stream
<< " length=" << curHeader_.length;
auto err = http2::parseExHeaders(
cursor, curHeader_, exAttributes, priority, headerBuf);
RETURN_IF_ERROR(err);
if (isRequest(curHeader_.stream)) {
RETURN_IF_ERROR(
checkNewStream(curHeader_.stream, false /* trailersAllowed */));
}
return parseHeadersImpl(cursor, std::move(headerBuf), priority, folly::none,
exAttributes);
}
ErrorCode HTTP2Codec::parseContinuation(Cursor& cursor) {
std::unique_ptr<IOBuf> headerBuf;
VLOG(4) << "parsing CONTINUATION frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
auto err = http2::parseContinuation(cursor, curHeader_, headerBuf);
RETURN_IF_ERROR(err);
err = parseHeadersImpl(cursor, std::move(headerBuf),
folly::none, folly::none, folly::none);
return err;
}
ErrorCode HTTP2Codec::parseHeadersImpl(
Cursor& /*cursor*/,
std::unique_ptr<IOBuf> headerBuf,
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes) {
curHeaderBlock_.append(std::move(headerBuf));
std::unique_ptr<HTTPMessage> msg;
if (curHeader_.flags & http2::END_HEADERS) {
auto errorCode =
parseHeadersDecodeFrames(priority, promisedStream, exAttributes, msg);
if (errorCode.hasValue()) {
return errorCode.value();
}
}
// if we're not parsing CONTINUATION, then it's start of new header block
if (curHeader_.type != http2::FrameType::CONTINUATION) {
headerBlockFrameType_ = curHeader_.type;
}
// Report back what we've parsed
if (callback_) {
auto concurError = parseHeadersCheckConcurrentStreams(priority);
if (concurError.hasValue()) {
return concurError.value();
}
uint32_t headersCompleteStream = curHeader_.stream;
bool trailers = parsingTrailers();
bool allHeaderFramesReceived =
(curHeader_.flags & http2::END_HEADERS) &&
(headerBlockFrameType_ == http2::FrameType::HEADERS);
if (allHeaderFramesReceived && !trailers) {
// Only deliver onMessageBegin once per stream.
// For responses with CONTINUATION, this will be delayed until
// the frame with the END_HEADERS flag set.
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageBegin,
"onMessageBegin",
curHeader_.stream,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::EX_HEADERS) {
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onExMessageBegin,
"onExMessageBegin",
curHeader_.stream,
exAttributes->controlStream,
exAttributes->unidirectional,
msg.get())) {
return handleEndStream();
}
} else if (curHeader_.type == http2::FrameType::PUSH_PROMISE) {
DCHECK(promisedStream);
if (!deliverCallbackIfAllowed(&HTTPCodec::Callback::onPushMessageBegin,
"onPushMessageBegin", *promisedStream,
curHeader_.stream, msg.get())) {
return handleEndStream();
}
headersCompleteStream = *promisedStream;
}
if (curHeader_.flags & http2::END_HEADERS && msg) {
if (!(curHeader_.flags & http2::END_STREAM)) {
// If it there are DATA frames coming, consider it chunked
msg->setIsChunked(true);
}
if (trailers) {
VLOG(4) << "Trailers complete for streamId=" << headersCompleteStream
<< " direction=" << transportDirection_;
auto trailerHeaders =
std::make_unique<HTTPHeaders>(msg->extractHeaders());
msg.reset();
callback_->onTrailersComplete(headersCompleteStream,
std::move(trailerHeaders));
} else {
callback_->onHeadersComplete(headersCompleteStream, std::move(msg));
}
}
return handleEndStream();
}
return ErrorCode::NO_ERROR;
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersDecodeFrames(
const folly::Optional<http2::PriorityUpdate>& priority,
const folly::Optional<uint32_t>& promisedStream,
const folly::Optional<ExAttributes>& exAttributes,
std::unique_ptr<HTTPMessage>& msg) {
// decompress headers
Cursor headerCursor(curHeaderBlock_.front());
bool isReq = false;
if (promisedStream) {
isReq = true;
} else if (exAttributes) {
isReq = isRequest(curHeader_.stream);
} else {
isReq = transportDirection_ == TransportDirection::DOWNSTREAM;
}
decodeInfo_.init(isReq, parsingDownstreamTrailers_);
if (priority) {
if (curHeader_.stream == priority->streamDependency) {
streamError(folly::to<string>("Circular dependency for txn=",
curHeader_.stream),
ErrorCode::PROTOCOL_ERROR,
curHeader_.type == http2::FrameType::HEADERS);
return ErrorCode::NO_ERROR;
}
decodeInfo_.msg->setHTTP2Priority(
std::make_tuple(priority->streamDependency,
priority->exclusive,
priority->weight));
}
headerCodec_.decodeStreaming(
headerCursor, curHeaderBlock_.chainLength(), this);
msg = std::move(decodeInfo_.msg);
// Saving this in case we need to log it on error
auto g = folly::makeGuard([this] { curHeaderBlock_.move(); });
// Check decoding error
if (decodeInfo_.decodeError != HPACK::DecodeError::NONE) {
static const std::string decodeErrorMessage =
"Failed decoding header block for stream=";
// Avoid logging header blocks that have failed decoding due to being
// excessively large.
if (decodeInfo_.decodeError != HPACK::DecodeError::HEADERS_TOO_LARGE) {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream
<< " header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
} else {
LOG(ERROR) << decodeErrorMessage << curHeader_.stream;
}
if (msg) {
// print the partial message
msg->dumpMessage(3);
}
return ErrorCode::COMPRESSION_ERROR;
}
// Check parsing error
if (decodeInfo_.parsingError != "") {
LOG(ERROR) << "Failed parsing header list for stream=" << curHeader_.stream
<< ", error=" << decodeInfo_.parsingError << ", header block=";
VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true);
HTTPException err(HTTPException::Direction::INGRESS,
folly::to<std::string>("HTTP2Codec stream error: ",
"stream=",
curHeader_.stream,
" status=",
400,
" error: ",
decodeInfo_.parsingError));
err.setHttpStatusCode(400);
callback_->onError(curHeader_.stream, err, true);
return ErrorCode::NO_ERROR;
}
return folly::Optional<ErrorCode>();
}
folly::Optional<ErrorCode> HTTP2Codec::parseHeadersCheckConcurrentStreams(
const folly::Optional<http2::PriorityUpdate>& priority) {
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::EX_HEADERS) {
if (curHeader_.flags & http2::PRIORITY) {
DCHECK(priority);
// callback_->onPriority(priority.get());
}
// callback checks total number of streams is smaller than settings max
if (callback_->numIncomingStreams() >=
egressSettings_.getSetting(SettingsId::MAX_CONCURRENT_STREAMS,
std::numeric_limits<int32_t>::max())) {
streamError(folly::to<string>("Exceeded max_concurrent_streams"),
ErrorCode::REFUSED_STREAM, true);
return ErrorCode::NO_ERROR;
}
}
return folly::Optional<ErrorCode>();
}
void HTTP2Codec::onHeader(const folly::fbstring& name,
const folly::fbstring& value) {
if (decodeInfo_.onHeader(name, value)) {
if (name == "user-agent" && userAgent_.empty()) {
userAgent_ = value.toStdString();
}
} else {
VLOG(4) << "dir=" << uint32_t(transportDirection_) <<
decodeInfo_.parsingError << " codec=" << headerCodec_;
}
}
void HTTP2Codec::onHeadersComplete(HTTPHeaderSize decodedSize,
bool /*acknowledge*/) {
decodeInfo_.onHeadersComplete(decodedSize);
decodeInfo_.msg->setAdvancedProtocolString(http2::kProtocolString);
HTTPMessage* msg = decodeInfo_.msg.get();
HTTPRequestVerifier& verifier = decodeInfo_.verifier;
if ((transportDirection_ == TransportDirection::DOWNSTREAM) &&
verifier.hasUpgradeProtocol() &&
(*msg->getUpgradeProtocol() == headers::kWebsocketString) &&
msg->getMethod() == HTTPMethod::CONNECT) {
msg->setIngressWebsocketUpgrade();
ingressWebsocketUpgrade_ = true;
} else {
auto it = upgradedStreams_.find(curHeader_.stream);
if (it != upgradedStreams_.end()) {
upgradedStreams_.erase(curHeader_.stream);
// a websocket upgrade was sent on this stream.
if (msg->getStatusCode() != 200) {
decodeInfo_.parsingError =
folly::to<string>("Invalid response code to a websocket upgrade: ",
msg->getStatusCode());
return;
}
msg->setIngressWebsocketUpgrade();
}
}
}
void HTTP2Codec::onDecodeError(HPACK::DecodeError decodeError) {
decodeInfo_.decodeError = decodeError;
}
ErrorCode HTTP2Codec::parsePriority(Cursor& cursor) {
VLOG(4) << "parsing PRIORITY frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
http2::PriorityUpdate pri;
auto err = http2::parsePriority(cursor, curHeader_, pri);
RETURN_IF_ERROR(err);
if (curHeader_.stream == pri.streamDependency) {
streamError(folly::to<string>("Circular dependency for txn=",
curHeader_.stream),
ErrorCode::PROTOCOL_ERROR, false);
return ErrorCode::NO_ERROR;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onPriority, "onPriority",
curHeader_.stream,
std::make_tuple(pri.streamDependency,
pri.exclusive,
pri.weight));
return ErrorCode::NO_ERROR;
}
size_t HTTP2Codec::addPriorityNodes(
PriorityQueue& queue,
folly::IOBufQueue& writeBuf,
uint8_t maxLevel) {
HTTPCodec::StreamID parent = 0;
size_t bytes = 0;
while (maxLevel--) {
auto id = createStream();
virtualPriorityNodes_.push_back(id);
queue.addPriorityNode(id, parent);
bytes += generatePriority(writeBuf, id, std::make_tuple(parent, false, 0));
parent = id;
}
return bytes;
}
ErrorCode HTTP2Codec::parseRstStream(Cursor& cursor) {
// rst for stream in idle state - protocol error
VLOG(4) << "parsing RST_STREAM frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
upgradedStreams_.erase(curHeader_.stream);
ErrorCode statusCode = ErrorCode::NO_ERROR;
auto err = http2::parseRstStream(cursor, curHeader_, statusCode);
RETURN_IF_ERROR(err);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: RST_STREAM with code=", getErrorCodeString(statusCode),
" for streamID=", curHeader_.stream, " user-agent=", userAgent_);
VLOG(2) << goawayErrorMessage_;
}
deliverCallbackIfAllowed(&HTTPCodec::Callback::onAbort, "onAbort",
curHeader_.stream, statusCode);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseSettings(Cursor& cursor) {
VLOG(4) << "parsing SETTINGS frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
std::deque<SettingPair> settings;
auto err = http2::parseSettings(cursor, curHeader_, settings);
RETURN_IF_ERROR(err);
if (curHeader_.flags & http2::ACK) {
handleSettingsAck();
return ErrorCode::NO_ERROR;
}
return handleSettings(settings);
}
void HTTP2Codec::handleSettingsAck() {
if (pendingTableMaxSize_) {
headerCodec_.setDecoderHeaderTableMaxSize(*pendingTableMaxSize_);
pendingTableMaxSize_ = folly::none;
}
if (callback_) {
callback_->onSettingsAck();
}
}
ErrorCode HTTP2Codec::handleSettings(const std::deque<SettingPair>& settings) {
SettingsList settingsList;
for (auto& setting: settings) {
switch (setting.first) {
case SettingsId::HEADER_TABLE_SIZE:
{
uint32_t tableSize = setting.second;
if (setting.second > http2::kMaxHeaderTableSize) {
VLOG(2) << "Limiting table size from " << tableSize << " to " <<
http2::kMaxHeaderTableSize;
tableSize = http2::kMaxHeaderTableSize;
}
headerCodec_.setEncoderHeaderTableSize(tableSize);
}
break;
case SettingsId::ENABLE_PUSH:
if ((setting.second != 0 && setting.second != 1) ||
(setting.second == 1 &&
transportDirection_ == TransportDirection::UPSTREAM)) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_PUSH invalid setting=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
break;
case SettingsId::INITIAL_WINDOW_SIZE:
if (setting.second > http2::kMaxWindowUpdateSize) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: INITIAL_WINDOW_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::MAX_FRAME_SIZE:
if (setting.second < http2::kMaxFramePayloadLengthMin ||
setting.second > http2::kMaxFramePayloadLength) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: MAX_FRAME_SIZE invalid size=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
ingressSettings_.setSetting(SettingsId::MAX_FRAME_SIZE, setting.second);
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
break;
case SettingsId::ENABLE_EX_HEADERS:
{
auto ptr = egressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS);
if (ptr && ptr->value > 0) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " got ENABLE_EX_HEADERS=" << setting.second;
if (setting.second != 0 && setting.second != 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid ENABLE_EX_HEADERS=", setting.second,
" for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
} else {
// egress ENABLE_EX_HEADERS is disabled, consider the ingress
// ENABLE_EX_HEADERS as unknown setting, and ignore it.
continue;
}
}
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.second > 1) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: ENABLE_CONNECT_PROTOCOL invalid number=",
setting.second, " for streamID=", curHeader_.stream);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
case SettingsId::SETTINGS_HTTP_CERT_AUTH:
break;
default:
continue; // ignore unknown setting
}
ingressSettings_.setSetting(setting.first, setting.second);
settingsList.push_back(*ingressSettings_.getSetting(setting.first));
}
if (callback_) {
callback_->onSettings(settingsList);
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parsePushPromise(Cursor& cursor) {
// stream id must be idle - protocol error
// assoc-stream-id=closed/unknown - protocol error, unless rst_stream sent
/*
* What does "must handle" mean in the following context? I have to
* accept this as a valid pushed resource?
However, an endpoint that has sent RST_STREAM on the associated
stream MUST handle PUSH_PROMISE frames that might have been
created before the RST_STREAM frame is received and processed.
*/
if (transportDirection_ != TransportDirection::UPSTREAM) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on DOWNSTREAM codec");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
if (egressSettings_.getSetting(SettingsId::ENABLE_PUSH, -1) != 1) {
goawayErrorMessage_ = folly::to<string>(
"Received PUSH_PROMISE on codec with push disabled");
VLOG(2) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
VLOG(4) << "parsing PUSH_PROMISE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t promisedStream;
std::unique_ptr<IOBuf> headerBlockFragment;
auto err = http2::parsePushPromise(cursor, curHeader_, promisedStream,
headerBlockFragment);
RETURN_IF_ERROR(err);
RETURN_IF_ERROR(checkNewStream(promisedStream, false /* trailersAllowed */));
err = parseHeadersImpl(cursor, std::move(headerBlockFragment), folly::none,
promisedStream, folly::none);
return err;
}
ErrorCode HTTP2Codec::parsePing(Cursor& cursor) {
VLOG(4) << "parsing PING frame length=" << curHeader_.length;
uint64_t opaqueData = 0;
auto err = http2::parsePing(cursor, curHeader_, opaqueData);
RETURN_IF_ERROR(err);
if (callback_) {
if (curHeader_.flags & http2::ACK) {
callback_->onPingReply(opaqueData);
} else {
callback_->onPingRequest(opaqueData);
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseGoaway(Cursor& cursor) {
VLOG(4) << "parsing GOAWAY frame length=" << curHeader_.length;
uint32_t lastGoodStream = 0;
ErrorCode statusCode = ErrorCode::NO_ERROR;
std::unique_ptr<IOBuf> debugData;
auto err = http2::parseGoaway(cursor, curHeader_, lastGoodStream, statusCode,
debugData);
if (statusCode != ErrorCode::NO_ERROR) {
VLOG(2) << "Goaway error statusCode=" << getErrorCodeString(statusCode)
<< " lastStream=" << lastGoodStream
<< " user-agent=" << userAgent_ << " debugData=" <<
((debugData) ? string((char*)debugData->data(), debugData->length()):
empty_string);
}
RETURN_IF_ERROR(err);
if (lastGoodStream < ingressGoawayAck_) {
ingressGoawayAck_ = lastGoodStream;
// Drain all streams <= lastGoodStream
// and abort streams > lastGoodStream
if (callback_) {
callback_->onGoaway(lastGoodStream, statusCode, std::move(debugData));
}
} else {
LOG(WARNING) << "Received multiple GOAWAY with increasing ack";
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseWindowUpdate(Cursor& cursor) {
VLOG(4) << "parsing WINDOW_UPDATE frame for stream=" << curHeader_.stream <<
" length=" << curHeader_.length;
uint32_t delta = 0;
auto err = http2::parseWindowUpdate(cursor, curHeader_, delta);
RETURN_IF_ERROR(err);
if (delta == 0) {
VLOG(4) << "Invalid 0 length delta for stream=" << curHeader_.stream;
if (curHeader_.stream == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid/0 length delta for streamID=",
curHeader_.stream);
return ErrorCode::PROTOCOL_ERROR;
} else {
// Parsing a zero delta window update should cause a protocol error
// and send a rst stream
goawayErrorMessage_ = folly::to<string>(
"parseWindowUpdate Invalid 0 length");
VLOG(4) << goawayErrorMessage_;
streamError(folly::to<std::string>("streamID=", curHeader_.stream,
" with HTTP2Codec stream error: ",
"window update delta=", delta),
ErrorCode::PROTOCOL_ERROR);
return ErrorCode::PROTOCOL_ERROR;
}
}
// if window exceeds 2^31-1, connection/stream error flow control error
// must be checked in session/txn
deliverCallbackIfAllowed(&HTTPCodec::Callback::onWindowUpdate,
"onWindowUpdate", curHeader_.stream, delta);
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificateRequest(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE_REQUEST frame length=" << curHeader_.length;
uint16_t requestId = 0;
std::unique_ptr<IOBuf> authRequest;
auto err = http2::parseCertificateRequest(
cursor, curHeader_, requestId, authRequest);
RETURN_IF_ERROR(err);
if (callback_) {
callback_->onCertificateRequest(requestId, std::move(authRequest));
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::parseCertificate(Cursor& cursor) {
VLOG(4) << "parsing CERTIFICATE frame length=" << curHeader_.length;
uint16_t certId = 0;
std::unique_ptr<IOBuf> authData;
auto err = http2::parseCertificate(cursor, curHeader_, certId, authData);
RETURN_IF_ERROR(err);
if (curAuthenticatorBlock_.empty()) {
curCertId_ = certId;
} else if (certId != curCertId_) {
// Received CERTIFICATE frame with different Cert-ID.
return ErrorCode::PROTOCOL_ERROR;
}
curAuthenticatorBlock_.append(std::move(authData));
if (curAuthenticatorBlock_.chainLength() > http2::kMaxAuthenticatorBufSize) {
// Received excessively long authenticator.
return ErrorCode::PROTOCOL_ERROR;
}
if (!(curHeader_.flags & http2::TO_BE_CONTINUED)) {
auto authenticator = curAuthenticatorBlock_.move();
if (callback_) {
callback_->onCertificate(certId, std::move(authenticator));
} else {
curAuthenticatorBlock_.clear();
}
}
return ErrorCode::NO_ERROR;
}
ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) {
if (streamId == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: received streamID=", streamId,
" as invalid new stream for lastStreamID_=", lastStreamID_);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_);
if (parsingDownstreamTrailers_) {
VLOG(4) << "Parsing downstream trailers streamId=" << streamId;
}
if (sessionClosing_ != ClosingState::CLOSED) {
lastStreamID_ = streamId;
}
if (isInitiatedStream(streamId)) {
// this stream should be initiated by us, not by peer
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid new stream received with streamID=", streamId);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
} else {
return ErrorCode::NO_ERROR;
}
}
size_t HTTP2Codec::generateConnectionPreface(folly::IOBufQueue& writeBuf) {
if (transportDirection_ == TransportDirection::UPSTREAM) {
VLOG(4) << "generating connection preface";
writeBuf.append(http2::kConnectionPreface);
return http2::kConnectionPreface.length();
}
return 0;
}
bool HTTP2Codec::onIngressUpgradeMessage(const HTTPMessage& msg) {
if (!HTTPParallelCodec::onIngressUpgradeMessage(msg)) {
return false;
}
if (msg.getHeaders().getNumberOfValues(http2::kProtocolSettingsHeader) != 1) {
VLOG(4) << __func__ << " with no HTTP2-Settings";
return false;
}
const auto& settingsHeader = msg.getHeaders().getSingleOrEmpty(
http2::kProtocolSettingsHeader);
if (settingsHeader.empty()) {
return true;
}
auto decoded = base64url_decode(settingsHeader);
// Must be well formed Base64Url and not too large
if (decoded.empty() || decoded.length() > http2::kMaxFramePayloadLength) {
VLOG(4) << __func__ << " failed to decode HTTP2-Settings";
return false;
}
std::unique_ptr<IOBuf> decodedBuf = IOBuf::wrapBuffer(decoded.data(),
decoded.length());
IOBufQueue settingsQueue{IOBufQueue::cacheChainLength()};
settingsQueue.append(std::move(decodedBuf));
Cursor c(settingsQueue.front());
std::deque<SettingPair> settings;
// downcast is ok because of above length check
http2::FrameHeader frameHeader{
(uint32_t)settingsQueue.chainLength(), 0, http2::FrameType::SETTINGS, 0, 0};
auto err = http2::parseSettings(c, frameHeader, settings);
if (err != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " bad settings frame";
return false;
}
if (handleSettings(settings) != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " handleSettings failed";
return false;
}
return true;
}
void HTTP2Codec::generateHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generatePushPromise(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
StreamID assocStream,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
assocStream,
folly::none, /* controlStream */
eom,
size);
}
void HTTP2Codec::generateExHeader(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const HTTPCodec::ExAttributes& exAttributes,
bool eom,
HTTPHeaderSize* size) {
generateHeaderImpl(writeBuf,
stream,
msg,
folly::none, /* assocStream */
exAttributes,
eom,
size);
}
void HTTP2Codec::generateHeaderImpl(
folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage& msg,
const folly::Optional<StreamID>& assocStream,
const folly::Optional<HTTPCodec::ExAttributes>& exAttributes,
bool eom,
HTTPHeaderSize* size) {
if (assocStream) {
CHECK(!exAttributes);
VLOG(4) << "generating PUSH_PROMISE for stream=" << stream;
} else if (exAttributes) {
CHECK(!assocStream);
VLOG(4) << "generating ExHEADERS for stream=" << stream
<< " with control stream=" << exAttributes->controlStream
<< " unidirectional=" << exAttributes->unidirectional;
} else {
VLOG(4) << "generating HEADERS for stream=" << stream;
}
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing HEADERS/PROMISE for stream=" << stream <<
" ingressGoawayAck_=" << ingressGoawayAck_;
if (size) {
size->uncompressed = 0;
size->compressed = 0;
}
return;
}
if (msg.isRequest()) {
DCHECK(transportDirection_ == TransportDirection::UPSTREAM ||
assocStream || exAttributes);
if (msg.isEgressWebsocketUpgrade()) {
upgradedStreams_.insert(stream);
}
} else {
DCHECK(transportDirection_ == TransportDirection::DOWNSTREAM ||
exAttributes);
}
std::vector<std::string> temps;
auto allHeaders = CodecUtil::prepareMessageForCompression(msg, temps);
auto out = encodeHeaders(msg.getHeaders(), allHeaders, size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto res = msg.getHTTP2Priority();
auto remainingFrameSize = maxFrameSize;
if (res) {
pri = http2::PriorityUpdate{std::get<0>(*res), std::get<1>(*res),
std::get<2>(*res)};
DCHECK_GE(remainingFrameSize, http2::kFramePrioritySize)
<< "no enough space for priority? frameHeadroom=" << remainingFrameSize;
remainingFrameSize -= http2::kFramePrioritySize;
}
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
if (assocStream) {
DCHECK_EQ(transportDirection_, TransportDirection::DOWNSTREAM);
DCHECK(!eom);
generateHeaderCallbackWrapper(stream, http2::FrameType::PUSH_PROMISE,
http2::writePushPromise(writeBuf,
*assocStream,
stream,
std::move(chunk),
http2::kNoPadding,
endHeaders));
} else if (exAttributes) {
generateHeaderCallbackWrapper(
stream,
http2::FrameType::EX_HEADERS,
http2::writeExHeaders(writeBuf,
std::move(chunk),
stream,
*exAttributes,
pri,
http2::kNoPadding,
eom,
endHeaders));
} else {
generateHeaderCallbackWrapper(stream, http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
eom,
endHeaders));
}
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
}
void HTTP2Codec::generateContinuation(folly::IOBufQueue& writeBuf,
folly::IOBufQueue& queue,
StreamID stream,
size_t maxFrameSize) {
bool endHeaders = false;
while (!endHeaders) {
auto chunk = queue.split(std::min(maxFrameSize, queue.chainLength()));
endHeaders = (queue.chainLength() == 0);
VLOG(4) << "generating CONTINUATION for stream=" << stream;
generateHeaderCallbackWrapper(
stream,
http2::FrameType::CONTINUATION,
http2::writeContinuation(
writeBuf, stream, endHeaders, std::move(chunk)));
}
}
std::unique_ptr<folly::IOBuf> HTTP2Codec::encodeHeaders(
const HTTPHeaders& headers,
std::vector<compress::Header>& allHeaders,
HTTPHeaderSize* size) {
headerCodec_.setEncodeHeadroom(http2::kFrameHeaderSize +
http2::kFrameHeadersBaseMaxSize);
auto out = headerCodec_.encode(allHeaders);
if (size) {
*size = headerCodec_.getEncodedSize();
}
if (headerCodec_.getEncodedSize().uncompressed >
ingressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE,
std::numeric_limits<uint32_t>::max())) {
// The remote side told us they don't want headers this large...
// but this function has no mechanism to fail
string serializedHeaders;
headers.forEach(
[&serializedHeaders] (const string& name, const string& value) {
serializedHeaders = folly::to<string>(serializedHeaders, "\\n", name,
":", value);
});
LOG(ERROR) << "generating HEADERS frame larger than peer maximum nHeaders="
<< headers.size() << " all headers="
<< serializedHeaders;
}
return out;
}
size_t HTTP2Codec::generateHeaderCallbackWrapper(StreamID stream,
http2::FrameType type,
size_t length) {
if (callback_) {
callback_->onGenerateFrameHeader(stream,
static_cast<uint8_t>(type),
length);
}
return length;
}
size_t HTTP2Codec::generateBody(folly::IOBufQueue& writeBuf,
StreamID stream,
std::unique_ptr<folly::IOBuf> chain,
folly::Optional<uint8_t> padding,
bool eom) {
// todo: generate random padding for everything?
size_t written = 0;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "Suppressing DATA for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(chain));
size_t maxFrameSize = maxSendFrameSize();
while (queue.chainLength() > maxFrameSize) {
auto chunk = queue.split(maxFrameSize);
written += generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
std::move(chunk),
stream,
padding,
false,
reuseIOBufHeadroomForData_));
}
return written + generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
queue.move(),
stream,
padding,
eom,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateChunkHeader(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/,
size_t /*length*/) {
// HTTP/2 has no chunk headers
return 0;
}
size_t HTTP2Codec::generateChunkTerminator(folly::IOBufQueue& /*writeBuf*/,
StreamID /*stream*/) {
// HTTP/2 has no chunk terminators
return 0;
}
size_t HTTP2Codec::generateTrailers(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPHeaders& trailers) {
std::vector<compress::Header> allHeaders;
CodecUtil::appendHeaders(trailers, allHeaders, HTTP_HEADER_NONE);
HTTPHeaderSize size;
auto out = encodeHeaders(trailers, allHeaders, &size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto remainingFrameSize = maxFrameSize;
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
generateHeaderCallbackWrapper(stream,
http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
true /*eom*/,
endHeaders));
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
return size.compressed;
}
size_t HTTP2Codec::generateEOM(folly::IOBufQueue& writeBuf,
StreamID stream) {
VLOG(4) << "sending EOM for stream=" << stream;
upgradedStreams_.erase(stream);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed EOM for stream=" << stream << " ingressGoawayAck_="
<< ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::DATA,
http2::writeData(writeBuf,
nullptr,
stream,
http2::kNoPadding,
true,
reuseIOBufHeadroomForData_));
}
size_t HTTP2Codec::generateRstStream(folly::IOBufQueue& writeBuf,
StreamID stream,
ErrorCode statusCode) {
VLOG(4) << "sending RST_STREAM for stream=" << stream
<< " with code=" << getErrorCodeString(statusCode);
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed RST_STREAM for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
// Suppress any EOM callback for the current frame.
if (stream == curHeader_.stream) {
curHeader_.flags &= ~http2::END_STREAM;
pendingEndStreamHandling_ = false;
ingressWebsocketUpgrade_ = false;
}
upgradedStreams_.erase(stream);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending RST_STREAM with code=" << getErrorCodeString(statusCode)
<< " for stream=" << stream << " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToReset(statusCode);
return generateHeaderCallbackWrapper(stream, http2::FrameType::RST_STREAM,
http2::writeRstStream(writeBuf, stream, code));
}
size_t HTTP2Codec::generateGoaway(folly::IOBufQueue& writeBuf,
StreamID lastStream,
ErrorCode statusCode,
std::unique_ptr<folly::IOBuf> debugData) {
DCHECK_LE(lastStream, egressGoawayAck_) << "Cannot increase last good stream";
egressGoawayAck_ = lastStream;
if (sessionClosing_ == ClosingState::CLOSED) {
VLOG(4) << "Not sending GOAWAY for closed session";
return 0;
}
switch (sessionClosing_) {
case ClosingState::OPEN:
case ClosingState::OPEN_WITH_GRACEFUL_DRAIN_ENABLED:
if (lastStream == std::numeric_limits<int32_t>::max() &&
statusCode == ErrorCode::NO_ERROR) {
sessionClosing_ = ClosingState::FIRST_GOAWAY_SENT;
} else {
// The user of this codec decided not to do the double goaway
// drain, or this is not a graceful shutdown
sessionClosing_ = ClosingState::CLOSED;
}
break;
case ClosingState::FIRST_GOAWAY_SENT:
sessionClosing_ = ClosingState::CLOSED;
break;
case ClosingState::CLOSING:
case ClosingState::CLOSED:
LOG(FATAL) << "unreachable";
}
VLOG(4) << "Sending GOAWAY with last acknowledged stream="
<< lastStream << " with code=" << getErrorCodeString(statusCode);
if (statusCode == ErrorCode::PROTOCOL_ERROR) {
VLOG(2) << "sending GOAWAY with last acknowledged stream=" << lastStream
<< " with code=" << getErrorCodeString(statusCode)
<< " user-agent=" << userAgent_;
}
auto code = http2::errorCodeToGoaway(statusCode);
return generateHeaderCallbackWrapper(
0,
http2::FrameType::GOAWAY,
http2::writeGoaway(writeBuf,
lastStream,
code,
std::move(debugData)));
}
size_t HTTP2Codec::generatePingRequest(folly::IOBufQueue& writeBuf) {
// should probably let the caller specify when integrating with session
// we know HTTPSession sets up events to track ping latency
uint64_t opaqueData = folly::Random::rand64();
VLOG(4) << "Generating ping request with opaqueData=" << opaqueData;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, opaqueData, false /* no ack */));
}
size_t HTTP2Codec::generatePingReply(folly::IOBufQueue& writeBuf,
uint64_t uniqueID) {
VLOG(4) << "Generating ping reply with opaqueData=" << uniqueID;
return generateHeaderCallbackWrapper(0, http2::FrameType::PING,
http2::writePing(writeBuf, uniqueID, true /* ack */));
}
size_t HTTP2Codec::generateSettings(folly::IOBufQueue& writeBuf) {
std::deque<SettingPair> settings;
for (auto& setting: egressSettings_.getAllSettings()) {
switch (setting.id) {
case SettingsId::HEADER_TABLE_SIZE:
if (pendingTableMaxSize_) {
LOG(ERROR) << "Can't have more than one settings in flight, skipping";
continue;
} else {
pendingTableMaxSize_ = setting.value;
}
break;
case SettingsId::ENABLE_PUSH:
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
// HTTP/2 spec says downstream must not send this flag
// HTTP2Codec uses it to determine if push features are enabled
continue;
} else {
CHECK(setting.value == 0 || setting.value == 1);
}
break;
case SettingsId::MAX_CONCURRENT_STREAMS:
case SettingsId::INITIAL_WINDOW_SIZE:
case SettingsId::MAX_FRAME_SIZE:
break;
case SettingsId::MAX_HEADER_LIST_SIZE:
headerCodec_.setMaxUncompressed(setting.value);
break;
case SettingsId::ENABLE_EX_HEADERS:
CHECK(setting.value == 0 || setting.value == 1);
if (setting.value == 0) {
continue; // just skip the experimental setting if disabled
} else {
VLOG(4) << "generating ENABLE_EX_HEADERS=" << setting.value;
}
break;
case SettingsId::ENABLE_CONNECT_PROTOCOL:
if (setting.value == 0) {
continue;
}
break;
case SettingsId::THRIFT_CHANNEL_ID:
case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED:
break;
default:
LOG(ERROR) << "ignore unknown settingsId="
<< std::underlying_type<SettingsId>::type(setting.id)
<< " value=" << setting.value;
continue;
}
settings.push_back(SettingPair(setting.id, setting.value));
}
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating " << (unsigned)settings.size() << " settings";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettings(writeBuf, settings));
}
void HTTP2Codec::requestUpgrade(HTTPMessage& request) {
static folly::ThreadLocalPtr<HTTP2Codec> defaultCodec;
if (!defaultCodec.get()) {
defaultCodec.reset(new HTTP2Codec(TransportDirection::UPSTREAM));
}
auto& headers = request.getHeaders();
headers.set(HTTP_HEADER_UPGRADE, http2::kProtocolCleartextString);
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION, "Upgrade", false)) {
headers.add(HTTP_HEADER_CONNECTION, "Upgrade");
}
IOBufQueue writeBuf{IOBufQueue::cacheChainLength()};
defaultCodec->generateSettings(writeBuf);
// fake an ack since defaultCodec gets reused
defaultCodec->handleSettingsAck();
writeBuf.trimStart(http2::kFrameHeaderSize);
auto buf = writeBuf.move();
buf->coalesce();
headers.set(http2::kProtocolSettingsHeader,
base64url_encode(folly::ByteRange(buf->data(), buf->length())));
if (!request.checkForHeaderToken(HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(),
false)) {
headers.add(HTTP_HEADER_CONNECTION, http2::kProtocolSettingsHeader);
}
}
size_t HTTP2Codec::generateSettingsAck(folly::IOBufQueue& writeBuf) {
VLOG(4) << getTransportDirectionString(getTransportDirection())
<< " generating settings ack";
return generateHeaderCallbackWrapper(0, http2::FrameType::SETTINGS,
http2::writeSettingsAck(writeBuf));
}
size_t HTTP2Codec::generateWindowUpdate(folly::IOBufQueue& writeBuf,
StreamID stream,
uint32_t delta) {
VLOG(4) << "generating window update for stream=" << stream
<< ": Processed " << delta << " bytes";
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed WINDOW_UPDATE for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(stream, http2::FrameType::WINDOW_UPDATE,
http2::writeWindowUpdate(writeBuf, stream, delta));
}
size_t HTTP2Codec::generatePriority(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPMessage::HTTPPriority& pri) {
VLOG(4) << "generating priority for stream=" << stream;
if (!isStreamIngressEgressAllowed(stream)) {
VLOG(2) << "suppressed PRIORITY for stream=" << stream
<< " ingressGoawayAck_=" << ingressGoawayAck_;
return 0;
}
return generateHeaderCallbackWrapper(
stream,
http2::FrameType::PRIORITY,
http2::writePriority(writeBuf, stream,
{std::get<0>(pri),
std::get<1>(pri),
std::get<2>(pri)}));
}
size_t HTTP2Codec::generateCertificateRequest(
folly::IOBufQueue& writeBuf,
uint16_t requestId,
std::unique_ptr<folly::IOBuf> certificateRequestData) {
VLOG(4) << "generating CERTIFICATE_REQUEST with Request-ID=" << requestId;
return http2::writeCertificateRequest(
writeBuf, requestId, std::move(certificateRequestData));
}
size_t HTTP2Codec::generateCertificate(folly::IOBufQueue& writeBuf,
uint16_t certId,
std::unique_ptr<folly::IOBuf> certData) {
size_t written = 0;
VLOG(4) << "sending CERTIFICATE with Cert-ID=" << certId << "for stream=0";
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(certData));
// The maximum size of an autenticator fragment, combined with the Cert-ID can
// not exceed the maximal allowable size of a sent frame.
size_t maxChunkSize = maxSendFrameSize() - sizeof(certId);
while (queue.chainLength() > maxChunkSize) {
auto chunk = queue.splitAtMost(maxChunkSize);
written +=
http2::writeCertificate(writeBuf, certId, std::move(chunk), true);
}
return written +
http2::writeCertificate(writeBuf, certId, queue.move(), false);
}
bool HTTP2Codec::checkConnectionError(ErrorCode err, const folly::IOBuf* buf) {
if (err != ErrorCode::NO_ERROR) {
LOG(ERROR) << "Connection error " << getErrorCodeString(err)
<< " with ingress=";
VLOG(3) << IOBufPrinter::printHexFolly(buf, true);
if (callback_) {
std::string errorDescription = goawayErrorMessage_.empty() ?
"Connection error" : goawayErrorMessage_;
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
errorDescription);
ex.setCodecStatusCode(err);
callback_->onError(0, ex, false);
}
return true;
}
return false;
}
void HTTP2Codec::streamError(const std::string& msg, ErrorCode code,
bool newTxn) {
HTTPException error(HTTPException::Direction::INGRESS_AND_EGRESS,
msg);
error.setCodecStatusCode(code);
if (callback_) {
callback_->onError(curHeader_.stream, error, newTxn);
}
}
HTTPCodec::StreamID
HTTP2Codec::mapPriorityToDependency(uint8_t priority) const {
// If the priority is out of the maximum index of virtual nodes array, we
// return the lowest level virtual node as a punishment of not setting
// priority correctly.
return virtualPriorityNodes_.empty()
? 0
: virtualPriorityNodes_[
std::min(priority, uint8_t(virtualPriorityNodes_.size() - 1))];
}
bool HTTP2Codec::parsingTrailers() const {
// HEADERS frame is used for request/response headers and trailers.
// Per spec, specific role of HEADERS frame is determined by it's postion
// within the stream. We don't keep full stream state in this codec,
// thus using heuristics to distinguish between headers/trailers.
// For DOWNSTREAM case, request headers HEADERS frame would be creating
// new stream, thus HEADERS on existing stream ID are considered trailers
// (see checkNewStream).
// For UPSTREAM case, response headers are required to have status code,
// thus if no status code we consider that trailers.
if (curHeader_.type == http2::FrameType::HEADERS ||
curHeader_.type == http2::FrameType::CONTINUATION) {
if (transportDirection_ == TransportDirection::DOWNSTREAM) {
return parsingDownstreamTrailers_;
} else {
return !decodeInfo_.hasStatus();
}
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-388/cpp/bad_599_0 |
crossvul-cpp_data_bad_599_1 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/test/HTTPParallelCodecTest.h>
#include <proxygen/lib/http/codec/test/MockHTTPCodec.h>
#include <folly/io/Cursor.h>
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/test/HTTP2FramerTest.h>
#include <proxygen/lib/http/HTTPHeaderSize.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include <folly/portability/GTest.h>
#include <folly/portability/GMock.h>
#include <random>
using namespace proxygen;
using namespace proxygen::compress;
using namespace folly;
using namespace folly::io;
using namespace std;
using namespace testing;
TEST(HTTP2CodecConstantsTest, HTTPContantsAreCommonHeaders) {
// The purpose of this test is to verify some basic assumptions that should
// never change but to make clear that the following http2 header constants
// map to the respective common headers. Should this test ever fail, the
// H2Codec would need to be updated in the corresponding places when creating
// compress/Header objects.
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kMethod),
HTTP_HEADER_COLON_METHOD);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kScheme),
HTTP_HEADER_COLON_SCHEME);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kPath),
HTTP_HEADER_COLON_PATH);
EXPECT_EQ(
HTTPCommonHeaders::hash(headers::kAuthority),
HTTP_HEADER_COLON_AUTHORITY);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kStatus),
HTTP_HEADER_COLON_STATUS);
}
class HTTP2CodecTest : public HTTPParallelCodecTest {
public:
HTTP2CodecTest()
:HTTPParallelCodecTest(upstreamCodec_, downstreamCodec_) {}
void SetUp() override {
HTTPParallelCodecTest::SetUp();
}
void testHeaderListSize(bool oversized);
void testFrameSizeLimit(bool oversized);
protected:
HTTP2Codec upstreamCodec_{TransportDirection::UPSTREAM};
HTTP2Codec downstreamCodec_{TransportDirection::DOWNSTREAM};
};
TEST_F(HTTP2CodecTest, IgnoreUnknownSettings) {
auto numSettings = downstreamCodec_.getIngressSettings()->getNumSettings();
std::deque<SettingPair> settings;
for (uint32_t i = 200; i < (200 + 1024); i++) {
settings.push_back(SettingPair(SettingsId(i), i));
}
http2::writeSettings(output_, settings);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(numSettings,
downstreamCodec_.getIngressSettings()->getNumSettings());
}
TEST_F(HTTP2CodecTest, NoExHeaders) {
// do not emit ENABLE_EX_HEADERS setting, if disabled
SetUpUpstreamTest();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.numSettings, 0);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
parseUpstream();
EXPECT_EQ(callbacks_.settings, 1);
// only 3 standard settings: HEADER_TABLE_SIZE, ENABLE_PUSH, MAX_FRAME_SIZE.
EXPECT_EQ(callbacks_.numSettings, 3);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersSetting) {
// disable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, EnableExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
EXPECT_EQ(true, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, InvalidExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
// attempt to set a invalid ENABLE_EX_HEADERS value
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 110)});
parse();
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeader) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, RequestFromServer) {
// this is to test EX_HEADERS frame, which carrys the HTTP request initiated
// by server side
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
SetUpUpstreamTest();
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
upstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true),
true);
parseUpstream();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, ResponseFromClient) {
// this is to test EX_HEADERS frame, which carrys the HTTP response replied by
// client side
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, resp,
HTTPCodec::ExAttributes(controlStream, true), true);
parse();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, ExHeadersWithPriority) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
auto req = getGetRequest();
auto pri = HTTPMessage::HTTPPriority(0, false, 7);
req.setHTTP2Priority(pri);
upstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.msg->getHTTP2Priority(), pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersIfNotEnabled) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
HTTPMessage req = getGetRequest("/guacamole");
downstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaders) {
static const std::string v1("GET");
static const std::string v2("/");
static const std::string v3("http");
static const std::string v4("foo.com");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 7);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPseudoHeaders) {
static const std::string v1("POST");
static const std::string v2("http");
static const std::string n3("foo");
static const std::string v3("bar");
static const std::string v4("/");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kScheme, v2),
Header::makeHeaderForTest(n3, v3),
Header::makeHeaderForTest(headers::kPath, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderValues) {
static const std::string v1("--1");
static const std::string v2("\13\10protocol-attack");
static const std::string v3("\13");
static const std::string v4("abc.com\\13\\10");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders;
allHeaders.push_back(reqHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 4);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
/**
* Ingress bytes with an empty header name
*/
const uint8_t kBufEmptyHeader[] = {
0x00, 0x00, 0x1d, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x82,
0x87, 0x44, 0x87, 0x62, 0x6b, 0x46, 0x41, 0xd2, 0x7a, 0x0b,
0x41, 0x89, 0xf1, 0xe3, 0xc2, 0xf2, 0x9c, 0xeb, 0x90, 0xf4,
0xff, 0x40, 0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7
};
TEST_F(HTTP2CodecTest, EmptyHeaderName) {
output_.append(IOBuf::copyBuffer(kBufEmptyHeader, sizeof(kBufEmptyHeader)));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicConnect) {
std::string authority = "myhost:1234";
HTTPMessage request;
request.setMethod(HTTPMethod::CONNECT);
request.getHeaders().add(proxygen::HTTP_HEADER_HOST, authority);
upstreamCodec_.generateHeader(output_, 1, request, false /* eom */);
parse();
callbacks_.expectMessage(false, 1, "");
EXPECT_EQ(HTTPMethod::CONNECT, callbacks_.msg->getMethod());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(authority, headers.getSingleOrEmpty(proxygen::HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, BadConnect) {
std::string v1 = "CONNECT";
std::string v2 = "somehost:576";
std::vector<proxygen::compress::Header> goodHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kAuthority, v2),
};
// See https://tools.ietf.org/html/rfc7540#section-8.3
std::string v3 = "/foobar";
std::vector<proxygen::compress::Header> badHeaders = {
Header::makeHeaderForTest(headers::kScheme, headers::kHttp),
Header::makeHeaderForTest(headers::kPath, v3),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < badHeaders.size(); i++, stream += 2) {
auto allHeaders = goodHeaders;
allHeaders.push_back(badHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, badHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
void HTTP2CodecTest::testHeaderListSize(bool oversized) {
if (oversized) {
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
}
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("x-long-long-header",
"supercalafragalisticexpialadoshus");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
void HTTP2CodecTest::testFrameSizeLimit(bool oversized) {
HTTPMessage req = getBigGetRequest("/guacamole");
auto settings = downstreamCodec_.getEgressSettings();
parse(); // consume preface
if (oversized) {
// trick upstream for sending a 2x bigger HEADERS frame
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin * 2);
downstreamCodec_.generateSettings(output_);
parseUpstream();
}
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
TEST_F(HTTP2CodecTest, NormalSizeHeader) {
testHeaderListSize(false);
}
TEST_F(HTTP2CodecTest, OversizedHeader) {
testHeaderListSize(true);
}
TEST_F(HTTP2CodecTest, NormalSizeFrame) {
testFrameSizeLimit(false);
}
TEST_F(HTTP2CodecTest, OversizedFrame) {
testFrameSizeLimit(true);
}
TEST_F(HTTP2CodecTest, BigHeaderCompressed) {
SetUpUpstreamTest();
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
downstreamCodec_.generateSettings(output_);
parseUpstream();
SetUp();
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeaderReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
// HTTP/2 doesnt support serialization - instead you get the default
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadHeadersReply) {
static const std::string v1("200");
static const vector<proxygen::compress::Header> respHeaders = {
Header::makeHeaderForTest(headers::kStatus, v1),
};
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, Cookies) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add("Cookie", "chocolate-chip=1");
req.getHeaders().add("Cookie", "rainbow-chip=2");
req.getHeaders().add("Cookie", "butterscotch=3");
req.getHeaders().add("Cookie", "oatmeal-raisin=4");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, "/guacamole");
EXPECT_EQ(callbacks_.msg->getCookie("chocolate-chip"), "1");
EXPECT_EQ(callbacks_.msg->getCookie("rainbow-chip"), "2");
EXPECT_EQ(callbacks_.msg->getCookie("butterscotch"), "3");
EXPECT_EQ(callbacks_.msg->getCookie("oatmeal-raisin"), "4");
}
TEST_F(HTTP2CodecTest, BasicContinuation) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicContinuationEndStream) {
// CONTINUATION with END_STREAM flag set on the preceding HEADERS frame
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadContinuation) {
// CONTINUATION with no preceding HEADERS
auto fakeHeaders = makeBuf(5);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, MissingContinuation) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, MissingContinuationBadFrame) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert an invalid frame
auto frame = makeBuf(http2::kFrameHeaderSize + 4134);
*((uint32_t *)frame->writableData()) = 0xfa000000;
output_.append(std::move(frame));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, BadContinuationStream) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
auto fakeHeaders = makeBuf(4134);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, FrameTooLarge) {
writeFrameHeaderManual(output_, 1 << 15, 0, 0, 1);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_TRUE(callbacks_.lastParseError->hasCodecStatusCode());
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::FRAME_SIZE_ERROR);
}
TEST_F(HTTP2CodecTest, UnknownFrameType) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// unknown frame type 17
writeFrameHeaderManual(output_, 17, 37, 0, 1);
output_.append("wicked awesome!!!");
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, ""); // + host
}
TEST_F(HTTP2CodecTest, JunkAfterConnError) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// write headers frame for stream 0
writeFrameHeaderManual(output_, 0, (uint8_t)http2::FrameType::HEADERS, 0, 0);
// now write a valid headers frame, should never be parsed
upstreamCodec_.generateHeader(output_, 1, req);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicData) {
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), data);
}
TEST_F(HTTP2CodecTest, LongData) {
// Hack the max frame size artificially low
HTTPSettings* settings = (HTTPSettings*)upstreamCodec_.getIngressSettings();
settings->setSetting(SettingsId::MAX_FRAME_SIZE, 16);
auto buf = makeBuf(100);
upstreamCodec_.generateBody(output_, 1, buf->clone(), HTTPCodec::NoPadding,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 7);
EXPECT_EQ(callbacks_.bodyLength, 100);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, MalformedPaddingLength) {
const uint8_t badInput[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x7e, 0x00, 0x6f, 0x6f, 0x6f, 0x6f,
// The padding length byte below is 0x82 (130
// in decimal) which is greater than the length
// specified by the header's length field, 126
0x01, 0x82, 0x87, 0x44, 0x87, 0x92, 0x97, 0x92,
0x92, 0x92, 0x7a, 0x0b, 0x41, 0x89, 0xf1, 0xe3,
0xc0, 0xf2, 0x9c, 0xdd, 0x90, 0xf4, 0xff, 0x40,
0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7};
output_.clear();
output_.append(badInput, sizeof(badInput));
EXPECT_EQ(output_.chainLength(), sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, MalformedPadding) {
const uint8_t badInput[] = {
0x00, 0x00, 0x0d, 0x01, 0xbe, 0x63, 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x73,
0x00, 0x00, 0x06, 0x08, 0x72, 0x00, 0x24, 0x00, 0xfa, 0x4d, 0x0d
};
output_.append(badInput, sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, NoAppByte) {
const uint8_t noAppByte[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x56, 0x00, 0x5d, 0x00, 0x00, 0x00,
0x01, 0x55, 0x00};
output_.clear();
output_.append(noAppByte, sizeof(noAppByte));
EXPECT_EQ(output_.chainLength(), sizeof(noAppByte));
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataOnFrameHeaderCall) {
using namespace testing;
NiceMock<MockHTTPCodecCallback> mockCallback;
EXPECT_CALL(mockCallback, onFrameHeader(_, _, _, _, _));
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
downstreamCodec_.setCallback(&mockCallback);
auto ingress = output_.move();
ingress->coalesce();
// Copy partial byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
downstreamCodec_.onIngress(*ingress1);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataWithNoAppByte) {
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
auto ingress = output_.move();
ingress->coalesce();
// Copy up to the padding length byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
size_t parsed = downstreamCodec_.onIngress(*ingress1);
// The 34th byte is the padding length byte which should not be parsed
EXPECT_EQ(parsed, 33);
// Copy from the padding length byte to the end
auto ingress2 = IOBuf::copyBuffer(ingress->data() + 33, 21);
parsed = downstreamCodec_.onIngress(*ingress2);
// The padding length byte should be parsed this time along with 10 bytes of
// application data and 10 bytes of padding
EXPECT_EQ(parsed, 21);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, bufSize);
// Total padding is the padding length byte and the padding bytes
EXPECT_EQ(callbacks_.paddingBytes, padding + 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, BasicRst) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicRstInvalidCode) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::_SPDY_INVALID_STREAM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicPing) {
upstreamCodec_.generatePingRequest(output_);
upstreamCodec_.generatePingReply(output_, 17);
uint64_t pingReq;
parse([&] (IOBuf* ingress) {
folly::io::Cursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
pingReq = c.read<uint64_t>();
});
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.recvPingRequest, pingReq);
EXPECT_EQ(callbacks_.recvPingReply, 17);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicWindow) {
// This test would fail if the codec had window state
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
upstreamCodec_.generateWindowUpdate(output_, 0, http2::kMaxWindowUpdateSize);
upstreamCodec_.generateWindowUpdate(output_, 1, 12);
upstreamCodec_.generateWindowUpdate(output_, 1, http2::kMaxWindowUpdateSize);
parse();
EXPECT_EQ(callbacks_.windowUpdateCalls, 4);
EXPECT_EQ(callbacks_.windowUpdates[0],
std::vector<uint32_t>({10, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.windowUpdates[1],
std::vector<uint32_t>({12, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, ZeroWindow) {
auto streamID = HTTPCodec::StreamID(1);
// First generate a frame with delta=1 so as to pass the checks, and then
// hack the frame so that delta=0 without modifying other checks
upstreamCodec_.generateWindowUpdate(output_, streamID, 1);
output_.trimEnd(http2::kFrameWindowUpdateSize);
QueueAppender appender(&output_, http2::kFrameWindowUpdateSize);
appender.writeBE<uint32_t>(0);
parse();
// This test doesn't ensure that RST_STREAM is generated
EXPECT_EQ(callbacks_.windowUpdateCalls, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::PROTOCOL_ERROR);
}
TEST_F(HTTP2CodecTest, BasicGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_DEATH_NO_CORE(upstreamCodec_.generateGoaway(
output_, 27, ErrorCode::ENHANCE_YOUR_CALM), ".*");
}
TEST_F(HTTP2CodecTest, DoubleGoaway) {
parse();
SetUpUpstreamTest();
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::NO_ERROR);
EXPECT_TRUE(downstreamCodec_.isWaitingToDrain());
EXPECT_TRUE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
downstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parseUpstream();
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_EQ(callbacks_.goaways, 2);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parse();
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(2));
}
TEST_F(HTTP2CodecTest, DoubleGoawayWithError) {
SetUpUpstreamTest();
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
auto ret = downstreamCodec_.generateGoaway(output_, 0,
ErrorCode::NO_ERROR);
EXPECT_EQ(ret, 0);
parseUpstream();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, GoawayHandling) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
// send request
HTTPMessage req = getGetRequest();
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
EXPECT_GT(size.uncompressed, 0);
parse();
callbacks_.expectMessage(true, 1, "/");
callbacks_.reset();
SetUpUpstreamTest();
// drain after this message
downstreamCodec_.generateGoaway(output_, 1, ErrorCode::NO_ERROR);
parseUpstream();
// upstream cannot generate id > 1
upstreamCodec_.generateHeader(output_, 3, req, false, &size);
EXPECT_EQ(size.uncompressed, 0);
upstreamCodec_.generateWindowUpdate(output_, 3, 100);
upstreamCodec_.generateBody(output_, 3, makeBuf(10), HTTPCodec::NoPadding,
false);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateEOM(output_, 3);
upstreamCodec_.generateRstStream(output_, 3, ErrorCode::CANCEL);
EXPECT_EQ(output_.chainLength(), 0);
// send a push promise that will be rejected by downstream
req.getHeaders().add("foomonkey", "george");
downstreamCodec_.generatePushPromise(output_, 2, req, 1, false, &size);
EXPECT_GT(size.uncompressed, 0);
HTTPMessage resp;
resp.setStatusCode(200);
// send a push response that will be ignored
downstreamCodec_.generateHeader(output_, 2, resp, false, &size);
// window update for push doesn't make any sense, but whatever
downstreamCodec_.generateWindowUpdate(output_, 2, 100);
downstreamCodec_.generateBody(output_, 2, makeBuf(10), HTTPCodec::NoPadding,
false);
writeFrameHeaderManual(output_, 20, (uint8_t)http2::FrameType::DATA, 0, 2);
output_.append(makeBuf(10));
// tell the upstream no pushing, and parse the first batch
IOBufQueue dummy;
upstreamCodec_.generateGoaway(dummy, 0, ErrorCode::NO_ERROR);
parseUpstream();
output_.append(makeBuf(10));
downstreamCodec_.generatePriority(output_, 2,
HTTPMessage::HTTPPriority(0, true, 1));
downstreamCodec_.generateEOM(output_, 2);
downstreamCodec_.generateRstStream(output_, 2, ErrorCode::CANCEL);
// send a response that will be accepted, headers should be ok
downstreamCodec_.generateHeader(output_, 1, resp, true, &size);
EXPECT_GT(size.uncompressed, 0);
// parse the remainder
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
}
TEST_F(HTTP2CodecTest, GoawayReply) {
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
}
TEST_F(HTTP2CodecTest, BasicSetting) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS, 37);
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 12345);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.maxStreams, 37);
EXPECT_EQ(callbacks_.windowSize, 12345);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsAck) {
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.settingsAcks, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadSettings) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 0xffffffff);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BadPushSettings) {
auto settings = downstreamCodec_.getEgressSettings();
settings->clearSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 0);
SetUpUpstreamTest();
parseUpstream([&] (IOBuf* ingress) {
EXPECT_EQ(ingress->computeChainDataLength(), http2::kFrameHeaderSize);
});
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
// Only way to disable push for downstreamCodec_ is to read
// ENABLE_PUSH:0 from client
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadSettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
// This sets the max decoder table size to 8k
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
callbacks_.reset();
// Attempt to set a new max table size. This is a no-op because the first,
// setting is unacknowledged. The upstream encoder will up the table size to
// 8k per the first settings frame and the HPACK codec will send a code to
// update the decoder.
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 4096);
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSizeEarlyShrink) {
// Lower size to 2k
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 2048);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
// Parsing SETTINGS ack updates upstream decoder to 2k
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
// downstream encoder will send TSU/2k
downstreamCodec_.generateHeader(output_, 1, resp);
// sets pending table size to 512, but doesn't update it yet
settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 512);
IOBufQueue tmp{IOBufQueue::cacheChainLength()};
upstreamCodec_.generateSettings(tmp);
// Previous code would barf here, since TSU/2k is a violation of the current
// max=512
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BasicPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.priority, pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderPriority) {
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
class DummyQueue: public HTTPCodec::PriorityQueue {
public:
DummyQueue() {}
~DummyQueue() override {}
void addPriorityNode(HTTPCodec::StreamID id, HTTPCodec::StreamID) override {
nodes_.push_back(id);
}
std::vector<HTTPCodec::StreamID> nodes_;
};
TEST_F(HTTP2CodecTest, VirtualNodes) {
DummyQueue queue;
uint8_t level = 30;
upstreamCodec_.addPriorityNodes(queue, output_, level);
EXPECT_TRUE(parse());
for (int i = 0; i < level; i++) {
EXPECT_EQ(queue.nodes_[i], upstreamCodec_.mapPriorityToDependency(i));
}
// Out-of-range priorites are mapped to the lowest level of virtual nodes.
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level));
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level + 1));
}
TEST_F(HTTP2CodecTest, BasicPushPromise) {
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
EXPECT_FALSE(downstreamCodec_.supportsPushTransactions());
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_TRUE(upstreamCodec_.supportsPushTransactions());
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
SetUpUpstreamTest();
HTTPCodec::StreamID assocStream = 7;
for (auto i = 0; i < 2; i++) {
// Push promise
HTTPCodec::StreamID pushStream = downstreamCodec_.createStream();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, pushStream, req, assocStream);
parseUpstream();
callbacks_.expectMessage(false, 2, "/"); // + host
EXPECT_EQ(callbacks_.assocStreamId, assocStream);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
callbacks_.reset();
// Actual reply headers
HTTPMessage resp;
resp.setStatusCode(200);
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "text/plain");
downstreamCodec_.generateHeader(output_, pushStream, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("text/plain", callbacks_.msg->getHeaders().getSingleOrEmpty(
HTTP_HEADER_CONTENT_TYPE));
callbacks_.reset();
}
}
TEST_F(HTTP2CodecTest, BadPushPromise) {
// ENABLE_PUSH is now 0 by default
SetUpUpstreamTest();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicCertificateRequest) {
uint16_t requestId = 17;
std::unique_ptr<folly::IOBuf> authRequest =
folly::IOBuf::copyBuffer("authRequestData");
upstreamCodec_.generateCertificateRequest(
output_, requestId, std::move(authRequest));
parse();
EXPECT_EQ(callbacks_.certificateRequests, 1);
EXPECT_EQ(callbacks_.lastCertRequestId, requestId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authRequestData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicCertificate) {
uint16_t certId = 17;
std::unique_ptr<folly::IOBuf> authenticator =
folly::IOBuf::copyBuffer("authenticatorData");
upstreamCodec_.generateCertificate(output_, certId, std::move(authenticator));
parse();
EXPECT_EQ(callbacks_.certificates, 1);
EXPECT_EQ(callbacks_.lastCertId, certId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authenticatorData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadServerPreface) {
output_.move();
downstreamCodec_.generateWindowUpdate(output_, 0, 10);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, Normal1024Continuation) {
HTTPMessage req = getGetRequest();
string bigval(8691, '!');
bigval.append(8691, ' ');
req.getHeaders().add("x-headr", bigval);
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(bigval, headers.getSingleOrEmpty("x-headr"));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settingsAcks, 1);
}
TEST_F(HTTP2CodecTest, StreamIdOverflow) {
HTTP2Codec codec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID streamId;
codec.setNextEgressStreamId(std::numeric_limits<int32_t>::max() - 10);
while (codec.isReusable()) {
streamId = codec.createStream();
}
EXPECT_EQ(streamId, std::numeric_limits<int32_t>::max() - 2);
}
TEST_F(HTTP2CodecTest, TestMultipleDifferentContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add(HTTP_HEADER_CONTENT_LENGTH, "300");
EXPECT_EQ(req.getHeaders().getNumberOfValues(HTTP_HEADER_CONTENT_LENGTH), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the request fails before the codec finishes parsing the headers
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.lastParseError->getHttpStatusCode(), 400);
}
TEST_F(HTTP2CodecTest, TestMultipleIdenticalContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add("content-length", "200");
EXPECT_EQ(req.getHeaders().getNumberOfValues("content-length"), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the headers parsing completes correctly
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.headersComplete, 1);
}
TEST_F(HTTP2CodecTest, CleartextUpgrade) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
HTTP2Codec::requestUpgrade(req);
EXPECT_EQ(req.getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE), "h2c");
EXPECT_TRUE(req.checkForHeaderToken(HTTP_HEADER_CONNECTION,
"Upgrade", false));
EXPECT_TRUE(req.checkForHeaderToken(
HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(), false));
EXPECT_GT(
req.getHeaders().getSingleOrEmpty(http2::kProtocolSettingsHeader).length(),
0);
}
TEST_F(HTTP2CodecTest, HTTP2SettingsSuccess) {
HTTPMessage req = getGetRequest("/guacamole");
// empty settings
req.getHeaders().add(http2::kProtocolSettingsHeader, "");
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
// real settings (overwrites empty)
HTTP2Codec::requestUpgrade(req);
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2SettingsFailure) {
HTTPMessage req = getGetRequest("/guacamole");
// no settings
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
HTTPHeaders& headers = req.getHeaders();
// Not base64_url settings
headers.set(http2::kProtocolSettingsHeader, "????");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
headers.set(http2::kProtocolSettingsHeader, "AAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Too big
string bigSettings((http2::kMaxFramePayloadLength + 1) * 4 / 3, 'A');
headers.set(http2::kProtocolSettingsHeader, bigSettings);
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Malformed (not a multiple of 6)
headers.set(http2::kProtocolSettingsHeader, "AAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Two headers
headers.set(http2::kProtocolSettingsHeader, "AAAAAAAA");
headers.add(http2::kProtocolSettingsHeader, "AAAAAAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2EnableConnect) {
SetUpUpstreamTest();
// egress settings have no connect settings.
auto ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
// enable connect settings, and check.
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL, 1);
ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
EXPECT_EQ(ws_enable->value, 1);
// generateSettings.
// pass the buffer to be parsed by the codec and check for ingress settings.
upstreamCodec_.generateSettings(output_);
parseUpstream();
EXPECT_EQ(1, upstreamCodec_.peerHasWebsockets());
}
TEST_F(HTTP2CodecTest, WebsocketUpgrade) {
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
EXPECT_TRUE(callbacks_.msg->isIngressWebsocketUpgrade());
EXPECT_NE(nullptr, callbacks_.msg->getUpgradeProtocol());
EXPECT_EQ(headers::kWebsocketString, *callbacks_.msg->getUpgradeProtocol());
}
TEST_F(HTTP2CodecTest, WebsocketBadHeader) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
};
vector<proxygen::compress::Header> optionalHeaders = {
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
int stream = 1;
for (size_t i = 0; i < optionalHeaders.size(); ++i, stream += 2) {
auto headers = reqHeaders;
headers.push_back(optionalHeaders[i]);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
false,
true);
parse();
}
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, optionalHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketDupProtocol) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> headers = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
1,
folly::none,
http2::kNoPadding,
false,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketIncorrectResponse) {
parse();
SetUpUpstreamTest();
parseUpstream();
output_.clear();
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
output_.clear();
HTTPMessage resp;
resp.setStatusCode(201);
resp.setStatusMessage("OK");
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TestAllEgressFrameTypeCallbacks) {
class CallbackTypeTracker {
std::set<uint8_t> types;
public:
void add(uint8_t, uint8_t type, uint64_t, uint16_t) {
types.insert(type);
}
bool isAllFrameTypesReceived() {
http2::FrameType expectedTypes[] = {
http2::FrameType::DATA,
http2::FrameType::HEADERS,
http2::FrameType::PRIORITY,
http2::FrameType::RST_STREAM,
http2::FrameType::SETTINGS,
http2::FrameType::PUSH_PROMISE,
http2::FrameType::PING,
http2::FrameType::GOAWAY,
http2::FrameType::WINDOW_UPDATE,
http2::FrameType::CONTINUATION,
http2::FrameType::EX_HEADERS,
};
for(http2::FrameType type: expectedTypes) {
EXPECT_TRUE(types.find(static_cast<uint8_t>(type)) != types.end())
<< "callback missing for type " << static_cast<uint8_t>(type);
}
return types.size() == (sizeof(expectedTypes)/sizeof(http2::FrameType));
}
};
CallbackTypeTracker callbackTypeTracker;
NiceMock<MockHTTPCodecCallback> mockCallback;
upstreamCodec_.setCallback(&mockCallback);
downstreamCodec_.setCallback(&mockCallback);
EXPECT_CALL(mockCallback, onGenerateFrameHeader(_, _, _, _)).
WillRepeatedly(Invoke(&callbackTypeTracker, &CallbackTypeTracker::add));
// DATA frame
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
HTTPMessage req = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
upstreamCodec_.generateSettings(output_);
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
upstreamCodec_.generatePingRequest(output_);
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true));
// Tests the continuation frame
req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
EXPECT_TRUE(callbackTypeTracker.isAllFrameTypesReceived());
}
TEST_F(HTTP2CodecTest, Trailers) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersWithPseudoHeaders) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TrailersNoBody) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, TrailersContinuation) {
HTTPMessage req = getGetRequest("/guacamole");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(callbacks_.msg->getTrailers(), nullptr);
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-trailer-2", "chicken-kyiv");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ("chicken-kyiv",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-2"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithNoData) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithPseudoHeaders) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, TrailersReplyContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.msg->getStatusCode(), 200);
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyMissingContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4132);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-388/cpp/bad_599_1 |
crossvul-cpp_data_good_599_1 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/test/HTTPParallelCodecTest.h>
#include <proxygen/lib/http/codec/test/MockHTTPCodec.h>
#include <folly/io/Cursor.h>
#include <proxygen/lib/http/codec/HTTP2Codec.h>
#include <proxygen/lib/http/codec/test/HTTP2FramerTest.h>
#include <proxygen/lib/http/HTTPHeaderSize.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include <folly/portability/GTest.h>
#include <folly/portability/GMock.h>
#include <random>
using namespace proxygen;
using namespace proxygen::compress;
using namespace folly;
using namespace folly::io;
using namespace std;
using namespace testing;
TEST(HTTP2CodecConstantsTest, HTTPContantsAreCommonHeaders) {
// The purpose of this test is to verify some basic assumptions that should
// never change but to make clear that the following http2 header constants
// map to the respective common headers. Should this test ever fail, the
// H2Codec would need to be updated in the corresponding places when creating
// compress/Header objects.
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kMethod),
HTTP_HEADER_COLON_METHOD);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kScheme),
HTTP_HEADER_COLON_SCHEME);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kPath),
HTTP_HEADER_COLON_PATH);
EXPECT_EQ(
HTTPCommonHeaders::hash(headers::kAuthority),
HTTP_HEADER_COLON_AUTHORITY);
EXPECT_EQ(HTTPCommonHeaders::hash(headers::kStatus),
HTTP_HEADER_COLON_STATUS);
}
class HTTP2CodecTest : public HTTPParallelCodecTest {
public:
HTTP2CodecTest()
:HTTPParallelCodecTest(upstreamCodec_, downstreamCodec_) {}
void SetUp() override {
HTTPParallelCodecTest::SetUp();
}
void testHeaderListSize(bool oversized);
void testFrameSizeLimit(bool oversized);
protected:
HTTP2Codec upstreamCodec_{TransportDirection::UPSTREAM};
HTTP2Codec downstreamCodec_{TransportDirection::DOWNSTREAM};
};
TEST_F(HTTP2CodecTest, IgnoreUnknownSettings) {
auto numSettings = downstreamCodec_.getIngressSettings()->getNumSettings();
std::deque<SettingPair> settings;
for (uint32_t i = 200; i < (200 + 1024); i++) {
settings.push_back(SettingPair(SettingsId(i), i));
}
http2::writeSettings(output_, settings);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(numSettings,
downstreamCodec_.getIngressSettings()->getNumSettings());
}
TEST_F(HTTP2CodecTest, NoExHeaders) {
// do not emit ENABLE_EX_HEADERS setting, if disabled
SetUpUpstreamTest();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.numSettings, 0);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
parseUpstream();
EXPECT_EQ(callbacks_.settings, 1);
// only 3 standard settings: HEADER_TABLE_SIZE, ENABLE_PUSH, MAX_FRAME_SIZE.
EXPECT_EQ(callbacks_.numSettings, 3);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersSetting) {
// disable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, EnableExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
auto ptr = downstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(nullptr, ptr);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
// attempt to enable EX_HEADERS on ingress
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 1)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(1, ptr->value);
EXPECT_EQ(true, downstreamCodec_.supportsExTransactions());
// attempt to disable EX_HEADERS on ingress
callbacks_.reset();
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 0)});
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
ptr = downstreamCodec_.getIngressSettings()->getSetting(
SettingsId::ENABLE_EX_HEADERS);
EXPECT_EQ(0, ptr->value);
EXPECT_EQ(false, downstreamCodec_.supportsExTransactions());
}
TEST_F(HTTP2CodecTest, InvalidExHeadersSetting) {
// enable EX_HEADERS on egress
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
// attempt to set a invalid ENABLE_EX_HEADERS value
http2::writeSettings(output_,
{SettingPair(SettingsId::ENABLE_EX_HEADERS, 110)});
parse();
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeader) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, RequestFromServer) {
// this is to test EX_HEADERS frame, which carrys the HTTP request initiated
// by server side
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
SetUpUpstreamTest();
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("tab-hdr", "coolio\tv2");
// Connection header will get dropped
req.getHeaders().add(HTTP_HEADER_CONNECTION, "Love");
req.setSecure(true);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
upstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true),
true);
parseUpstream();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
callbacks_.expectMessage(true, 3, "/guacamole");
EXPECT_TRUE(callbacks_.msg->isSecure());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ("coolio\tv2", headers.getSingleOrEmpty("tab-hdr"));
EXPECT_EQ("www.foo.com", headers.getSingleOrEmpty(HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, ResponseFromClient) {
// this is to test EX_HEADERS frame, which carrys the HTTP response replied by
// client side
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, resp,
HTTPCodec::ExAttributes(controlStream, true), true);
parse();
EXPECT_EQ(controlStream, callbacks_.controlStreamId);
EXPECT_TRUE(callbacks_.isUnidirectional);
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, ExHeadersWithPriority) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 1);
proxygen::http2::writeSettings(
output_, {{proxygen::SettingsId::ENABLE_EX_HEADERS, 1}});
auto req = getGetRequest();
auto pri = HTTPMessage::HTTPPriority(0, false, 7);
req.setHTTP2Priority(pri);
upstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.msg->getHTTP2Priority(), pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, IgnoreExHeadersIfNotEnabled) {
downstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_EX_HEADERS, 0);
HTTPMessage req = getGetRequest("/guacamole");
downstreamCodec_.generateExHeader(output_, 3, req,
HTTPCodec::ExAttributes(1, true));
parse();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaders) {
static const std::string v1("GET");
static const std::string v2("/");
static const std::string v3("http");
static const std::string v4("foo.com");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 7);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPseudoHeaders) {
static const std::string v1("POST");
static const std::string v2("http");
static const std::string n3("foo");
static const std::string v3("bar");
static const std::string v4("/");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kScheme, v2),
Header::makeHeaderForTest(n3, v3),
Header::makeHeaderForTest(headers::kPath, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
std::vector<proxygen::compress::Header> allHeaders = reqHeaders;
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderValues) {
static const std::string v1("--1");
static const std::string v2("\13\10protocol-attack");
static const std::string v3("\13");
static const std::string v4("abc.com\\13\\10");
static const vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kPath, v2),
Header::makeHeaderForTest(headers::kScheme, v3),
Header::makeHeaderForTest(headers::kAuthority, v4),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < reqHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders;
allHeaders.push_back(reqHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 4);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
/**
* Ingress bytes with an empty header name
*/
const uint8_t kBufEmptyHeader[] = {
0x00, 0x00, 0x1d, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x82,
0x87, 0x44, 0x87, 0x62, 0x6b, 0x46, 0x41, 0xd2, 0x7a, 0x0b,
0x41, 0x89, 0xf1, 0xe3, 0xc2, 0xf2, 0x9c, 0xeb, 0x90, 0xf4,
0xff, 0x40, 0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7
};
TEST_F(HTTP2CodecTest, EmptyHeaderName) {
output_.append(IOBuf::copyBuffer(kBufEmptyHeader, sizeof(kBufEmptyHeader)));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicConnect) {
std::string authority = "myhost:1234";
HTTPMessage request;
request.setMethod(HTTPMethod::CONNECT);
request.getHeaders().add(proxygen::HTTP_HEADER_HOST, authority);
upstreamCodec_.generateHeader(output_, 1, request, false /* eom */);
parse();
callbacks_.expectMessage(false, 1, "");
EXPECT_EQ(HTTPMethod::CONNECT, callbacks_.msg->getMethod());
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(authority, headers.getSingleOrEmpty(proxygen::HTTP_HEADER_HOST));
}
TEST_F(HTTP2CodecTest, BadConnect) {
std::string v1 = "CONNECT";
std::string v2 = "somehost:576";
std::vector<proxygen::compress::Header> goodHeaders = {
Header::makeHeaderForTest(headers::kMethod, v1),
Header::makeHeaderForTest(headers::kAuthority, v2),
};
// See https://tools.ietf.org/html/rfc7540#section-8.3
std::string v3 = "/foobar";
std::vector<proxygen::compress::Header> badHeaders = {
Header::makeHeaderForTest(headers::kScheme, headers::kHttp),
Header::makeHeaderForTest(headers::kPath, v3),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID stream = 1;
for (size_t i = 0; i < badHeaders.size(); i++, stream += 2) {
auto allHeaders = goodHeaders;
allHeaders.push_back(badHeaders[i]);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, badHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
void HTTP2CodecTest::testHeaderListSize(bool oversized) {
if (oversized) {
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
}
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
req.getHeaders().add("x-long-long-header",
"supercalafragalisticexpialadoshus");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
void HTTP2CodecTest::testFrameSizeLimit(bool oversized) {
HTTPMessage req = getBigGetRequest("/guacamole");
auto settings = downstreamCodec_.getEgressSettings();
parse(); // consume preface
if (oversized) {
// trick upstream for sending a 2x bigger HEADERS frame
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin * 2);
downstreamCodec_.generateSettings(output_);
parseUpstream();
}
settings->setSetting(SettingsId::MAX_FRAME_SIZE,
http2::kMaxFramePayloadLengthMin);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.headersComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.messageComplete, oversized ? 0 : 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, oversized ? 1 : 0);
}
TEST_F(HTTP2CodecTest, NormalSizeHeader) {
testHeaderListSize(false);
}
TEST_F(HTTP2CodecTest, OversizedHeader) {
testHeaderListSize(true);
}
TEST_F(HTTP2CodecTest, NormalSizeFrame) {
testFrameSizeLimit(false);
}
TEST_F(HTTP2CodecTest, OversizedFrame) {
testFrameSizeLimit(true);
}
TEST_F(HTTP2CodecTest, BigHeaderCompressed) {
SetUpUpstreamTest();
auto settings = downstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_HEADER_LIST_SIZE, 37);
downstreamCodec_.generateSettings(output_);
parseUpstream();
SetUp();
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// session error
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicHeaderReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
// HTTP/2 doesnt support serialization - instead you get the default
EXPECT_EQ("OK", callbacks_.msg->getStatusMessage());
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadHeadersReply) {
static const std::string v1("200");
static const vector<proxygen::compress::Header> respHeaders = {
Header::makeHeaderForTest(headers::kStatus, v1),
};
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
HTTPCodec::StreamID stream = 1;
// missing fields (missing authority is OK)
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
allHeaders.erase(allHeaders.begin() + i);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
// dup fields
std::string v("foomonkey");
for (size_t i = 0; i < respHeaders.size(); i++, stream += 2) {
std::vector<proxygen::compress::Header> allHeaders = respHeaders;
auto h = allHeaders[i];
h.value = &v;
allHeaders.push_back(h);
auto encodedHeaders = headerCodec.encode(allHeaders);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
true,
true);
}
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, Cookies) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add("Cookie", "chocolate-chip=1");
req.getHeaders().add("Cookie", "rainbow-chip=2");
req.getHeaders().add("Cookie", "butterscotch=3");
req.getHeaders().add("Cookie", "oatmeal-raisin=4");
req.setSecure(true);
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, "/guacamole");
EXPECT_EQ(callbacks_.msg->getCookie("chocolate-chip"), "1");
EXPECT_EQ(callbacks_.msg->getCookie("rainbow-chip"), "2");
EXPECT_EQ(callbacks_.msg->getCookie("butterscotch"), "3");
EXPECT_EQ(callbacks_.msg->getCookie("oatmeal-raisin"), "4");
}
TEST_F(HTTP2CodecTest, BasicContinuation) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicContinuationEndStream) {
// CONTINUATION with END_STREAM flag set on the preceding HEADERS frame
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
callbacks_.expectMessage(true, -1, "/");
#ifndef NDEBUG
EXPECT_GT(downstreamCodec_.getReceivedFrameCount(), 1);
#endif
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadContinuation) {
// CONTINUATION with no preceding HEADERS
auto fakeHeaders = makeBuf(5);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, MissingContinuation) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, MissingContinuationBadFrame) {
IOBufQueue output(IOBufQueue::cacheChainLength());
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
// insert an invalid frame
auto frame = makeBuf(http2::kFrameHeaderSize + 4134);
*((uint32_t *)frame->writableData()) = 0xfa000000;
output_.append(std::move(frame));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, BadContinuationStream) {
HTTPMessage req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req);
// empirically determined the size of continuation frame, and fake it
output_.trimEnd(http2::kFrameHeaderSize + 4134);
auto fakeHeaders = makeBuf(4134);
http2::writeContinuation(output_, 3, true, std::move(fakeHeaders));
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, FrameTooLarge) {
writeFrameHeaderManual(output_, 1 << 15, 0, 0, 1);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_TRUE(callbacks_.lastParseError->hasCodecStatusCode());
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::FRAME_SIZE_ERROR);
}
TEST_F(HTTP2CodecTest, UnknownFrameType) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// unknown frame type 17
writeFrameHeaderManual(output_, 17, 37, 0, 1);
output_.append("wicked awesome!!!");
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, 2, ""); // + host
}
TEST_F(HTTP2CodecTest, JunkAfterConnError) {
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
// write headers frame for stream 0
writeFrameHeaderManual(output_, 0, (uint8_t)http2::FrameType::HEADERS, 0, 0);
// now write a valid headers frame, should never be parsed
upstreamCodec_.generateHeader(output_, 1, req);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicData) {
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), data);
}
TEST_F(HTTP2CodecTest, LongData) {
// Hack the max frame size artificially low
HTTPSettings* settings = (HTTPSettings*)upstreamCodec_.getIngressSettings();
settings->setSetting(SettingsId::MAX_FRAME_SIZE, 16);
auto buf = makeBuf(100);
upstreamCodec_.generateBody(output_, 1, buf->clone(), HTTPCodec::NoPadding,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 7);
EXPECT_EQ(callbacks_.bodyLength, 100);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, MalformedPaddingLength) {
const uint8_t badInput[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x7e, 0x00, 0x6f, 0x6f, 0x6f, 0x6f,
// The padding length byte below is 0x82 (130
// in decimal) which is greater than the length
// specified by the header's length field, 126
0x01, 0x82, 0x87, 0x44, 0x87, 0x92, 0x97, 0x92,
0x92, 0x92, 0x7a, 0x0b, 0x41, 0x89, 0xf1, 0xe3,
0xc0, 0xf2, 0x9c, 0xdd, 0x90, 0xf4, 0xff, 0x40,
0x80, 0x84, 0x2d, 0x35, 0xa7, 0xd7};
output_.clear();
output_.append(badInput, sizeof(badInput));
EXPECT_EQ(output_.chainLength(), sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, MalformedPadding) {
const uint8_t badInput[] = {
0x00, 0x00, 0x0d, 0x01, 0xbe, 0x63, 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x73,
0x00, 0x00, 0x06, 0x08, 0x72, 0x00, 0x24, 0x00, 0xfa, 0x4d, 0x0d
};
output_.append(badInput, sizeof(badInput));
EXPECT_FALSE(parse());
}
TEST_F(HTTP2CodecTest, NoAppByte) {
const uint8_t noAppByte[] = {0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54,
0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
0x00, 0x00, 0x56, 0x00, 0x5d, 0x00, 0x00, 0x00,
0x01, 0x55, 0x00};
output_.clear();
output_.append(noAppByte, sizeof(noAppByte));
EXPECT_EQ(output_.chainLength(), sizeof(noAppByte));
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataOnFrameHeaderCall) {
using namespace testing;
NiceMock<MockHTTPCodecCallback> mockCallback;
EXPECT_CALL(mockCallback, onFrameHeader(_, _, _, _, _));
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
downstreamCodec_.setCallback(&mockCallback);
auto ingress = output_.move();
ingress->coalesce();
// Copy partial byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
downstreamCodec_.onIngress(*ingress1);
}
TEST_F(HTTP2CodecTest, DataFramePartialDataWithNoAppByte) {
const size_t bufSize = 10;
auto buf = makeBuf(bufSize);
const size_t padding = 10;
upstreamCodec_.generateBody(output_, 1, buf->clone(), padding, true);
EXPECT_EQ(output_.chainLength(), 54);
auto ingress = output_.move();
ingress->coalesce();
// Copy up to the padding length byte to a new buffer
auto ingress1 = IOBuf::copyBuffer(ingress->data(), 34);
size_t parsed = downstreamCodec_.onIngress(*ingress1);
// The 34th byte is the padding length byte which should not be parsed
EXPECT_EQ(parsed, 33);
// Copy from the padding length byte to the end
auto ingress2 = IOBuf::copyBuffer(ingress->data() + 33, 21);
parsed = downstreamCodec_.onIngress(*ingress2);
// The padding length byte should be parsed this time along with 10 bytes of
// application data and 10 bytes of padding
EXPECT_EQ(parsed, 21);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, bufSize);
// Total padding is the padding length byte and the padding bytes
EXPECT_EQ(callbacks_.paddingBytes, padding + 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), buf->moveToFbString());
}
TEST_F(HTTP2CodecTest, BasicRst) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicRstInvalidCode) {
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::_SPDY_INVALID_STREAM);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.aborts, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicPing) {
upstreamCodec_.generatePingRequest(output_);
upstreamCodec_.generatePingReply(output_, 17);
uint64_t pingReq;
parse([&] (IOBuf* ingress) {
folly::io::Cursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
pingReq = c.read<uint64_t>();
});
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.recvPingRequest, pingReq);
EXPECT_EQ(callbacks_.recvPingReply, 17);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicWindow) {
// This test would fail if the codec had window state
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
upstreamCodec_.generateWindowUpdate(output_, 0, http2::kMaxWindowUpdateSize);
upstreamCodec_.generateWindowUpdate(output_, 1, 12);
upstreamCodec_.generateWindowUpdate(output_, 1, http2::kMaxWindowUpdateSize);
parse();
EXPECT_EQ(callbacks_.windowUpdateCalls, 4);
EXPECT_EQ(callbacks_.windowUpdates[0],
std::vector<uint32_t>({10, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.windowUpdates[1],
std::vector<uint32_t>({12, http2::kMaxWindowUpdateSize}));
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, ZeroWindow) {
auto streamID = HTTPCodec::StreamID(1);
// First generate a frame with delta=1 so as to pass the checks, and then
// hack the frame so that delta=0 without modifying other checks
upstreamCodec_.generateWindowUpdate(output_, streamID, 1);
output_.trimEnd(http2::kFrameWindowUpdateSize);
QueueAppender appender(&output_, http2::kFrameWindowUpdateSize);
appender.writeBE<uint32_t>(0);
parse();
// This test doesn't ensure that RST_STREAM is generated
EXPECT_EQ(callbacks_.windowUpdateCalls, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.lastParseError->getCodecStatusCode(),
ErrorCode::PROTOCOL_ERROR);
}
TEST_F(HTTP2CodecTest, BasicGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadGoaway) {
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_DEATH_NO_CORE(upstreamCodec_.generateGoaway(
output_, 27, ErrorCode::ENHANCE_YOUR_CALM), ".*");
}
TEST_F(HTTP2CodecTest, DoubleGoaway) {
parse();
SetUpUpstreamTest();
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::NO_ERROR);
EXPECT_TRUE(downstreamCodec_.isWaitingToDrain());
EXPECT_TRUE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
downstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parseUpstream();
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(2));
EXPECT_EQ(callbacks_.goaways, 2);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
EXPECT_TRUE(upstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(upstreamCodec_.isStreamIngressEgressAllowed(2));
parse();
EXPECT_TRUE(downstreamCodec_.isStreamIngressEgressAllowed(0));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(1));
EXPECT_FALSE(downstreamCodec_.isStreamIngressEgressAllowed(2));
}
TEST_F(HTTP2CodecTest, DoubleGoawayWithError) {
SetUpUpstreamTest();
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
downstreamCodec_.generateGoaway(output_, std::numeric_limits<int32_t>::max(),
ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
EXPECT_FALSE(downstreamCodec_.isWaitingToDrain());
EXPECT_FALSE(downstreamCodec_.isReusable());
auto ret = downstreamCodec_.generateGoaway(output_, 0,
ErrorCode::NO_ERROR);
EXPECT_EQ(ret, 0);
parseUpstream();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "debugData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, GoawayHandling) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
// send request
HTTPMessage req = getGetRequest();
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
EXPECT_GT(size.uncompressed, 0);
parse();
callbacks_.expectMessage(true, 1, "/");
callbacks_.reset();
SetUpUpstreamTest();
// drain after this message
downstreamCodec_.generateGoaway(output_, 1, ErrorCode::NO_ERROR);
parseUpstream();
// upstream cannot generate id > 1
upstreamCodec_.generateHeader(output_, 3, req, false, &size);
EXPECT_EQ(size.uncompressed, 0);
upstreamCodec_.generateWindowUpdate(output_, 3, 100);
upstreamCodec_.generateBody(output_, 3, makeBuf(10), HTTPCodec::NoPadding,
false);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateEOM(output_, 3);
upstreamCodec_.generateRstStream(output_, 3, ErrorCode::CANCEL);
EXPECT_EQ(output_.chainLength(), 0);
// send a push promise that will be rejected by downstream
req.getHeaders().add("foomonkey", "george");
downstreamCodec_.generatePushPromise(output_, 2, req, 1, false, &size);
EXPECT_GT(size.uncompressed, 0);
HTTPMessage resp;
resp.setStatusCode(200);
// send a push response that will be ignored
downstreamCodec_.generateHeader(output_, 2, resp, false, &size);
// window update for push doesn't make any sense, but whatever
downstreamCodec_.generateWindowUpdate(output_, 2, 100);
downstreamCodec_.generateBody(output_, 2, makeBuf(10), HTTPCodec::NoPadding,
false);
writeFrameHeaderManual(output_, 20, (uint8_t)http2::FrameType::DATA, 0, 2);
output_.append(makeBuf(10));
// tell the upstream no pushing, and parse the first batch
IOBufQueue dummy;
upstreamCodec_.generateGoaway(dummy, 0, ErrorCode::NO_ERROR);
parseUpstream();
output_.append(makeBuf(10));
downstreamCodec_.generatePriority(output_, 2,
HTTPMessage::HTTPPriority(0, true, 1));
downstreamCodec_.generateEOM(output_, 2);
downstreamCodec_.generateRstStream(output_, 2, ErrorCode::CANCEL);
// send a response that will be accepted, headers should be ok
downstreamCodec_.generateHeader(output_, 1, resp, true, &size);
EXPECT_GT(size.uncompressed, 0);
// parse the remainder
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
}
TEST_F(HTTP2CodecTest, GoawayReply) {
upstreamCodec_.generateGoaway(output_, 0, ErrorCode::NO_ERROR);
parse();
EXPECT_EQ(callbacks_.goaways, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
downstreamCodec_.generateHeader(output_, 1, resp);
downstreamCodec_.generateEOM(output_, 1);
parseUpstream();
callbacks_.expectMessage(true, 1, 200);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
}
TEST_F(HTTP2CodecTest, BasicSetting) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::MAX_CONCURRENT_STREAMS, 37);
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 12345);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.maxStreams, 37);
EXPECT_EQ(callbacks_.windowSize, 12345);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsAck) {
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.settingsAcks, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadSettings) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 0xffffffff);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BadPushSettings) {
auto settings = downstreamCodec_.getEgressSettings();
settings->clearSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 0);
SetUpUpstreamTest();
parseUpstream([&] (IOBuf* ingress) {
EXPECT_EQ(ingress->computeChainDataLength(), http2::kFrameHeaderSize);
});
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
// Only way to disable push for downstreamCodec_ is to read
// ENABLE_PUSH:0 from client
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BadSettingsTableSize) {
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 8192);
// This sets the max decoder table size to 8k
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
callbacks_.reset();
// Attempt to set a new max table size. This is a no-op because the first,
// setting is unacknowledged. The upstream encoder will up the table size to
// 8k per the first settings frame and the HPACK codec will send a code to
// update the decoder.
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 4096);
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
}
TEST_F(HTTP2CodecTest, SettingsTableSizeEarlyShrink) {
// Lower size to 2k
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 2048);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_EQ(callbacks_.settings, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
downstreamCodec_.generateSettingsAck(output_);
// Parsing SETTINGS ack updates upstream decoder to 2k
parseUpstream();
callbacks_.reset();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
SetUpUpstreamTest();
// downstream encoder will send TSU/2k
downstreamCodec_.generateHeader(output_, 1, resp);
// sets pending table size to 512, but doesn't update it yet
settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::HEADER_TABLE_SIZE, 512);
IOBufQueue tmp{IOBufQueue::cacheChainLength()};
upstreamCodec_.generateSettings(tmp);
// Previous code would barf here, since TSU/2k is a violation of the current
// max=512
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
}
TEST_F(HTTP2CodecTest, BasicPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
EXPECT_TRUE(parse());
EXPECT_EQ(callbacks_.priority, pri);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadHeaderPriority) {
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, DuplicateBadHeaderPriority) {
// Sent an initial header with a circular dependency
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// Hack ingress with circular dependency.
EXPECT_TRUE(parse([&](IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
// On the same stream, send another request.
HTTPMessage nextRequest = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, nextRequest, true /* eom */);
parse();
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadPriority) {
auto pri = HTTPMessage::HTTPPriority(0, true, 1);
upstreamCodec_.generatePriority(output_, 1, pri);
// hack ingress with cirular dep
EXPECT_TRUE(parse([&] (IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
class DummyQueue: public HTTPCodec::PriorityQueue {
public:
DummyQueue() {}
~DummyQueue() override {}
void addPriorityNode(HTTPCodec::StreamID id, HTTPCodec::StreamID) override {
nodes_.push_back(id);
}
std::vector<HTTPCodec::StreamID> nodes_;
};
TEST_F(HTTP2CodecTest, VirtualNodes) {
DummyQueue queue;
uint8_t level = 30;
upstreamCodec_.addPriorityNodes(queue, output_, level);
EXPECT_TRUE(parse());
for (int i = 0; i < level; i++) {
EXPECT_EQ(queue.nodes_[i], upstreamCodec_.mapPriorityToDependency(i));
}
// Out-of-range priorites are mapped to the lowest level of virtual nodes.
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level));
EXPECT_EQ(queue.nodes_[level - 1],
upstreamCodec_.mapPriorityToDependency(level + 1));
}
TEST_F(HTTP2CodecTest, BasicPushPromise) {
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_FALSE(upstreamCodec_.supportsPushTransactions());
EXPECT_FALSE(downstreamCodec_.supportsPushTransactions());
auto settings = upstreamCodec_.getEgressSettings();
settings->setSetting(SettingsId::ENABLE_PUSH, 1);
upstreamCodec_.generateSettings(output_);
parse();
EXPECT_TRUE(upstreamCodec_.supportsPushTransactions());
EXPECT_TRUE(downstreamCodec_.supportsPushTransactions());
SetUpUpstreamTest();
HTTPCodec::StreamID assocStream = 7;
for (auto i = 0; i < 2; i++) {
// Push promise
HTTPCodec::StreamID pushStream = downstreamCodec_.createStream();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, pushStream, req, assocStream);
parseUpstream();
callbacks_.expectMessage(false, 2, "/"); // + host
EXPECT_EQ(callbacks_.assocStreamId, assocStream);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ("coolio", headers.getSingleOrEmpty(HTTP_HEADER_USER_AGENT));
callbacks_.reset();
// Actual reply headers
HTTPMessage resp;
resp.setStatusCode(200);
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "text/plain");
downstreamCodec_.generateHeader(output_, pushStream, resp);
parseUpstream();
callbacks_.expectMessage(false, 2, 200);
EXPECT_EQ(callbacks_.headersCompleteId, pushStream);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("text/plain", callbacks_.msg->getHeaders().getSingleOrEmpty(
HTTP_HEADER_CONTENT_TYPE));
callbacks_.reset();
}
}
TEST_F(HTTP2CodecTest, BadPushPromise) {
// ENABLE_PUSH is now 0 by default
SetUpUpstreamTest();
HTTPMessage req = getGetRequest();
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, BasicCertificateRequest) {
uint16_t requestId = 17;
std::unique_ptr<folly::IOBuf> authRequest =
folly::IOBuf::copyBuffer("authRequestData");
upstreamCodec_.generateCertificateRequest(
output_, requestId, std::move(authRequest));
parse();
EXPECT_EQ(callbacks_.certificateRequests, 1);
EXPECT_EQ(callbacks_.lastCertRequestId, requestId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authRequestData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BasicCertificate) {
uint16_t certId = 17;
std::unique_ptr<folly::IOBuf> authenticator =
folly::IOBuf::copyBuffer("authenticatorData");
upstreamCodec_.generateCertificate(output_, certId, std::move(authenticator));
parse();
EXPECT_EQ(callbacks_.certificates, 1);
EXPECT_EQ(callbacks_.lastCertId, certId);
EXPECT_EQ(callbacks_.data.move()->moveToFbString(), "authenticatorData");
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, BadServerPreface) {
output_.move();
downstreamCodec_.generateWindowUpdate(output_, 0, 10);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.assocStreamId, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
}
TEST_F(HTTP2CodecTest, Normal1024Continuation) {
HTTPMessage req = getGetRequest();
string bigval(8691, '!');
bigval.append(8691, ' ');
req.getHeaders().add("x-headr", bigval);
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req);
parse();
callbacks_.expectMessage(false, -1, "/");
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_EQ(bigval, headers.getSingleOrEmpty("x-headr"));
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
upstreamCodec_.generateSettingsAck(output_);
parse();
EXPECT_EQ(callbacks_.settingsAcks, 1);
}
TEST_F(HTTP2CodecTest, StreamIdOverflow) {
HTTP2Codec codec(TransportDirection::UPSTREAM);
HTTPCodec::StreamID streamId;
codec.setNextEgressStreamId(std::numeric_limits<int32_t>::max() - 10);
while (codec.isReusable()) {
streamId = codec.createStream();
}
EXPECT_EQ(streamId, std::numeric_limits<int32_t>::max() - 2);
}
TEST_F(HTTP2CodecTest, TestMultipleDifferentContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add(HTTP_HEADER_CONTENT_LENGTH, "300");
EXPECT_EQ(req.getHeaders().getNumberOfValues(HTTP_HEADER_CONTENT_LENGTH), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the request fails before the codec finishes parsing the headers
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.lastParseError->getHttpStatusCode(), 400);
}
TEST_F(HTTP2CodecTest, TestMultipleIdenticalContentLengthHeaders) {
// Generate a POST request with two Content-Length headers
// NOTE: getPostRequest already adds the content-length
HTTPMessage req = getPostRequest();
req.getHeaders().add("content-length", "200");
EXPECT_EQ(req.getHeaders().getNumberOfValues("content-length"), 2);
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
parse();
// Check that the headers parsing completes correctly
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.headersComplete, 1);
}
TEST_F(HTTP2CodecTest, CleartextUpgrade) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
HTTP2Codec::requestUpgrade(req);
EXPECT_EQ(req.getHeaders().getSingleOrEmpty(HTTP_HEADER_UPGRADE), "h2c");
EXPECT_TRUE(req.checkForHeaderToken(HTTP_HEADER_CONNECTION,
"Upgrade", false));
EXPECT_TRUE(req.checkForHeaderToken(
HTTP_HEADER_CONNECTION,
http2::kProtocolSettingsHeader.c_str(), false));
EXPECT_GT(
req.getHeaders().getSingleOrEmpty(http2::kProtocolSettingsHeader).length(),
0);
}
TEST_F(HTTP2CodecTest, HTTP2SettingsSuccess) {
HTTPMessage req = getGetRequest("/guacamole");
// empty settings
req.getHeaders().add(http2::kProtocolSettingsHeader, "");
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
// real settings (overwrites empty)
HTTP2Codec::requestUpgrade(req);
EXPECT_TRUE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2SettingsFailure) {
HTTPMessage req = getGetRequest("/guacamole");
// no settings
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
HTTPHeaders& headers = req.getHeaders();
// Not base64_url settings
headers.set(http2::kProtocolSettingsHeader, "????");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
headers.set(http2::kProtocolSettingsHeader, "AAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Too big
string bigSettings((http2::kMaxFramePayloadLength + 1) * 4 / 3, 'A');
headers.set(http2::kProtocolSettingsHeader, bigSettings);
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Malformed (not a multiple of 6)
headers.set(http2::kProtocolSettingsHeader, "AAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
// Two headers
headers.set(http2::kProtocolSettingsHeader, "AAAAAAAA");
headers.add(http2::kProtocolSettingsHeader, "AAAAAAAA");
EXPECT_FALSE(downstreamCodec_.onIngressUpgradeMessage(req));
}
TEST_F(HTTP2CodecTest, HTTP2EnableConnect) {
SetUpUpstreamTest();
// egress settings have no connect settings.
auto ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
// enable connect settings, and check.
upstreamCodec_.getEgressSettings()->setSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL, 1);
ws_enable = upstreamCodec_.getEgressSettings()->getSetting(
SettingsId::ENABLE_CONNECT_PROTOCOL);
EXPECT_EQ(ws_enable->value, 1);
// generateSettings.
// pass the buffer to be parsed by the codec and check for ingress settings.
upstreamCodec_.generateSettings(output_);
parseUpstream();
EXPECT_EQ(1, upstreamCodec_.peerHasWebsockets());
}
TEST_F(HTTP2CodecTest, WebsocketUpgrade) {
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
EXPECT_TRUE(callbacks_.msg->isIngressWebsocketUpgrade());
EXPECT_NE(nullptr, callbacks_.msg->getUpgradeProtocol());
EXPECT_EQ(headers::kWebsocketString, *callbacks_.msg->getUpgradeProtocol());
}
TEST_F(HTTP2CodecTest, WebsocketBadHeader) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> reqHeaders = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
};
vector<proxygen::compress::Header> optionalHeaders = {
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
int stream = 1;
for (size_t i = 0; i < optionalHeaders.size(); ++i, stream += 2) {
auto headers = reqHeaders;
headers.push_back(optionalHeaders[i]);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
stream,
folly::none,
http2::kNoPadding,
false,
true);
parse();
}
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, optionalHeaders.size());
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketDupProtocol) {
const std::string kConnect{"CONNECT"};
const std::string kWebsocketPath{"/websocket"};
const std::string kSchemeHttps{"https"};
vector<proxygen::compress::Header> headers = {
Header::makeHeaderForTest(headers::kMethod, kConnect),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kProtocol, headers::kWebsocketString),
Header::makeHeaderForTest(headers::kPath, kWebsocketPath),
Header::makeHeaderForTest(headers::kScheme, kSchemeHttps),
};
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
auto encodedHeaders = headerCodec.encode(headers);
http2::writeHeaders(output_,
std::move(encodedHeaders),
1,
folly::none,
http2::kNoPadding,
false,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 0);
EXPECT_EQ(callbacks_.headersComplete, 0);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, WebsocketIncorrectResponse) {
parse();
SetUpUpstreamTest();
parseUpstream();
output_.clear();
HTTPMessage req = getGetRequest("/apples");
req.setSecure(true);
req.setEgressWebsocketUpgrade();
upstreamCodec_.generateHeader(output_, 1, req, false);
parse();
output_.clear();
HTTPMessage resp;
resp.setStatusCode(201);
resp.setStatusMessage("OK");
downstreamCodec_.generateHeader(output_, 1, resp);
parseUpstream();
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TestAllEgressFrameTypeCallbacks) {
class CallbackTypeTracker {
std::set<uint8_t> types;
public:
void add(uint8_t, uint8_t type, uint64_t, uint16_t) {
types.insert(type);
}
bool isAllFrameTypesReceived() {
http2::FrameType expectedTypes[] = {
http2::FrameType::DATA,
http2::FrameType::HEADERS,
http2::FrameType::PRIORITY,
http2::FrameType::RST_STREAM,
http2::FrameType::SETTINGS,
http2::FrameType::PUSH_PROMISE,
http2::FrameType::PING,
http2::FrameType::GOAWAY,
http2::FrameType::WINDOW_UPDATE,
http2::FrameType::CONTINUATION,
http2::FrameType::EX_HEADERS,
};
for(http2::FrameType type: expectedTypes) {
EXPECT_TRUE(types.find(static_cast<uint8_t>(type)) != types.end())
<< "callback missing for type " << static_cast<uint8_t>(type);
}
return types.size() == (sizeof(expectedTypes)/sizeof(http2::FrameType));
}
};
CallbackTypeTracker callbackTypeTracker;
NiceMock<MockHTTPCodecCallback> mockCallback;
upstreamCodec_.setCallback(&mockCallback);
downstreamCodec_.setCallback(&mockCallback);
EXPECT_CALL(mockCallback, onGenerateFrameHeader(_, _, _, _)).
WillRepeatedly(Invoke(&callbackTypeTracker, &CallbackTypeTracker::add));
// DATA frame
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(output_, 2, std::move(buf),
HTTPCodec::NoPadding, true);
HTTPHeaderSize size;
size.uncompressed = size.compressed = 0;
HTTPMessage req = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true, &size);
upstreamCodec_.generatePriority(output_, 3,
HTTPMessage::HTTPPriority(0, true, 1));
upstreamCodec_.generateRstStream(output_, 2, ErrorCode::ENHANCE_YOUR_CALM);
upstreamCodec_.generateSettings(output_);
downstreamCodec_.generatePushPromise(output_, 2, req, 1);
upstreamCodec_.generatePingRequest(output_);
std::unique_ptr<folly::IOBuf> debugData =
folly::IOBuf::copyBuffer("debugData");
upstreamCodec_.generateGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM,
std::move(debugData));
upstreamCodec_.generateWindowUpdate(output_, 0, 10);
HTTPCodec::StreamID stream = folly::Random::rand32(10, 1024) * 2;
HTTPCodec::StreamID controlStream = folly::Random::rand32(10, 1024) * 2 + 1;
downstreamCodec_.generateExHeader(output_, stream, req,
HTTPCodec::ExAttributes(controlStream, true));
// Tests the continuation frame
req = getBigGetRequest();
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
EXPECT_TRUE(callbackTypeTracker.isAllFrameTypesReceived());
}
TEST_F(HTTP2CodecTest, Trailers) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersWithPseudoHeaders) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
upstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false /* eom */);
HPACKCodec headerCodec(TransportDirection::UPSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 1);
}
TEST_F(HTTP2CodecTest, TrailersNoBody) {
HTTPMessage req = getGetRequest("/guacamole");
req.getHeaders().add(HTTP_HEADER_USER_AGENT, "coolio");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 2);
#endif
}
TEST_F(HTTP2CodecTest, TrailersContinuation) {
HTTPMessage req = getGetRequest("/guacamole");
upstreamCodec_.generateHeader(output_, 1, req);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
upstreamCodec_.generateTrailers(output_, 1, trailers);
parse();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.trailers, 1);
EXPECT_NE(callbacks_.msg->getTrailers(), nullptr);
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(downstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReply) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-trailer-2", "chicken-kyiv");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 1);
EXPECT_EQ(callbacks_.bodyLength, 5);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ("chicken-kyiv",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-2"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithNoData) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
callbacks_.expectMessage(true, 2, 200);
EXPECT_EQ(callbacks_.bodyCalls, 0);
EXPECT_EQ(callbacks_.bodyLength, 0);
const auto& headers = callbacks_.msg->getHeaders();
EXPECT_TRUE(callbacks_.msg->getHeaders().exists(HTTP_HEADER_DATE));
EXPECT_EQ("x-coolio", headers.getSingleOrEmpty(HTTP_HEADER_CONTENT_TYPE));
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 3);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyWithPseudoHeaders) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
resp.setStatusMessage("nifty-nice");
resp.getHeaders().add(HTTP_HEADER_CONTENT_TYPE, "x-coolio");
downstreamCodec_.generateHeader(output_, 1, resp);
string data("abcde");
auto buf = folly::IOBuf::copyBuffer(data.data(), data.length());
downstreamCodec_.generateBody(
output_, 1, std::move(buf), HTTPCodec::NoPadding, false);
HPACKCodec headerCodec(TransportDirection::DOWNSTREAM);
std::string post("POST");
std::vector<proxygen::compress::Header> trailers = {
Header::makeHeaderForTest(headers::kMethod, post)};
auto encodedTrailers = headerCodec.encode(trailers);
http2::writeHeaders(output_,
std::move(encodedTrailers),
1,
folly::none,
http2::kNoPadding,
true,
true);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.trailers, 0);
EXPECT_EQ(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
}
TEST_F(HTTP2CodecTest, TrailersReplyContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 1);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 0);
EXPECT_NE(callbacks_.msg, nullptr);
EXPECT_EQ(callbacks_.msg->getStatusCode(), 200);
EXPECT_EQ(1, callbacks_.trailers);
EXPECT_NE(nullptr, callbacks_.msg->getTrailers());
EXPECT_EQ("pico-de-gallo",
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-trailer-1"));
EXPECT_EQ(std::string(http2::kMaxFramePayloadLengthMin, '!'),
callbacks_.msg->getTrailers()->getSingleOrEmpty("x-huge-trailer"));
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
TEST_F(HTTP2CodecTest, TrailersReplyMissingContinuation) {
SetUpUpstreamTest();
HTTPMessage resp;
resp.setStatusCode(200);
downstreamCodec_.generateHeader(output_, 1, resp);
HTTPHeaders trailers;
trailers.add("x-trailer-1", "pico-de-gallo");
trailers.add("x-huge-trailer",
std::string(http2::kMaxFramePayloadLengthMin, '!'));
downstreamCodec_.generateTrailers(output_, 1, trailers);
// empirically determined the size of continuation frame, and strip it
output_.trimEnd(http2::kFrameHeaderSize + 4132);
// insert a non-continuation (but otherwise valid) frame
http2::writeGoaway(output_, 17, ErrorCode::ENHANCE_YOUR_CALM);
parseUpstream();
EXPECT_EQ(callbacks_.messageBegin, 1);
EXPECT_EQ(callbacks_.headersComplete, 1);
EXPECT_EQ(callbacks_.messageComplete, 0);
EXPECT_EQ(callbacks_.streamErrors, 0);
EXPECT_EQ(callbacks_.sessionErrors, 1);
#ifndef NDEBUG
EXPECT_EQ(upstreamCodec_.getReceivedFrameCount(), 4);
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-388/cpp/good_599_1 |
crossvul-cpp_data_bad_3321_0 | /*
* hid-cp2112.c - Silicon Labs HID USB to SMBus master bridge
* Copyright (c) 2013,2014 Uplogix, Inc.
* David Barksdale <dbarksdale@uplogix.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*/
/*
* The Silicon Labs CP2112 chip is a USB HID device which provides an
* SMBus controller for talking to slave devices and 8 GPIO pins. The
* host communicates with the CP2112 via raw HID reports.
*
* Data Sheet:
* http://www.silabs.com/Support%20Documents/TechnicalDocs/CP2112.pdf
* Programming Interface Specification:
* http://www.silabs.com/Support%20Documents/TechnicalDocs/AN495.pdf
*/
#include <linux/gpio.h>
#include <linux/gpio/driver.h>
#include <linux/hid.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/nls.h>
#include <linux/usb/ch9.h>
#include "hid-ids.h"
#define CP2112_REPORT_MAX_LENGTH 64
#define CP2112_GPIO_CONFIG_LENGTH 5
#define CP2112_GPIO_GET_LENGTH 2
#define CP2112_GPIO_SET_LENGTH 3
enum {
CP2112_GPIO_CONFIG = 0x02,
CP2112_GPIO_GET = 0x03,
CP2112_GPIO_SET = 0x04,
CP2112_GET_VERSION_INFO = 0x05,
CP2112_SMBUS_CONFIG = 0x06,
CP2112_DATA_READ_REQUEST = 0x10,
CP2112_DATA_WRITE_READ_REQUEST = 0x11,
CP2112_DATA_READ_FORCE_SEND = 0x12,
CP2112_DATA_READ_RESPONSE = 0x13,
CP2112_DATA_WRITE_REQUEST = 0x14,
CP2112_TRANSFER_STATUS_REQUEST = 0x15,
CP2112_TRANSFER_STATUS_RESPONSE = 0x16,
CP2112_CANCEL_TRANSFER = 0x17,
CP2112_LOCK_BYTE = 0x20,
CP2112_USB_CONFIG = 0x21,
CP2112_MANUFACTURER_STRING = 0x22,
CP2112_PRODUCT_STRING = 0x23,
CP2112_SERIAL_STRING = 0x24,
};
enum {
STATUS0_IDLE = 0x00,
STATUS0_BUSY = 0x01,
STATUS0_COMPLETE = 0x02,
STATUS0_ERROR = 0x03,
};
enum {
STATUS1_TIMEOUT_NACK = 0x00,
STATUS1_TIMEOUT_BUS = 0x01,
STATUS1_ARBITRATION_LOST = 0x02,
STATUS1_READ_INCOMPLETE = 0x03,
STATUS1_WRITE_INCOMPLETE = 0x04,
STATUS1_SUCCESS = 0x05,
};
struct cp2112_smbus_config_report {
u8 report; /* CP2112_SMBUS_CONFIG */
__be32 clock_speed; /* Hz */
u8 device_address; /* Stored in the upper 7 bits */
u8 auto_send_read; /* 1 = enabled, 0 = disabled */
__be16 write_timeout; /* ms, 0 = no timeout */
__be16 read_timeout; /* ms, 0 = no timeout */
u8 scl_low_timeout; /* 1 = enabled, 0 = disabled */
__be16 retry_time; /* # of retries, 0 = no limit */
} __packed;
struct cp2112_usb_config_report {
u8 report; /* CP2112_USB_CONFIG */
__le16 vid; /* Vendor ID */
__le16 pid; /* Product ID */
u8 max_power; /* Power requested in 2mA units */
u8 power_mode; /* 0x00 = bus powered
0x01 = self powered & regulator off
0x02 = self powered & regulator on */
u8 release_major;
u8 release_minor;
u8 mask; /* What fields to program */
} __packed;
struct cp2112_read_req_report {
u8 report; /* CP2112_DATA_READ_REQUEST */
u8 slave_address;
__be16 length;
} __packed;
struct cp2112_write_read_req_report {
u8 report; /* CP2112_DATA_WRITE_READ_REQUEST */
u8 slave_address;
__be16 length;
u8 target_address_length;
u8 target_address[16];
} __packed;
struct cp2112_write_req_report {
u8 report; /* CP2112_DATA_WRITE_REQUEST */
u8 slave_address;
u8 length;
u8 data[61];
} __packed;
struct cp2112_force_read_report {
u8 report; /* CP2112_DATA_READ_FORCE_SEND */
__be16 length;
} __packed;
struct cp2112_xfer_status_report {
u8 report; /* CP2112_TRANSFER_STATUS_RESPONSE */
u8 status0; /* STATUS0_* */
u8 status1; /* STATUS1_* */
__be16 retries;
__be16 length;
} __packed;
struct cp2112_string_report {
u8 dummy; /* force .string to be aligned */
u8 report; /* CP2112_*_STRING */
u8 length; /* length in bytes of everyting after .report */
u8 type; /* USB_DT_STRING */
wchar_t string[30]; /* UTF16_LITTLE_ENDIAN string */
} __packed;
/* Number of times to request transfer status before giving up waiting for a
transfer to complete. This may need to be changed if SMBUS clock, retries,
or read/write/scl_low timeout settings are changed. */
static const int XFER_STATUS_RETRIES = 10;
/* Time in ms to wait for a CP2112_DATA_READ_RESPONSE or
CP2112_TRANSFER_STATUS_RESPONSE. */
static const int RESPONSE_TIMEOUT = 50;
static const struct hid_device_id cp2112_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_CP2112) },
{ }
};
MODULE_DEVICE_TABLE(hid, cp2112_devices);
struct cp2112_device {
struct i2c_adapter adap;
struct hid_device *hdev;
wait_queue_head_t wait;
u8 read_data[61];
u8 read_length;
u8 hwversion;
int xfer_status;
atomic_t read_avail;
atomic_t xfer_avail;
struct gpio_chip gc;
u8 *in_out_buffer;
struct mutex lock;
struct gpio_desc *desc[8];
bool gpio_poll;
struct delayed_work gpio_poll_worker;
unsigned long irq_mask;
u8 gpio_prev_state;
};
static int gpio_push_pull = 0xFF;
module_param(gpio_push_pull, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(gpio_push_pull, "GPIO push-pull configuration bitmask");
static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto exit;
}
buf[1] &= ~(1 << offset);
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto exit;
}
ret = 0;
exit:
mutex_unlock(&dev->lock);
return ret <= 0 ? ret : -EIO;
}
static void cp2112_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
buf[0] = CP2112_GPIO_SET;
buf[1] = value ? 0xff : 0;
buf[2] = 1 << offset;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_SET, buf,
CP2112_GPIO_SET_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0)
hid_err(hdev, "error setting GPIO values: %d\n", ret);
mutex_unlock(&dev->lock);
}
static int cp2112_gpio_get_all(struct gpio_chip *chip)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf,
CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_GET_LENGTH) {
hid_err(hdev, "error requesting GPIO values: %d\n", ret);
ret = ret < 0 ? ret : -EIO;
goto exit;
}
ret = buf[1];
exit:
mutex_unlock(&dev->lock);
return ret;
}
static int cp2112_gpio_get(struct gpio_chip *chip, unsigned int offset)
{
int ret;
ret = cp2112_gpio_get_all(chip);
if (ret < 0)
return ret;
return (ret >> offset) & 1;
}
static int cp2112_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto fail;
}
buf[1] |= 1 << offset;
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto fail;
}
mutex_unlock(&dev->lock);
/*
* Set gpio value when output direction is already set,
* as specified in AN495, Rev. 0.2, cpt. 4.4
*/
cp2112_gpio_set(chip, offset, value);
return 0;
fail:
mutex_unlock(&dev->lock);
return ret < 0 ? ret : -EIO;
}
static int cp2112_hid_get(struct hid_device *hdev, unsigned char report_number,
u8 *data, size_t count, unsigned char report_type)
{
u8 *buf;
int ret;
buf = kmalloc(count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
ret = hid_hw_raw_request(hdev, report_number, buf, count,
report_type, HID_REQ_GET_REPORT);
memcpy(data, buf, count);
kfree(buf);
return ret;
}
static int cp2112_hid_output(struct hid_device *hdev, u8 *data, size_t count,
unsigned char report_type)
{
u8 *buf;
int ret;
buf = kmemdup(data, count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (report_type == HID_OUTPUT_REPORT)
ret = hid_hw_output_report(hdev, buf, count);
else
ret = hid_hw_raw_request(hdev, buf[0], buf, count, report_type,
HID_REQ_SET_REPORT);
kfree(buf);
return ret;
}
static int cp2112_wait(struct cp2112_device *dev, atomic_t *avail)
{
int ret = 0;
/* We have sent either a CP2112_TRANSFER_STATUS_REQUEST or a
* CP2112_DATA_READ_FORCE_SEND and we are waiting for the response to
* come in cp2112_raw_event or timeout. There will only be one of these
* in flight at any one time. The timeout is extremely large and is a
* last resort if the CP2112 has died. If we do timeout we don't expect
* to receive the response which would cause data races, it's not like
* we can do anything about it anyway.
*/
ret = wait_event_interruptible_timeout(dev->wait,
atomic_read(avail), msecs_to_jiffies(RESPONSE_TIMEOUT));
if (-ERESTARTSYS == ret)
return ret;
if (!ret)
return -ETIMEDOUT;
atomic_set(avail, 0);
return 0;
}
static int cp2112_xfer_status(struct cp2112_device *dev)
{
struct hid_device *hdev = dev->hdev;
u8 buf[2];
int ret;
buf[0] = CP2112_TRANSFER_STATUS_REQUEST;
buf[1] = 0x01;
atomic_set(&dev->xfer_avail, 0);
ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error requesting status: %d\n", ret);
return ret;
}
ret = cp2112_wait(dev, &dev->xfer_avail);
if (ret)
return ret;
return dev->xfer_status;
}
static int cp2112_read(struct cp2112_device *dev, u8 *data, size_t size)
{
struct hid_device *hdev = dev->hdev;
struct cp2112_force_read_report report;
int ret;
if (size > sizeof(dev->read_data))
size = sizeof(dev->read_data);
report.report = CP2112_DATA_READ_FORCE_SEND;
report.length = cpu_to_be16(size);
atomic_set(&dev->read_avail, 0);
ret = cp2112_hid_output(hdev, &report.report, sizeof(report),
HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error requesting data: %d\n", ret);
return ret;
}
ret = cp2112_wait(dev, &dev->read_avail);
if (ret)
return ret;
hid_dbg(hdev, "read %d of %zd bytes requested\n",
dev->read_length, size);
if (size > dev->read_length)
size = dev->read_length;
memcpy(data, dev->read_data, size);
return dev->read_length;
}
static int cp2112_read_req(void *buf, u8 slave_address, u16 length)
{
struct cp2112_read_req_report *report = buf;
if (length < 1 || length > 512)
return -EINVAL;
report->report = CP2112_DATA_READ_REQUEST;
report->slave_address = slave_address << 1;
report->length = cpu_to_be16(length);
return sizeof(*report);
}
static int cp2112_write_read_req(void *buf, u8 slave_address, u16 length,
u8 command, u8 *data, u8 data_length)
{
struct cp2112_write_read_req_report *report = buf;
if (length < 1 || length > 512
|| data_length > sizeof(report->target_address) - 1)
return -EINVAL;
report->report = CP2112_DATA_WRITE_READ_REQUEST;
report->slave_address = slave_address << 1;
report->length = cpu_to_be16(length);
report->target_address_length = data_length + 1;
report->target_address[0] = command;
memcpy(&report->target_address[1], data, data_length);
return data_length + 6;
}
static int cp2112_write_req(void *buf, u8 slave_address, u8 command, u8 *data,
u8 data_length)
{
struct cp2112_write_req_report *report = buf;
if (data_length > sizeof(report->data) - 1)
return -EINVAL;
report->report = CP2112_DATA_WRITE_REQUEST;
report->slave_address = slave_address << 1;
report->length = data_length + 1;
report->data[0] = command;
memcpy(&report->data[1], data, data_length);
return data_length + 4;
}
static int cp2112_i2c_write_req(void *buf, u8 slave_address, u8 *data,
u8 data_length)
{
struct cp2112_write_req_report *report = buf;
if (data_length > sizeof(report->data))
return -EINVAL;
report->report = CP2112_DATA_WRITE_REQUEST;
report->slave_address = slave_address << 1;
report->length = data_length;
memcpy(report->data, data, data_length);
return data_length + 3;
}
static int cp2112_i2c_write_read_req(void *buf, u8 slave_address,
u8 *addr, int addr_length,
int read_length)
{
struct cp2112_write_read_req_report *report = buf;
if (read_length < 1 || read_length > 512 ||
addr_length > sizeof(report->target_address))
return -EINVAL;
report->report = CP2112_DATA_WRITE_READ_REQUEST;
report->slave_address = slave_address << 1;
report->length = cpu_to_be16(read_length);
report->target_address_length = addr_length;
memcpy(report->target_address, addr, addr_length);
return addr_length + 5;
}
static int cp2112_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
int num)
{
struct cp2112_device *dev = (struct cp2112_device *)adap->algo_data;
struct hid_device *hdev = dev->hdev;
u8 buf[64];
ssize_t count;
ssize_t read_length = 0;
u8 *read_buf = NULL;
unsigned int retries;
int ret;
hid_dbg(hdev, "I2C %d messages\n", num);
if (num == 1) {
if (msgs->flags & I2C_M_RD) {
hid_dbg(hdev, "I2C read %#04x len %d\n",
msgs->addr, msgs->len);
read_length = msgs->len;
read_buf = msgs->buf;
count = cp2112_read_req(buf, msgs->addr, msgs->len);
} else {
hid_dbg(hdev, "I2C write %#04x len %d\n",
msgs->addr, msgs->len);
count = cp2112_i2c_write_req(buf, msgs->addr,
msgs->buf, msgs->len);
}
if (count < 0)
return count;
} else if (dev->hwversion > 1 && /* no repeated start in rev 1 */
num == 2 &&
msgs[0].addr == msgs[1].addr &&
!(msgs[0].flags & I2C_M_RD) && (msgs[1].flags & I2C_M_RD)) {
hid_dbg(hdev, "I2C write-read %#04x wlen %d rlen %d\n",
msgs[0].addr, msgs[0].len, msgs[1].len);
read_length = msgs[1].len;
read_buf = msgs[1].buf;
count = cp2112_i2c_write_read_req(buf, msgs[0].addr,
msgs[0].buf, msgs[0].len, msgs[1].len);
if (count < 0)
return count;
} else {
hid_err(hdev,
"Multi-message I2C transactions not supported\n");
return -EOPNOTSUPP;
}
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
return ret;
}
ret = cp2112_hid_output(hdev, buf, count, HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error starting transaction: %d\n", ret);
goto power_normal;
}
for (retries = 0; retries < XFER_STATUS_RETRIES; ++retries) {
ret = cp2112_xfer_status(dev);
if (-EBUSY == ret)
continue;
if (ret < 0)
goto power_normal;
break;
}
if (XFER_STATUS_RETRIES <= retries) {
hid_warn(hdev, "Transfer timed out, cancelling.\n");
buf[0] = CP2112_CANCEL_TRANSFER;
buf[1] = 0x01;
ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
if (ret < 0)
hid_warn(hdev, "Error cancelling transaction: %d\n",
ret);
ret = -ETIMEDOUT;
goto power_normal;
}
for (count = 0; count < read_length;) {
ret = cp2112_read(dev, read_buf + count, read_length - count);
if (ret < 0)
goto power_normal;
if (ret == 0) {
hid_err(hdev, "read returned 0\n");
ret = -EIO;
goto power_normal;
}
count += ret;
if (count > read_length) {
/*
* The hardware returned too much data.
* This is mostly harmless because cp2112_read()
* has a limit check so didn't overrun our
* buffer. Nevertheless, we return an error
* because something is seriously wrong and
* it shouldn't go unnoticed.
*/
hid_err(hdev, "long read: %d > %zd\n",
ret, read_length - count + ret);
ret = -EIO;
goto power_normal;
}
}
/* return the number of transferred messages */
ret = num;
power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
hid_dbg(hdev, "I2C transfer finished: %d\n", ret);
return ret;
}
static int cp2112_xfer(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write, u8 command,
int size, union i2c_smbus_data *data)
{
struct cp2112_device *dev = (struct cp2112_device *)adap->algo_data;
struct hid_device *hdev = dev->hdev;
u8 buf[64];
__le16 word;
ssize_t count;
size_t read_length = 0;
unsigned int retries;
int ret;
hid_dbg(hdev, "%s addr 0x%x flags 0x%x cmd 0x%x size %d\n",
read_write == I2C_SMBUS_WRITE ? "write" : "read",
addr, flags, command, size);
switch (size) {
case I2C_SMBUS_BYTE:
read_length = 1;
if (I2C_SMBUS_READ == read_write)
count = cp2112_read_req(buf, addr, read_length);
else
count = cp2112_write_req(buf, addr, command, NULL,
0);
break;
case I2C_SMBUS_BYTE_DATA:
read_length = 1;
if (I2C_SMBUS_READ == read_write)
count = cp2112_write_read_req(buf, addr, read_length,
command, NULL, 0);
else
count = cp2112_write_req(buf, addr, command,
&data->byte, 1);
break;
case I2C_SMBUS_WORD_DATA:
read_length = 2;
word = cpu_to_le16(data->word);
if (I2C_SMBUS_READ == read_write)
count = cp2112_write_read_req(buf, addr, read_length,
command, NULL, 0);
else
count = cp2112_write_req(buf, addr, command,
(u8 *)&word, 2);
break;
case I2C_SMBUS_PROC_CALL:
size = I2C_SMBUS_WORD_DATA;
read_write = I2C_SMBUS_READ;
read_length = 2;
word = cpu_to_le16(data->word);
count = cp2112_write_read_req(buf, addr, read_length, command,
(u8 *)&word, 2);
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
size = I2C_SMBUS_BLOCK_DATA;
/* fallthrough */
case I2C_SMBUS_BLOCK_DATA:
if (I2C_SMBUS_READ == read_write) {
count = cp2112_write_read_req(buf, addr,
I2C_SMBUS_BLOCK_MAX,
command, NULL, 0);
} else {
count = cp2112_write_req(buf, addr, command,
data->block,
data->block[0] + 1);
}
break;
case I2C_SMBUS_BLOCK_PROC_CALL:
size = I2C_SMBUS_BLOCK_DATA;
read_write = I2C_SMBUS_READ;
count = cp2112_write_read_req(buf, addr, I2C_SMBUS_BLOCK_MAX,
command, data->block,
data->block[0] + 1);
break;
default:
hid_warn(hdev, "Unsupported transaction %d\n", size);
return -EOPNOTSUPP;
}
if (count < 0)
return count;
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
return ret;
}
ret = cp2112_hid_output(hdev, buf, count, HID_OUTPUT_REPORT);
if (ret < 0) {
hid_warn(hdev, "Error starting transaction: %d\n", ret);
goto power_normal;
}
for (retries = 0; retries < XFER_STATUS_RETRIES; ++retries) {
ret = cp2112_xfer_status(dev);
if (-EBUSY == ret)
continue;
if (ret < 0)
goto power_normal;
break;
}
if (XFER_STATUS_RETRIES <= retries) {
hid_warn(hdev, "Transfer timed out, cancelling.\n");
buf[0] = CP2112_CANCEL_TRANSFER;
buf[1] = 0x01;
ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
if (ret < 0)
hid_warn(hdev, "Error cancelling transaction: %d\n",
ret);
ret = -ETIMEDOUT;
goto power_normal;
}
if (I2C_SMBUS_WRITE == read_write) {
ret = 0;
goto power_normal;
}
if (I2C_SMBUS_BLOCK_DATA == size)
read_length = ret;
ret = cp2112_read(dev, buf, read_length);
if (ret < 0)
goto power_normal;
if (ret != read_length) {
hid_warn(hdev, "short read: %d < %zd\n", ret, read_length);
ret = -EIO;
goto power_normal;
}
switch (size) {
case I2C_SMBUS_BYTE:
case I2C_SMBUS_BYTE_DATA:
data->byte = buf[0];
break;
case I2C_SMBUS_WORD_DATA:
data->word = le16_to_cpup((__le16 *)buf);
break;
case I2C_SMBUS_BLOCK_DATA:
if (read_length > I2C_SMBUS_BLOCK_MAX) {
ret = -EPROTO;
goto power_normal;
}
memcpy(data->block, buf, read_length);
break;
}
ret = 0;
power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
hid_dbg(hdev, "transfer finished: %d\n", ret);
return ret;
}
static u32 cp2112_functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C |
I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_BLOCK_DATA |
I2C_FUNC_SMBUS_I2C_BLOCK |
I2C_FUNC_SMBUS_PROC_CALL |
I2C_FUNC_SMBUS_BLOCK_PROC_CALL;
}
static const struct i2c_algorithm smbus_algorithm = {
.master_xfer = cp2112_i2c_xfer,
.smbus_xfer = cp2112_xfer,
.functionality = cp2112_functionality,
};
static int cp2112_get_usb_config(struct hid_device *hdev,
struct cp2112_usb_config_report *cfg)
{
int ret;
ret = cp2112_hid_get(hdev, CP2112_USB_CONFIG, (u8 *)cfg, sizeof(*cfg),
HID_FEATURE_REPORT);
if (ret != sizeof(*cfg)) {
hid_err(hdev, "error reading usb config: %d\n", ret);
if (ret < 0)
return ret;
return -EIO;
}
return 0;
}
static int cp2112_set_usb_config(struct hid_device *hdev,
struct cp2112_usb_config_report *cfg)
{
int ret;
BUG_ON(cfg->report != CP2112_USB_CONFIG);
ret = cp2112_hid_output(hdev, (u8 *)cfg, sizeof(*cfg),
HID_FEATURE_REPORT);
if (ret != sizeof(*cfg)) {
hid_err(hdev, "error writing usb config: %d\n", ret);
if (ret < 0)
return ret;
return -EIO;
}
return 0;
}
static void chmod_sysfs_attrs(struct hid_device *hdev);
#define CP2112_CONFIG_ATTR(name, store, format, ...) \
static ssize_t name##_store(struct device *kdev, \
struct device_attribute *attr, const char *buf, \
size_t count) \
{ \
struct hid_device *hdev = to_hid_device(kdev); \
struct cp2112_usb_config_report cfg; \
int ret = cp2112_get_usb_config(hdev, &cfg); \
if (ret) \
return ret; \
store; \
ret = cp2112_set_usb_config(hdev, &cfg); \
if (ret) \
return ret; \
chmod_sysfs_attrs(hdev); \
return count; \
} \
static ssize_t name##_show(struct device *kdev, \
struct device_attribute *attr, char *buf) \
{ \
struct hid_device *hdev = to_hid_device(kdev); \
struct cp2112_usb_config_report cfg; \
int ret = cp2112_get_usb_config(hdev, &cfg); \
if (ret) \
return ret; \
return scnprintf(buf, PAGE_SIZE, format, ##__VA_ARGS__); \
} \
static DEVICE_ATTR_RW(name);
CP2112_CONFIG_ATTR(vendor_id, ({
u16 vid;
if (sscanf(buf, "%hi", &vid) != 1)
return -EINVAL;
cfg.vid = cpu_to_le16(vid);
cfg.mask = 0x01;
}), "0x%04x\n", le16_to_cpu(cfg.vid));
CP2112_CONFIG_ATTR(product_id, ({
u16 pid;
if (sscanf(buf, "%hi", &pid) != 1)
return -EINVAL;
cfg.pid = cpu_to_le16(pid);
cfg.mask = 0x02;
}), "0x%04x\n", le16_to_cpu(cfg.pid));
CP2112_CONFIG_ATTR(max_power, ({
int mA;
if (sscanf(buf, "%i", &mA) != 1)
return -EINVAL;
cfg.max_power = (mA + 1) / 2;
cfg.mask = 0x04;
}), "%u mA\n", cfg.max_power * 2);
CP2112_CONFIG_ATTR(power_mode, ({
if (sscanf(buf, "%hhi", &cfg.power_mode) != 1)
return -EINVAL;
cfg.mask = 0x08;
}), "%u\n", cfg.power_mode);
CP2112_CONFIG_ATTR(release_version, ({
if (sscanf(buf, "%hhi.%hhi", &cfg.release_major, &cfg.release_minor)
!= 2)
return -EINVAL;
cfg.mask = 0x10;
}), "%u.%u\n", cfg.release_major, cfg.release_minor);
#undef CP2112_CONFIG_ATTR
struct cp2112_pstring_attribute {
struct device_attribute attr;
unsigned char report;
};
static ssize_t pstr_store(struct device *kdev,
struct device_attribute *kattr, const char *buf,
size_t count)
{
struct hid_device *hdev = to_hid_device(kdev);
struct cp2112_pstring_attribute *attr =
container_of(kattr, struct cp2112_pstring_attribute, attr);
struct cp2112_string_report report;
int ret;
memset(&report, 0, sizeof(report));
ret = utf8s_to_utf16s(buf, count, UTF16_LITTLE_ENDIAN,
report.string, ARRAY_SIZE(report.string));
report.report = attr->report;
report.length = ret * sizeof(report.string[0]) + 2;
report.type = USB_DT_STRING;
ret = cp2112_hid_output(hdev, &report.report, report.length + 1,
HID_FEATURE_REPORT);
if (ret != report.length + 1) {
hid_err(hdev, "error writing %s string: %d\n", kattr->attr.name,
ret);
if (ret < 0)
return ret;
return -EIO;
}
chmod_sysfs_attrs(hdev);
return count;
}
static ssize_t pstr_show(struct device *kdev,
struct device_attribute *kattr, char *buf)
{
struct hid_device *hdev = to_hid_device(kdev);
struct cp2112_pstring_attribute *attr =
container_of(kattr, struct cp2112_pstring_attribute, attr);
struct cp2112_string_report report;
u8 length;
int ret;
ret = cp2112_hid_get(hdev, attr->report, &report.report,
sizeof(report) - 1, HID_FEATURE_REPORT);
if (ret < 3) {
hid_err(hdev, "error reading %s string: %d\n", kattr->attr.name,
ret);
if (ret < 0)
return ret;
return -EIO;
}
if (report.length < 2) {
hid_err(hdev, "invalid %s string length: %d\n",
kattr->attr.name, report.length);
return -EIO;
}
length = report.length > ret - 1 ? ret - 1 : report.length;
length = (length - 2) / sizeof(report.string[0]);
ret = utf16s_to_utf8s(report.string, length, UTF16_LITTLE_ENDIAN, buf,
PAGE_SIZE - 1);
buf[ret++] = '\n';
return ret;
}
#define CP2112_PSTR_ATTR(name, _report) \
static struct cp2112_pstring_attribute dev_attr_##name = { \
.attr = __ATTR(name, (S_IWUSR | S_IRUGO), pstr_show, pstr_store), \
.report = _report, \
};
CP2112_PSTR_ATTR(manufacturer, CP2112_MANUFACTURER_STRING);
CP2112_PSTR_ATTR(product, CP2112_PRODUCT_STRING);
CP2112_PSTR_ATTR(serial, CP2112_SERIAL_STRING);
#undef CP2112_PSTR_ATTR
static const struct attribute_group cp2112_attr_group = {
.attrs = (struct attribute *[]){
&dev_attr_vendor_id.attr,
&dev_attr_product_id.attr,
&dev_attr_max_power.attr,
&dev_attr_power_mode.attr,
&dev_attr_release_version.attr,
&dev_attr_manufacturer.attr.attr,
&dev_attr_product.attr.attr,
&dev_attr_serial.attr.attr,
NULL
}
};
/* Chmoding our sysfs attributes is simply a way to expose which fields in the
* PROM have already been programmed. We do not depend on this preventing
* writing to these attributes since the CP2112 will simply ignore writes to
* already-programmed fields. This is why there is no sense in fixing this
* racy behaviour.
*/
static void chmod_sysfs_attrs(struct hid_device *hdev)
{
struct attribute **attr;
u8 buf[2];
int ret;
ret = cp2112_hid_get(hdev, CP2112_LOCK_BYTE, buf, sizeof(buf),
HID_FEATURE_REPORT);
if (ret != sizeof(buf)) {
hid_err(hdev, "error reading lock byte: %d\n", ret);
return;
}
for (attr = cp2112_attr_group.attrs; *attr; ++attr) {
umode_t mode = (buf[1] & 1) ? S_IWUSR | S_IRUGO : S_IRUGO;
ret = sysfs_chmod_file(&hdev->dev.kobj, *attr, mode);
if (ret < 0)
hid_err(hdev, "error chmoding sysfs file %s\n",
(*attr)->name);
buf[1] >>= 1;
}
}
static void cp2112_gpio_irq_ack(struct irq_data *d)
{
}
static void cp2112_gpio_irq_mask(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
__clear_bit(d->hwirq, &dev->irq_mask);
}
static void cp2112_gpio_irq_unmask(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
__set_bit(d->hwirq, &dev->irq_mask);
}
static void cp2112_gpio_poll_callback(struct work_struct *work)
{
struct cp2112_device *dev = container_of(work, struct cp2112_device,
gpio_poll_worker.work);
struct irq_data *d;
u8 gpio_mask;
u8 virqs = (u8)dev->irq_mask;
u32 irq_type;
int irq, virq, ret;
ret = cp2112_gpio_get_all(&dev->gc);
if (ret == -ENODEV) /* the hardware has been disconnected */
return;
if (ret < 0)
goto exit;
gpio_mask = ret;
while (virqs) {
virq = ffs(virqs) - 1;
virqs &= ~BIT(virq);
if (!dev->gc.to_irq)
break;
irq = dev->gc.to_irq(&dev->gc, virq);
d = irq_get_irq_data(irq);
if (!d)
continue;
irq_type = irqd_get_trigger_type(d);
if (gpio_mask & BIT(virq)) {
/* Level High */
if (irq_type & IRQ_TYPE_LEVEL_HIGH)
handle_nested_irq(irq);
if ((irq_type & IRQ_TYPE_EDGE_RISING) &&
!(dev->gpio_prev_state & BIT(virq)))
handle_nested_irq(irq);
} else {
/* Level Low */
if (irq_type & IRQ_TYPE_LEVEL_LOW)
handle_nested_irq(irq);
if ((irq_type & IRQ_TYPE_EDGE_FALLING) &&
(dev->gpio_prev_state & BIT(virq)))
handle_nested_irq(irq);
}
}
dev->gpio_prev_state = gpio_mask;
exit:
if (dev->gpio_poll)
schedule_delayed_work(&dev->gpio_poll_worker, 10);
}
static unsigned int cp2112_gpio_irq_startup(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
INIT_DELAYED_WORK(&dev->gpio_poll_worker, cp2112_gpio_poll_callback);
cp2112_gpio_direction_input(gc, d->hwirq);
if (!dev->gpio_poll) {
dev->gpio_poll = true;
schedule_delayed_work(&dev->gpio_poll_worker, 0);
}
cp2112_gpio_irq_unmask(d);
return 0;
}
static void cp2112_gpio_irq_shutdown(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct cp2112_device *dev = gpiochip_get_data(gc);
cancel_delayed_work_sync(&dev->gpio_poll_worker);
}
static int cp2112_gpio_irq_type(struct irq_data *d, unsigned int type)
{
return 0;
}
static struct irq_chip cp2112_gpio_irqchip = {
.name = "cp2112-gpio",
.irq_startup = cp2112_gpio_irq_startup,
.irq_shutdown = cp2112_gpio_irq_shutdown,
.irq_ack = cp2112_gpio_irq_ack,
.irq_mask = cp2112_gpio_irq_mask,
.irq_unmask = cp2112_gpio_irq_unmask,
.irq_set_type = cp2112_gpio_irq_type,
};
static int __maybe_unused cp2112_allocate_irq(struct cp2112_device *dev,
int pin)
{
int ret;
if (dev->desc[pin])
return -EINVAL;
dev->desc[pin] = gpiochip_request_own_desc(&dev->gc, pin,
"HID/I2C:Event");
if (IS_ERR(dev->desc[pin])) {
dev_err(dev->gc.parent, "Failed to request GPIO\n");
return PTR_ERR(dev->desc[pin]);
}
ret = gpiochip_lock_as_irq(&dev->gc, pin);
if (ret) {
dev_err(dev->gc.parent, "Failed to lock GPIO as interrupt\n");
goto err_desc;
}
ret = gpiod_to_irq(dev->desc[pin]);
if (ret < 0) {
dev_err(dev->gc.parent, "Failed to translate GPIO to IRQ\n");
goto err_lock;
}
return ret;
err_lock:
gpiochip_unlock_as_irq(&dev->gc, pin);
err_desc:
gpiochip_free_own_desc(dev->desc[pin]);
dev->desc[pin] = NULL;
return ret;
}
static int cp2112_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
struct cp2112_device *dev;
u8 buf[3];
struct cp2112_smbus_config_report config;
int ret;
dev = devm_kzalloc(&hdev->dev, sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->in_out_buffer = devm_kzalloc(&hdev->dev, CP2112_REPORT_MAX_LENGTH,
GFP_KERNEL);
if (!dev->in_out_buffer)
return -ENOMEM;
mutex_init(&dev->lock);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
return ret;
}
ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
if (ret) {
hid_err(hdev, "hw start failed\n");
return ret;
}
ret = hid_hw_open(hdev);
if (ret) {
hid_err(hdev, "hw open failed\n");
goto err_hid_stop;
}
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
goto err_hid_close;
}
ret = cp2112_hid_get(hdev, CP2112_GET_VERSION_INFO, buf, sizeof(buf),
HID_FEATURE_REPORT);
if (ret != sizeof(buf)) {
hid_err(hdev, "error requesting version\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_info(hdev, "Part Number: 0x%02X Device Version: 0x%02X\n",
buf[1], buf[2]);
ret = cp2112_hid_get(hdev, CP2112_SMBUS_CONFIG, (u8 *)&config,
sizeof(config), HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error requesting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
config.retry_time = cpu_to_be16(1);
ret = cp2112_hid_output(hdev, (u8 *)&config, sizeof(config),
HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error setting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_set_drvdata(hdev, (void *)dev);
dev->hdev = hdev;
dev->adap.owner = THIS_MODULE;
dev->adap.class = I2C_CLASS_HWMON;
dev->adap.algo = &smbus_algorithm;
dev->adap.algo_data = dev;
dev->adap.dev.parent = &hdev->dev;
snprintf(dev->adap.name, sizeof(dev->adap.name),
"CP2112 SMBus Bridge on hiddev%d", hdev->minor);
dev->hwversion = buf[2];
init_waitqueue_head(&dev->wait);
hid_device_io_start(hdev);
ret = i2c_add_adapter(&dev->adap);
hid_device_io_stop(hdev);
if (ret) {
hid_err(hdev, "error registering i2c adapter\n");
goto err_power_normal;
}
hid_dbg(hdev, "adapter registered\n");
dev->gc.label = "cp2112_gpio";
dev->gc.direction_input = cp2112_gpio_direction_input;
dev->gc.direction_output = cp2112_gpio_direction_output;
dev->gc.set = cp2112_gpio_set;
dev->gc.get = cp2112_gpio_get;
dev->gc.base = -1;
dev->gc.ngpio = 8;
dev->gc.can_sleep = 1;
dev->gc.parent = &hdev->dev;
ret = gpiochip_add_data(&dev->gc, dev);
if (ret < 0) {
hid_err(hdev, "error registering gpio chip\n");
goto err_free_i2c;
}
ret = sysfs_create_group(&hdev->dev.kobj, &cp2112_attr_group);
if (ret < 0) {
hid_err(hdev, "error creating sysfs attrs\n");
goto err_gpiochip_remove;
}
chmod_sysfs_attrs(hdev);
hid_hw_power(hdev, PM_HINT_NORMAL);
ret = gpiochip_irqchip_add(&dev->gc, &cp2112_gpio_irqchip, 0,
handle_simple_irq, IRQ_TYPE_NONE);
if (ret) {
dev_err(dev->gc.parent, "failed to add IRQ chip\n");
goto err_sysfs_remove;
}
return ret;
err_sysfs_remove:
sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
err_gpiochip_remove:
gpiochip_remove(&dev->gc);
err_free_i2c:
i2c_del_adapter(&dev->adap);
err_power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
err_hid_close:
hid_hw_close(hdev);
err_hid_stop:
hid_hw_stop(hdev);
return ret;
}
static void cp2112_remove(struct hid_device *hdev)
{
struct cp2112_device *dev = hid_get_drvdata(hdev);
int i;
sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
i2c_del_adapter(&dev->adap);
if (dev->gpio_poll) {
dev->gpio_poll = false;
cancel_delayed_work_sync(&dev->gpio_poll_worker);
}
for (i = 0; i < ARRAY_SIZE(dev->desc); i++) {
gpiochip_unlock_as_irq(&dev->gc, i);
gpiochip_free_own_desc(dev->desc[i]);
}
gpiochip_remove(&dev->gc);
/* i2c_del_adapter has finished removing all i2c devices from our
* adapter. Well behaved devices should no longer call our cp2112_xfer
* and should have waited for any pending calls to finish. It has also
* waited for device_unregister(&adap->dev) to complete. Therefore we
* can safely free our struct cp2112_device.
*/
hid_hw_close(hdev);
hid_hw_stop(hdev);
}
static int cp2112_raw_event(struct hid_device *hdev, struct hid_report *report,
u8 *data, int size)
{
struct cp2112_device *dev = hid_get_drvdata(hdev);
struct cp2112_xfer_status_report *xfer = (void *)data;
switch (data[0]) {
case CP2112_TRANSFER_STATUS_RESPONSE:
hid_dbg(hdev, "xfer status: %02x %02x %04x %04x\n",
xfer->status0, xfer->status1,
be16_to_cpu(xfer->retries), be16_to_cpu(xfer->length));
switch (xfer->status0) {
case STATUS0_IDLE:
dev->xfer_status = -EAGAIN;
break;
case STATUS0_BUSY:
dev->xfer_status = -EBUSY;
break;
case STATUS0_COMPLETE:
dev->xfer_status = be16_to_cpu(xfer->length);
break;
case STATUS0_ERROR:
switch (xfer->status1) {
case STATUS1_TIMEOUT_NACK:
case STATUS1_TIMEOUT_BUS:
dev->xfer_status = -ETIMEDOUT;
break;
default:
dev->xfer_status = -EIO;
break;
}
break;
default:
dev->xfer_status = -EINVAL;
break;
}
atomic_set(&dev->xfer_avail, 1);
break;
case CP2112_DATA_READ_RESPONSE:
hid_dbg(hdev, "read response: %02x %02x\n", data[1], data[2]);
dev->read_length = data[2];
if (dev->read_length > sizeof(dev->read_data))
dev->read_length = sizeof(dev->read_data);
memcpy(dev->read_data, &data[3], dev->read_length);
atomic_set(&dev->read_avail, 1);
break;
default:
hid_err(hdev, "unknown report\n");
return 0;
}
wake_up_interruptible(&dev->wait);
return 1;
}
static struct hid_driver cp2112_driver = {
.name = "cp2112",
.id_table = cp2112_devices,
.probe = cp2112_probe,
.remove = cp2112_remove,
.raw_event = cp2112_raw_event,
};
module_hid_driver(cp2112_driver);
MODULE_DESCRIPTION("Silicon Labs HID USB to SMBus master bridge");
MODULE_AUTHOR("David Barksdale <dbarksdale@uplogix.com>");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-388/c/bad_3321_0 |
crossvul-cpp_data_good_3122_0 | /*
* Copyright © 2014 Broadcom
*
* 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.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/device.h>
#include <linux/io.h>
#include "uapi/drm/vc4_drm.h"
#include "vc4_drv.h"
#include "vc4_regs.h"
#include "vc4_trace.h"
static void
vc4_queue_hangcheck(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
mod_timer(&vc4->hangcheck.timer,
round_jiffies_up(jiffies + msecs_to_jiffies(100)));
}
struct vc4_hang_state {
struct drm_vc4_get_hang_state user_state;
u32 bo_count;
struct drm_gem_object **bo;
};
static void
vc4_free_hang_state(struct drm_device *dev, struct vc4_hang_state *state)
{
unsigned int i;
for (i = 0; i < state->user_state.bo_count; i++)
drm_gem_object_unreference_unlocked(state->bo[i]);
kfree(state);
}
int
vc4_get_hang_state_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vc4_get_hang_state *get_state = data;
struct drm_vc4_get_hang_state_bo *bo_state;
struct vc4_hang_state *kernel_state;
struct drm_vc4_get_hang_state *state;
struct vc4_dev *vc4 = to_vc4_dev(dev);
unsigned long irqflags;
u32 i;
int ret = 0;
spin_lock_irqsave(&vc4->job_lock, irqflags);
kernel_state = vc4->hang_state;
if (!kernel_state) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return -ENOENT;
}
state = &kernel_state->user_state;
/* If the user's array isn't big enough, just return the
* required array size.
*/
if (get_state->bo_count < state->bo_count) {
get_state->bo_count = state->bo_count;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return 0;
}
vc4->hang_state = NULL;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
/* Save the user's BO pointer, so we don't stomp it with the memcpy. */
state->bo = get_state->bo;
memcpy(get_state, state, sizeof(*state));
bo_state = kcalloc(state->bo_count, sizeof(*bo_state), GFP_KERNEL);
if (!bo_state) {
ret = -ENOMEM;
goto err_free;
}
for (i = 0; i < state->bo_count; i++) {
struct vc4_bo *vc4_bo = to_vc4_bo(kernel_state->bo[i]);
u32 handle;
ret = drm_gem_handle_create(file_priv, kernel_state->bo[i],
&handle);
if (ret) {
state->bo_count = i - 1;
goto err;
}
bo_state[i].handle = handle;
bo_state[i].paddr = vc4_bo->base.paddr;
bo_state[i].size = vc4_bo->base.base.size;
}
if (copy_to_user((void __user *)(uintptr_t)get_state->bo,
bo_state,
state->bo_count * sizeof(*bo_state)))
ret = -EFAULT;
kfree(bo_state);
err_free:
vc4_free_hang_state(dev, kernel_state);
err:
return ret;
}
static void
vc4_save_hang_state(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct drm_vc4_get_hang_state *state;
struct vc4_hang_state *kernel_state;
struct vc4_exec_info *exec[2];
struct vc4_bo *bo;
unsigned long irqflags;
unsigned int i, j, unref_list_count, prev_idx;
kernel_state = kcalloc(1, sizeof(*kernel_state), GFP_KERNEL);
if (!kernel_state)
return;
state = &kernel_state->user_state;
spin_lock_irqsave(&vc4->job_lock, irqflags);
exec[0] = vc4_first_bin_job(vc4);
exec[1] = vc4_first_render_job(vc4);
if (!exec[0] && !exec[1]) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return;
}
/* Get the bos from both binner and renderer into hang state. */
state->bo_count = 0;
for (i = 0; i < 2; i++) {
if (!exec[i])
continue;
unref_list_count = 0;
list_for_each_entry(bo, &exec[i]->unref_list, unref_head)
unref_list_count++;
state->bo_count += exec[i]->bo_count + unref_list_count;
}
kernel_state->bo = kcalloc(state->bo_count,
sizeof(*kernel_state->bo), GFP_ATOMIC);
if (!kernel_state->bo) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return;
}
prev_idx = 0;
for (i = 0; i < 2; i++) {
if (!exec[i])
continue;
for (j = 0; j < exec[i]->bo_count; j++) {
drm_gem_object_reference(&exec[i]->bo[j]->base);
kernel_state->bo[j + prev_idx] = &exec[i]->bo[j]->base;
}
list_for_each_entry(bo, &exec[i]->unref_list, unref_head) {
drm_gem_object_reference(&bo->base.base);
kernel_state->bo[j + prev_idx] = &bo->base.base;
j++;
}
prev_idx = j + 1;
}
if (exec[0])
state->start_bin = exec[0]->ct0ca;
if (exec[1])
state->start_render = exec[1]->ct1ca;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
state->ct0ca = V3D_READ(V3D_CTNCA(0));
state->ct0ea = V3D_READ(V3D_CTNEA(0));
state->ct1ca = V3D_READ(V3D_CTNCA(1));
state->ct1ea = V3D_READ(V3D_CTNEA(1));
state->ct0cs = V3D_READ(V3D_CTNCS(0));
state->ct1cs = V3D_READ(V3D_CTNCS(1));
state->ct0ra0 = V3D_READ(V3D_CT00RA0);
state->ct1ra0 = V3D_READ(V3D_CT01RA0);
state->bpca = V3D_READ(V3D_BPCA);
state->bpcs = V3D_READ(V3D_BPCS);
state->bpoa = V3D_READ(V3D_BPOA);
state->bpos = V3D_READ(V3D_BPOS);
state->vpmbase = V3D_READ(V3D_VPMBASE);
state->dbge = V3D_READ(V3D_DBGE);
state->fdbgo = V3D_READ(V3D_FDBGO);
state->fdbgb = V3D_READ(V3D_FDBGB);
state->fdbgr = V3D_READ(V3D_FDBGR);
state->fdbgs = V3D_READ(V3D_FDBGS);
state->errstat = V3D_READ(V3D_ERRSTAT);
spin_lock_irqsave(&vc4->job_lock, irqflags);
if (vc4->hang_state) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
vc4_free_hang_state(dev, kernel_state);
} else {
vc4->hang_state = kernel_state;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
}
}
static void
vc4_reset(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
DRM_INFO("Resetting GPU.\n");
mutex_lock(&vc4->power_lock);
if (vc4->power_refcount) {
/* Power the device off and back on the by dropping the
* reference on runtime PM.
*/
pm_runtime_put_sync_suspend(&vc4->v3d->pdev->dev);
pm_runtime_get_sync(&vc4->v3d->pdev->dev);
}
mutex_unlock(&vc4->power_lock);
vc4_irq_reset(dev);
/* Rearm the hangcheck -- another job might have been waiting
* for our hung one to get kicked off, and vc4_irq_reset()
* would have started it.
*/
vc4_queue_hangcheck(dev);
}
static void
vc4_reset_work(struct work_struct *work)
{
struct vc4_dev *vc4 =
container_of(work, struct vc4_dev, hangcheck.reset_work);
vc4_save_hang_state(vc4->dev);
vc4_reset(vc4->dev);
}
static void
vc4_hangcheck_elapsed(unsigned long data)
{
struct drm_device *dev = (struct drm_device *)data;
struct vc4_dev *vc4 = to_vc4_dev(dev);
uint32_t ct0ca, ct1ca;
unsigned long irqflags;
struct vc4_exec_info *bin_exec, *render_exec;
spin_lock_irqsave(&vc4->job_lock, irqflags);
bin_exec = vc4_first_bin_job(vc4);
render_exec = vc4_first_render_job(vc4);
/* If idle, we can stop watching for hangs. */
if (!bin_exec && !render_exec) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return;
}
ct0ca = V3D_READ(V3D_CTNCA(0));
ct1ca = V3D_READ(V3D_CTNCA(1));
/* If we've made any progress in execution, rearm the timer
* and wait.
*/
if ((bin_exec && ct0ca != bin_exec->last_ct0ca) ||
(render_exec && ct1ca != render_exec->last_ct1ca)) {
if (bin_exec)
bin_exec->last_ct0ca = ct0ca;
if (render_exec)
render_exec->last_ct1ca = ct1ca;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
vc4_queue_hangcheck(dev);
return;
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
/* We've gone too long with no progress, reset. This has to
* be done from a work struct, since resetting can sleep and
* this timer hook isn't allowed to.
*/
schedule_work(&vc4->hangcheck.reset_work);
}
static void
submit_cl(struct drm_device *dev, uint32_t thread, uint32_t start, uint32_t end)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
/* Set the current and end address of the control list.
* Writing the end register is what starts the job.
*/
V3D_WRITE(V3D_CTNCA(thread), start);
V3D_WRITE(V3D_CTNEA(thread), end);
}
int
vc4_wait_for_seqno(struct drm_device *dev, uint64_t seqno, uint64_t timeout_ns,
bool interruptible)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
int ret = 0;
unsigned long timeout_expire;
DEFINE_WAIT(wait);
if (vc4->finished_seqno >= seqno)
return 0;
if (timeout_ns == 0)
return -ETIME;
timeout_expire = jiffies + nsecs_to_jiffies(timeout_ns);
trace_vc4_wait_for_seqno_begin(dev, seqno, timeout_ns);
for (;;) {
prepare_to_wait(&vc4->job_wait_queue, &wait,
interruptible ? TASK_INTERRUPTIBLE :
TASK_UNINTERRUPTIBLE);
if (interruptible && signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
if (vc4->finished_seqno >= seqno)
break;
if (timeout_ns != ~0ull) {
if (time_after_eq(jiffies, timeout_expire)) {
ret = -ETIME;
break;
}
schedule_timeout(timeout_expire - jiffies);
} else {
schedule();
}
}
finish_wait(&vc4->job_wait_queue, &wait);
trace_vc4_wait_for_seqno_end(dev, seqno);
return ret;
}
static void
vc4_flush_caches(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
/* Flush the GPU L2 caches. These caches sit on top of system
* L3 (the 128kb or so shared with the CPU), and are
* non-allocating in the L3.
*/
V3D_WRITE(V3D_L2CACTL,
V3D_L2CACTL_L2CCLR);
V3D_WRITE(V3D_SLCACTL,
VC4_SET_FIELD(0xf, V3D_SLCACTL_T1CC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_T0CC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC) |
VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC));
}
/* Sets the registers for the next job to be actually be executed in
* the hardware.
*
* The job_lock should be held during this.
*/
void
vc4_submit_next_bin_job(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct vc4_exec_info *exec;
again:
exec = vc4_first_bin_job(vc4);
if (!exec)
return;
vc4_flush_caches(dev);
/* Either put the job in the binner if it uses the binner, or
* immediately move it to the to-be-rendered queue.
*/
if (exec->ct0ca != exec->ct0ea) {
submit_cl(dev, 0, exec->ct0ca, exec->ct0ea);
} else {
vc4_move_job_to_render(dev, exec);
goto again;
}
}
void
vc4_submit_next_render_job(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct vc4_exec_info *exec = vc4_first_render_job(vc4);
if (!exec)
return;
submit_cl(dev, 1, exec->ct1ca, exec->ct1ea);
}
void
vc4_move_job_to_render(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
bool was_empty = list_empty(&vc4->render_job_list);
list_move_tail(&exec->head, &vc4->render_job_list);
if (was_empty)
vc4_submit_next_render_job(dev);
}
static void
vc4_update_bo_seqnos(struct vc4_exec_info *exec, uint64_t seqno)
{
struct vc4_bo *bo;
unsigned i;
for (i = 0; i < exec->bo_count; i++) {
bo = to_vc4_bo(&exec->bo[i]->base);
bo->seqno = seqno;
}
list_for_each_entry(bo, &exec->unref_list, unref_head) {
bo->seqno = seqno;
}
for (i = 0; i < exec->rcl_write_bo_count; i++) {
bo = to_vc4_bo(&exec->rcl_write_bo[i]->base);
bo->write_seqno = seqno;
}
}
/* Queues a struct vc4_exec_info for execution. If no job is
* currently executing, then submits it.
*
* Unlike most GPUs, our hardware only handles one command list at a
* time. To queue multiple jobs at once, we'd need to edit the
* previous command list to have a jump to the new one at the end, and
* then bump the end address. That's a change for a later date,
* though.
*/
static void
vc4_queue_submit(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
uint64_t seqno;
unsigned long irqflags;
spin_lock_irqsave(&vc4->job_lock, irqflags);
seqno = ++vc4->emit_seqno;
exec->seqno = seqno;
vc4_update_bo_seqnos(exec, seqno);
list_add_tail(&exec->head, &vc4->bin_job_list);
/* If no job was executing, kick ours off. Otherwise, it'll
* get started when the previous job's flush done interrupt
* occurs.
*/
if (vc4_first_bin_job(vc4) == exec) {
vc4_submit_next_bin_job(dev);
vc4_queue_hangcheck(dev);
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
}
/**
* Looks up a bunch of GEM handles for BOs and stores the array for
* use in the command validator that actually writes relocated
* addresses pointing to them.
*/
static int
vc4_cl_lookup_bos(struct drm_device *dev,
struct drm_file *file_priv,
struct vc4_exec_info *exec)
{
struct drm_vc4_submit_cl *args = exec->args;
uint32_t *handles;
int ret = 0;
int i;
exec->bo_count = args->bo_handle_count;
if (!exec->bo_count) {
/* See comment on bo_index for why we have to check
* this.
*/
DRM_ERROR("Rendering requires BOs to validate\n");
return -EINVAL;
}
exec->bo = drm_calloc_large(exec->bo_count,
sizeof(struct drm_gem_cma_object *));
if (!exec->bo) {
DRM_ERROR("Failed to allocate validated BO pointers\n");
return -ENOMEM;
}
handles = drm_malloc_ab(exec->bo_count, sizeof(uint32_t));
if (!handles) {
ret = -ENOMEM;
DRM_ERROR("Failed to allocate incoming GEM handles\n");
goto fail;
}
if (copy_from_user(handles,
(void __user *)(uintptr_t)args->bo_handles,
exec->bo_count * sizeof(uint32_t))) {
ret = -EFAULT;
DRM_ERROR("Failed to copy in GEM handles\n");
goto fail;
}
spin_lock(&file_priv->table_lock);
for (i = 0; i < exec->bo_count; i++) {
struct drm_gem_object *bo = idr_find(&file_priv->object_idr,
handles[i]);
if (!bo) {
DRM_ERROR("Failed to look up GEM BO %d: %d\n",
i, handles[i]);
ret = -EINVAL;
spin_unlock(&file_priv->table_lock);
goto fail;
}
drm_gem_object_reference(bo);
exec->bo[i] = (struct drm_gem_cma_object *)bo;
}
spin_unlock(&file_priv->table_lock);
fail:
drm_free_large(handles);
return ret;
}
static int
vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct drm_vc4_submit_cl *args = exec->args;
void *temp = NULL;
void *bin;
int ret = 0;
uint32_t bin_offset = 0;
uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size,
16);
uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size;
uint32_t exec_size = uniforms_offset + args->uniforms_size;
uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) *
args->shader_rec_count);
struct vc4_bo *bo;
if (shader_rec_offset < args->bin_cl_size ||
uniforms_offset < shader_rec_offset ||
exec_size < uniforms_offset ||
args->shader_rec_count >= (UINT_MAX /
sizeof(struct vc4_shader_state)) ||
temp_size < exec_size) {
DRM_ERROR("overflow in exec arguments\n");
ret = -EINVAL;
goto fail;
}
/* Allocate space where we'll store the copied in user command lists
* and shader records.
*
* We don't just copy directly into the BOs because we need to
* read the contents back for validation, and I think the
* bo->vaddr is uncached access.
*/
temp = drm_malloc_ab(temp_size, 1);
if (!temp) {
DRM_ERROR("Failed to allocate storage for copying "
"in bin/render CLs.\n");
ret = -ENOMEM;
goto fail;
}
bin = temp + bin_offset;
exec->shader_rec_u = temp + shader_rec_offset;
exec->uniforms_u = temp + uniforms_offset;
exec->shader_state = temp + exec_size;
exec->shader_state_size = args->shader_rec_count;
if (copy_from_user(bin,
(void __user *)(uintptr_t)args->bin_cl,
args->bin_cl_size)) {
ret = -EFAULT;
goto fail;
}
if (copy_from_user(exec->shader_rec_u,
(void __user *)(uintptr_t)args->shader_rec,
args->shader_rec_size)) {
ret = -EFAULT;
goto fail;
}
if (copy_from_user(exec->uniforms_u,
(void __user *)(uintptr_t)args->uniforms,
args->uniforms_size)) {
ret = -EFAULT;
goto fail;
}
bo = vc4_bo_create(dev, exec_size, true);
if (IS_ERR(bo)) {
DRM_ERROR("Couldn't allocate BO for binning\n");
ret = PTR_ERR(bo);
goto fail;
}
exec->exec_bo = &bo->base;
list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head,
&exec->unref_list);
exec->ct0ca = exec->exec_bo->paddr + bin_offset;
exec->bin_u = bin;
exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset;
exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset;
exec->shader_rec_size = args->shader_rec_size;
exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset;
exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset;
exec->uniforms_size = args->uniforms_size;
ret = vc4_validate_bin_cl(dev,
exec->exec_bo->vaddr + bin_offset,
bin,
exec);
if (ret)
goto fail;
ret = vc4_validate_shader_recs(dev, exec);
if (ret)
goto fail;
/* Block waiting on any previous rendering into the CS's VBO,
* IB, or textures, so that pixels are actually written by the
* time we try to read them.
*/
ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true);
fail:
drm_free_large(temp);
return ret;
}
static void
vc4_complete_exec(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
unsigned i;
if (exec->bo) {
for (i = 0; i < exec->bo_count; i++)
drm_gem_object_unreference_unlocked(&exec->bo[i]->base);
drm_free_large(exec->bo);
}
while (!list_empty(&exec->unref_list)) {
struct vc4_bo *bo = list_first_entry(&exec->unref_list,
struct vc4_bo, unref_head);
list_del(&bo->unref_head);
drm_gem_object_unreference_unlocked(&bo->base.base);
}
mutex_lock(&vc4->power_lock);
if (--vc4->power_refcount == 0) {
pm_runtime_mark_last_busy(&vc4->v3d->pdev->dev);
pm_runtime_put_autosuspend(&vc4->v3d->pdev->dev);
}
mutex_unlock(&vc4->power_lock);
kfree(exec);
}
void
vc4_job_handle_completed(struct vc4_dev *vc4)
{
unsigned long irqflags;
struct vc4_seqno_cb *cb, *cb_temp;
spin_lock_irqsave(&vc4->job_lock, irqflags);
while (!list_empty(&vc4->job_done_list)) {
struct vc4_exec_info *exec =
list_first_entry(&vc4->job_done_list,
struct vc4_exec_info, head);
list_del(&exec->head);
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
vc4_complete_exec(vc4->dev, exec);
spin_lock_irqsave(&vc4->job_lock, irqflags);
}
list_for_each_entry_safe(cb, cb_temp, &vc4->seqno_cb_list, work.entry) {
if (cb->seqno <= vc4->finished_seqno) {
list_del_init(&cb->work.entry);
schedule_work(&cb->work);
}
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
}
static void vc4_seqno_cb_work(struct work_struct *work)
{
struct vc4_seqno_cb *cb = container_of(work, struct vc4_seqno_cb, work);
cb->func(cb);
}
int vc4_queue_seqno_cb(struct drm_device *dev,
struct vc4_seqno_cb *cb, uint64_t seqno,
void (*func)(struct vc4_seqno_cb *cb))
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
int ret = 0;
unsigned long irqflags;
cb->func = func;
INIT_WORK(&cb->work, vc4_seqno_cb_work);
spin_lock_irqsave(&vc4->job_lock, irqflags);
if (seqno > vc4->finished_seqno) {
cb->seqno = seqno;
list_add_tail(&cb->work.entry, &vc4->seqno_cb_list);
} else {
schedule_work(&cb->work);
}
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return ret;
}
/* Scheduled when any job has been completed, this walks the list of
* jobs that had completed and unrefs their BOs and frees their exec
* structs.
*/
static void
vc4_job_done_work(struct work_struct *work)
{
struct vc4_dev *vc4 =
container_of(work, struct vc4_dev, job_done_work);
vc4_job_handle_completed(vc4);
}
static int
vc4_wait_for_seqno_ioctl_helper(struct drm_device *dev,
uint64_t seqno,
uint64_t *timeout_ns)
{
unsigned long start = jiffies;
int ret = vc4_wait_for_seqno(dev, seqno, *timeout_ns, true);
if ((ret == -EINTR || ret == -ERESTARTSYS) && *timeout_ns != ~0ull) {
uint64_t delta = jiffies_to_nsecs(jiffies - start);
if (*timeout_ns >= delta)
*timeout_ns -= delta;
}
return ret;
}
int
vc4_wait_seqno_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vc4_wait_seqno *args = data;
return vc4_wait_for_seqno_ioctl_helper(dev, args->seqno,
&args->timeout_ns);
}
int
vc4_wait_bo_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
int ret;
struct drm_vc4_wait_bo *args = data;
struct drm_gem_object *gem_obj;
struct vc4_bo *bo;
if (args->pad != 0)
return -EINVAL;
gem_obj = drm_gem_object_lookup(file_priv, args->handle);
if (!gem_obj) {
DRM_ERROR("Failed to look up GEM BO %d\n", args->handle);
return -EINVAL;
}
bo = to_vc4_bo(gem_obj);
ret = vc4_wait_for_seqno_ioctl_helper(dev, bo->seqno,
&args->timeout_ns);
drm_gem_object_unreference_unlocked(gem_obj);
return ret;
}
/**
* Submits a command list to the VC4.
*
* This is what is called batchbuffer emitting on other hardware.
*/
int
vc4_submit_cl_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct drm_vc4_submit_cl *args = data;
struct vc4_exec_info *exec;
int ret = 0;
if ((args->flags & ~VC4_SUBMIT_CL_USE_CLEAR_COLOR) != 0) {
DRM_ERROR("Unknown flags: 0x%02x\n", args->flags);
return -EINVAL;
}
exec = kcalloc(1, sizeof(*exec), GFP_KERNEL);
if (!exec) {
DRM_ERROR("malloc failure on exec struct\n");
return -ENOMEM;
}
mutex_lock(&vc4->power_lock);
if (vc4->power_refcount++ == 0)
ret = pm_runtime_get_sync(&vc4->v3d->pdev->dev);
mutex_unlock(&vc4->power_lock);
if (ret < 0) {
kfree(exec);
return ret;
}
exec->args = args;
INIT_LIST_HEAD(&exec->unref_list);
ret = vc4_cl_lookup_bos(dev, file_priv, exec);
if (ret)
goto fail;
if (exec->args->bin_cl_size != 0) {
ret = vc4_get_bcl(dev, exec);
if (ret)
goto fail;
} else {
exec->ct0ca = 0;
exec->ct0ea = 0;
}
ret = vc4_get_rcl(dev, exec);
if (ret)
goto fail;
/* Clear this out of the struct we'll be putting in the queue,
* since it's part of our stack.
*/
exec->args = NULL;
vc4_queue_submit(dev, exec);
/* Return the seqno for our job. */
args->seqno = vc4->emit_seqno;
return 0;
fail:
vc4_complete_exec(vc4->dev, exec);
return ret;
}
void
vc4_gem_init(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
INIT_LIST_HEAD(&vc4->bin_job_list);
INIT_LIST_HEAD(&vc4->render_job_list);
INIT_LIST_HEAD(&vc4->job_done_list);
INIT_LIST_HEAD(&vc4->seqno_cb_list);
spin_lock_init(&vc4->job_lock);
INIT_WORK(&vc4->hangcheck.reset_work, vc4_reset_work);
setup_timer(&vc4->hangcheck.timer,
vc4_hangcheck_elapsed,
(unsigned long)dev);
INIT_WORK(&vc4->job_done_work, vc4_job_done_work);
mutex_init(&vc4->power_lock);
}
void
vc4_gem_destroy(struct drm_device *dev)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
/* Waiting for exec to finish would need to be done before
* unregistering V3D.
*/
WARN_ON(vc4->emit_seqno != vc4->finished_seqno);
/* V3D should already have disabled its interrupt and cleared
* the overflow allocation registers. Now free the object.
*/
if (vc4->overflow_mem) {
drm_gem_object_unreference_unlocked(&vc4->overflow_mem->base.base);
vc4->overflow_mem = NULL;
}
if (vc4->hang_state)
vc4_free_hang_state(dev, vc4->hang_state);
vc4_bo_cache_destroy(dev);
}
| ./CrossVul/dataset_final_sorted/CWE-388/c/good_3122_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.